diff --git a/.cproject b/.cproject index 67c24b54..e7571c7a 100644 --- a/.cproject +++ b/.cproject @@ -2,20 +2,23 @@ - + + + + @@ -28,11 +31,11 @@ - + - + - - + + - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + @@ -367,25 +131,13 @@ - - - - - - - - - - - - - - - + + + @@ -396,4 +148,13 @@ + + + + + + + + + diff --git a/.gitignore b/.gitignore index c9b50b27..397ee2f5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,254 @@ -*.d +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +[Xx]64/ +[Xx]86/ +[Bb]uild/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml + +# TODO: Un-comment the next line if you do not want to checkin +# your web deploy settings because they may include unencrypted +# passwords +#*.pubxml +*.publishproj + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directory +AppPackages/ +BundleArtifacts/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# LightSwitch generated files +GeneratedArtifacts/ +ModelManifest.xml + +# Paket dependency manager +.paket/paket.exe + +# FAKE - F# Make +.fake/ + + +## Ignore .o and .d files (objects and dependencies) *.o -/bin/* +*.d + +# Don't ignore binary resource files !res/bin/* + +## Ignore Data Folder symlink +Data Folder /core -Debug/ -.vs/cathook/v15/Browse.VC.db \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 48b3e7b9..7317ff1c 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "simple-ipc"] path = simple-ipc url = https://github.com/nullifiedcat/simple-ipc +[submodule "ucccccp"] + path = ucccccp + url = https://github.com/nullifiedcat/ucccccp diff --git a/.settings/language.settings.xml b/.settings/language.settings.xml index 3b6c7dff..fe87ca4d 100644 --- a/.settings/language.settings.xml +++ b/.settings/language.settings.xml @@ -1,6 +1,6 @@ - + @@ -11,37 +11,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.settings/org.eclipse.cdt.codan.core.prefs b/.settings/org.eclipse.cdt.codan.core.prefs index b5248c62..cf61d79d 100644 --- a/.settings/org.eclipse.cdt.codan.core.prefs +++ b/.settings/org.eclipse.cdt.codan.core.prefs @@ -69,3 +69,5 @@ org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem=Warning org.eclipse.cdt.codan.internal.checkers.UnusedVariableDeclarationProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Unused variable declaration in file scope\\")",macro\=>true,exceptions\=>("@(\#)","$Id")} org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem=Error org.eclipse.cdt.codan.internal.checkers.VariableResolutionProblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>true,RUN_ON_INC_BUILD\=>true,RUN_ON_FILE_OPEN\=>false,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>"@suppress(\\"Symbol is not resolved\\")"} +org.eclipse.cdt.qt.core.qtproblem=Warning +org.eclipse.cdt.qt.core.qtproblem.params={launchModes\=>{RUN_ON_FULL_BUILD\=>false,RUN_ON_INC_BUILD\=>false,RUN_ON_FILE_OPEN\=>true,RUN_ON_FILE_SAVE\=>false,RUN_AS_YOU_TYPE\=>true,RUN_ON_DEMAND\=>true},suppression_comment\=>null} diff --git a/.vs/ProjectSettings.json b/.vs/ProjectSettings.json deleted file mode 100644 index f8b48885..00000000 --- a/.vs/ProjectSettings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "CurrentProjectSetting": null -} \ No newline at end of file diff --git a/.vs/VSWorkspaceState.json b/.vs/VSWorkspaceState.json deleted file mode 100644 index 62afdc15..00000000 --- a/.vs/VSWorkspaceState.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "ExpandedNodes": [ - "", - "\\src", - "\\src\\hacks" - ], - "PreviewInSolutionExplorer": false -} \ No newline at end of file diff --git a/.vs/cathook/v15/.suo b/.vs/cathook/v15/.suo deleted file mode 100644 index 831440fc..00000000 Binary files a/.vs/cathook/v15/.suo and /dev/null differ diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite deleted file mode 100644 index 0b906d87..00000000 Binary files a/.vs/slnx.sqlite and /dev/null differ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..4c727443 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,6 @@ +# Contributor Code of Conduct + +This project adheres to No Code of Conduct. We are all adults. We accept anyone's contributions. Nothing else matters. + +For more information please visit the [No Code of Conduct](https://github.com/domgetter/NCoC) homepage. + diff --git a/README.md b/README.md index 5495d965..cec0b7d4 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,99 @@ -# Discord Server -[Official Discord Server (updated link)](https://discord.gg/kvNVNSX) +# Cathook Training Software +![banner](http://i.imgur.com/w96wdtE.png) + +## Discord Server +[Official Discord Server](https://discord.gg/kvNVNSX) + +cathook is a training software designed for Team Fortress 2 for Linux. cathook includes some joke features like + +* Backpack.TF API integration with playerlist GUI, allowing you to see players' inventory values +* Always/Never spycrab +* Ignore Hoovy +* 100% Casual/Comp coin flip +* Encrypted chat +* Emoji ESP +* Fidget Spinner crosshair + +and a lot of useful features, including + +* Anti Backstab with option to say "No" voice command when spy tries to backstab you +* Heal Arrows exploit (overheal an enemy for 1200 health with single huntsman arrow, you can also do it with buildings!) +* Extremely customizable spam (you can make spam lines that'll include name of random dead enemy pyro or sniper) +* Follow Bots +* Working crit hack + +[FULL LIST OF FEATURES HERE](https://github.com/nullifiedcat/cathook/wiki/List-of-features) # INSTALLATION -Ubuntu (and probably Debian) users can run this script: +You can use gcc-7 for compiling cathook if you add `-e CC=gcc-7 CXX=g++-7` to make command line +Ubuntu gcc6 installation: (check if you have gcc-6 installed already by typing `gcc-6 -v` +```bash +sudo apt update && sudo apt install build-essential software-properties-common -y && sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y && sudo apt update && sudo apt install gcc-snapshot g++-6-multilib gcc-6 g++-6 -y ``` -sudo apt update && sudo apt install build-essential software-properties-common -y && sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y && sudo apt update && sudo apt install gcc-snapshot -y && sudo apt update && sudo apt install git libc6-dev gcc-6 g++-6 libc6-dev:i386 g++-6-multilib gdb -y && git clone --recursive https://github.com/nullifiedcat/cathook && cd cathook && make -j4 + +Ubuntu other dependencies installation: + +```bash +sudo apt update && sudo apt install git libssl-dev:i386 libc6-dev:i386 gdb libsdl2-dev libglew-dev:i386 libfreetype6-dev:i386 -y +``` + + +Arch gcc6 & dependencies installation: +```bash +sudo pacman -Syu && sudo pacman -S gdb gdb-common glew1.10 lib32-glew1.10 rsync --noconfirm && yes | sudo pacman -U https://archive.archlinux.org/packages/g/gcc-multilib/gcc-multilib-6.3.1-2-x86_64.pkg.tar.xz https://archive.archlinux.org/packages/g/gcc-libs-multilib/gcc-libs-multilib-6.3.1-2-x86_64.pkg.tar.xz https://archive.archlinux.org/packages/l/lib32-gcc-libs/lib32-gcc-libs-6.3.1-2-x86_64.pkg.tar.xz +``` + +If you don't use Ubuntu or Arch (or if Arch script gets outdated), here's the list of what cathook requires: + +* `gcc-6` +* `g++-6` +* `gcc-6-multilib` +* `g++-6-multilib` +* `gdb` (for the injection script, you can use different injector if you want) +* `libssl-dev:i386` +* `libc6-dev:i386` +* `libsdl2-dev` +* `libglew-dev:i386` +* `libfreetype6-dev:i386` +* `rsync` (only for copying shaders/fonts to tf2 data directory, `update-data` script) + + +Cathook installation script: +```bash +git clone --recursive https://github.com/nullifiedcat/cathook && cd cathook && bash build-tf2 && bash update-data ``` **Errors while installing?** -`/usr/include/c++/5/string:38:28: fatal error: bits/c++config.h: No such file or directory` - You don't have g++6 or g++6 multilib installed correctly +`/usr/include/c++/5/string:38:28: fatal error: bits/c++config.h: No such file or directory` +You don't have gcc-multilib-6 installed correctly. -`src/: fatal error: mathlib/vector.h: No such file or directory` - You didn't download Source SDK. **DO NOT DOWNLOAD CATHOOK USING "DOWNLOAD .ZIP" FROM GITHUB. USE git clone --recursive**! +`src/: fatal error: mathlib/vector.h: No such file or directory` +You didn't download Source SDK. **DO NOT DOWNLOAD CATHOOK USING "DOWNLOAD .ZIP" FROM GITHUB. USE git clone --recursive!** -If you are using other distro, make sure to have g++-6, gdb, libc6 and build essentials installed. +If you are using another distro, make sure to have g++-6, gdb, libc6 and build essentials installed. ## Updating cathook Run the `update` script in cathook folder. -## Injection -`sudo ./attach` to attach to tf2 process (can take argument number 0-N - # of tf2 instance to attach to (for bots)) +Cathook requires the shader folder provided in order to launch properly. To install this, run the `update-data` script. This will create a sym-link for the required folders. +If you wish to do this manually, copy the tf-settings folder inside Cathook into your Team Fortress 2 folder and rename it to "cathook". +You will want to update these files if you wish to have an updated menu. -`sudo ./attach-backtrace` to attach and print backtrace if tf2 crashes. Some users reported that this method makes you get less FPS ingame. +## Injection +`sudo ./attach` to attach cathook into TF2. Optionally, you can provide an argument number (0-n - #) to provide the TF2 process ID (for bots). + +`sudo ./attach-backtrace` to attach and print backtrace incase TF2 crashes. Some users report that this causes FPS drop in-game. This is recommended to grab a log of what went wrong if Cathook is crashing on you. ## Followbots +`cathook-ipc-server` allows you to run and control Followbots to do your evil bidding in-game. The installation for Followbots is quite complex, and will not be covered on this page. Obviously, you must have several user accounts ready to run TF2. +A guide for Followbots can be found here: [How to setup and use followbots.](https://www.youtube.com/watch?v=kns5-nw7xUg) +You may also ask someone in our discord server to help you out. -Followbot installation is quite complex and I won't cover it fully here. -You have to have several user accounts ready to run tf2 - use google for that. -You can ask someone in my discord server for help with installation. -To control followbots, you need to download and install `cathook-ipc-server`. - -### Followbot server installation script +The installation script is as followed: +```bash +git clone --recursive https://github.com/nullifiedcat/cathook-ipc-server && cd cathook-ipc-server && make -j4 ``` -git clone --recursive https://github.com/nullifiedcat/cathook-ipc-server && \ -cd cathook-ipc-server && \ -make -j4 -``` -### Updating script is the same as updating cathook - -### Running followbot server -`./bin/cathook-ipc-server` or `./bin/cathook-ipc-server &>/dev/null &` to run it in background +To run the Followbot server, run `./bin/cathook-ipc-server`. You can also use `./bin/cathook-ipc-server &>/dev/null &` to run it in background. diff --git a/TODO b/TODO index 9075f1e7..4c0cd318 100644 --- a/TODO +++ b/TODO @@ -1,80 +1,141 @@ -MULTIPLATFORM: +//==================================================================================================// +//Big TODO list for cathook // +//Organized by Julianacat // +//==================================================================================================// -Signature Scanner -Whole IPC thing | actually, no. cathook for windows WON'T have followbots/ipc. -Signatures and offsets -File handling (playerlist, spam, etc...) -CMake? -------------====----------- -alias clearcond "host_timescale 300;wait 500;host_timescale 1" -alias clearcond_taunt "taunt;wait 50;host_timescale 300;wait 500;host_timescale 1" -bind l clearcond_taunt +//----------------------------------------------------------------------------------------------------------------------// +//Aimbot/Triggerbot // +//------------------------------------------------------------------------------------------------------------------// // + // // +Hook + Aimbot FIX // // + // // +no aim sapper // // + // // +Make hacks respect Mannpower powerups and other conditions when calcuating damage, hitbox and prioritizing targets // // +Proper AutoHitbox, Isnt this already a thing?? // // + // // +Flare aim on fire // // +Improve Projectile Aimbot. A lot. // // +ProjPredOrigin // // +MAX -> MIN priority // // + // // +Hunter Rifle? // // + // // +AutoDetonator // // + // // +No AutoShoot when disguised // // +Ambassador bodyshotting // // +No Trigger Mediguns // // +More projectile weapons aimbot (wrap assassin, wrangler, stickybomb, airstrike) // // +Auto trigger DR before rockets // // + // // +Make make sentrys slightly lower priority (for getting those pesky turtle engies) // // + // // +Make building aimbot compensate for gravity on projectile weapons // // + // // +add Spectator Silent for projectile weapons // // + // // +Improve aimbot accuracy // // + // // +Add Multipoint (Take hitbox, shrink it, then use corners as points to check) // // + // // +Make ambasador check rely on wait for charge user setting // // + // // +//------------------------------------------------------------------------------------------------------------------// // +// // +//----------------------------------------------------------------------------------------------------------------------// + + -TF2C teams -TF2C merc -HL2DM teams +//----------------------------------------------------------------------------------------------------------------------// +//Visuals/GUI // +//------------------------------------------------------------------------------------------------------------------// // + // // +Display on the left // // + // // +make gui color change // // + // // +Cheat status menu (A gui to display enabled/disabled states of user settings for when the menu is off) // // + // // +add teleporter count down // // +add spy cloak esp // // + // // +Make ubercharge esp color RGB when fully charged // // + // // +fullbright toggle // // + // // +FLAG ESP? // // + // // +ESP Icons // // +ESP Distance sort // // +Show sapped buildings in ESP // // +halloween medkits // // +carrying esp // // +Tracers/Spy Cam // // + // // +//------------------------------------------------------------------------------------------------------------------// // +// // +//----------------------------------------------------------------------------------------------------------------------// -Fix Autosticky -Proj Aimbot -fullbright toggle -Hunter Rifle -inspect shit -TTS -noise spam -team name spam (pre round team name spam thing) -insta taunt (taunts for like .5 ms and then you can do it again lithium has it) -auto vacc -namesteal -autovote -voice command spam (not like 1 voice command every 1 ms but like just spamming it on the menu) -dominatesay assistsay worldsay -AutoDetonator +//----------------------------------------------------------------------------------------------------------------------// +//Chat and Related // +//------------------------------------------------------------------------------------------------------------------// // + // // +TTS // // +namesteal // // +autovote // // + // // +dominatesay assistsay worldsay // // +InsultSpam // // + // // +//------------------------------------------------------------------------------------------------------------------// // +// // +//----------------------------------------------------------------------------------------------------------------------// -ProjPredOrigin -MAX -> MIN priority -Deflected by enemy player - Aim Stickies -FLAG ESP -no aim sapper -Improve Projectile Aimbot. A lot. -Proper AutoHitbox -Smoothe the smooth aim -Display on the left -Flare aim on fire -Aim Sticky -Proj Pred visuals -Hook + Aimbot FIX -ESP Icons -ESP Distance sort -Show sapped buildings in ESP -Make hacks respect Mannpower powerups and other conditions when calcuating damage, hitbox and prioritizing targets -Fake Lag -Engine Prediction -AutoSticky improve -No AutoShoot when disguised -Ambassador bodyshotting -No Trigger Mediguns -More projectile weapons aimbot (wrap assassin, wrangler, stickybomb, airstrike) -Auto trigger DR before rockets -Sticky vischeck -InsultSpam -Critical rifles bodyshotting -FLAG ESP -Spy alert uses angles -halloween medkits -carrying esp -Tracers/Spy Cam -Bodyshot if not zoomed -Proper medic followbot AI -Bot option for aiming at owner's prey (just for fun) -Bot pathfinding & navigation files system -SkinChanger -Proper entity classes (actually I might just use a lot of helper functions taking IClientEntity* as first arg) -Priority system optimization and testing -General optimization and refactoring -Bone ESP -XorString or something to make it harder to detect. + + +//----------------------------------------------------------------------------------------------------------------------// +//Followbots // +//------------------------------------------------------------------------------------------------------------------// // + // // +Proper medic followbot AI, breadcrumb followbot is good but a nav system would be better // // + // // +Bot option for aiming at owner's prey (just for fun) // // +Bot pathfinding & navigation files system // // +Proper entity classes (actually I might just use a lot of helper functions taking IClientEntity* as first arg) // // + // // +//------------------------------------------------------------------------------------------------------------------// // +// // +//----------------------------------------------------------------------------------------------------------------------// + + + +//----------------------------------------------------------------------------------------------------------------------// +//Misc // +//------------------------------------------------------------------------------------------------------------------// // + // // +Proper Fake Lag // // +Add auto-strafe // // + // // +Fix achievement hack getting blocked with sv_cheats // // + // // +Spy alert uses angles // // + // // +Add ignore gunslinger to melee crit hack // // + // // +Priority system optimization and testing // // +General optimization and refactoring // // + // // +XorString or something to make it harder to detect. // // + // // +TF2C teams // // +TF2C merc // // +HL2DM teams // // + // // +//------------------------------------------------------------------------------------------------------------------// // +// // +//----------------------------------------------------------------------------------------------------------------------// diff --git a/attach b/attach index 29d457f6..50bccc76 100755 --- a/attach +++ b/attach @@ -24,17 +24,36 @@ echo Attaching to "$proc" #sudo ./detach $inst bin/libcathook.so -if grep -q "$(realpath bin/libcathook.so)" /proc/"$proc"/maps; then - echo already loaded - exit -fi +#if grep -q "$(realpath bin/libcathook.so)" /proc/"$proc"/maps; then +# echo already loaded +# exit +#fi + +# pBypass for crash dumps being sent +# You may also want to consider using -nobreakpad in your launch options. +sudo rm -rf /tmp/dumps # Remove if it exists +sudo mkdir /tmp/dumps # Make it as root +sudo chmod 000 /tmp/dumps # No permissions + +FILENAME="/tmp/.gl$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 6 | head -n 1)" + +cp "bin/libcathook.so" "$FILENAME" + +echo loading "$FILENAME" to "$proc" + +sudo killall -19 steam +sudo killall -19 steamwebhelper -echo loading "$(realpath bin/libcathook.so)" to "$proc" gdb -n -q -batch \ -ex "attach $proc" \ -ex "set \$dlopen = (void*(*)(char*, int)) dlopen" \ - -ex "call \$dlopen(\"$(realpath bin/libcathook.so)\", 1)" \ + -ex "call \$dlopen(\"$FILENAME\", 1)" \ -ex "call dlerror()" \ -ex 'print (char *) $2' \ -ex "detach" \ -ex "quit" + +rm $FILENAME + +sudo killall -18 steamwebhelper +sudo killall -18 steam \ No newline at end of file diff --git a/attach-pid b/attach-pid index 4e276ede..c91d6152 100755 --- a/attach-pid +++ b/attach-pid @@ -1,8 +1,9 @@ #!/usr/bin/env bash -proc=$1 - -echo Attaching to "$proc" +proc=${1:-$(ps $(pidof gameoverlayui) | tail -n1 | cut -d\- -f2 | cut -d\ -f2)} +if ! [[ $proc =~ ^[0-9]+$ ]]; then + echo "Couldn't find process! Are you sure a game is running?" >&2; exit 1 +fi if grep -q "$(realpath bin/libcathook.so)" /proc/"$proc"/maps; then echo already loaded diff --git a/attach-user b/attach-user new file mode 100755 index 00000000..7d999c17 --- /dev/null +++ b/attach-user @@ -0,0 +1,46 @@ +#!/usr/bin/env bash + +user=$USER + +if [ "$#" == 1 ]; then + user=$1 +fi + +proc="0" + +for pid in $(pidof hl2_linux) +do + if sudo -H -u $user kill -0 $pid + then + proc=$pid + break + fi +done + + +if [ "$proc" == "0" ] +then + echo "TF2 for $user is not running" + continue +fi + +echo Attaching to "$proc" + +FILENAME=$(realpath "bin/libcathook.so") + +echo loading "$FILENAME" to "$proc" + +sudo killall -19 steam +sudo killall -19 steamwebhelper + +sudo gdb -n -q -batch \ + -ex "attach $proc" \ + -ex "set \$dlopen = (void*(*)(char*, int)) dlopen" \ + -ex "call \$dlopen(\"$FILENAME\", 1)" \ + -ex "call dlerror()" \ + -ex 'print (char *) $2' \ + -ex "detach" \ + -ex "quit" + +sudo killall -18 steamwebhelper +sudo killall -18 steam \ No newline at end of file diff --git a/build-debug-tf2 b/build-debug-tf2 new file mode 100755 index 00000000..fbe034ec --- /dev/null +++ b/build-debug-tf2 @@ -0,0 +1 @@ +make -j4 -e GAME=tf2 BUILD_DEBUG=1 \ No newline at end of file diff --git a/build-tf2 b/build-tf2 new file mode 100755 index 00000000..a6dfa43d --- /dev/null +++ b/build-tf2 @@ -0,0 +1,2 @@ +make -j4 -e GAME=tf2 NO_WARNINGS=1 +strip --strip-all bin/libcathook.so \ No newline at end of file diff --git a/cathook.vcxproj.user b/cathook.vcxproj.user deleted file mode 100644 index 0b0f24d5..00000000 --- a/cathook.vcxproj.user +++ /dev/null @@ -1,6 +0,0 @@ - - - - true - - \ No newline at end of file diff --git a/classdump-dab.txt b/classdump-dab.txt new file mode 100644 index 00000000..874dd965 --- /dev/null +++ b/classdump-dab.txt @@ -0,0 +1,185 @@ +[131] CTEFireBullets +[94] CSDKTeam_Deathmatch +[95] CSDKTeam_Red +[93] CSDKTeam_Blue +[96] CSDKTeam_Unassigned +[92] CSDKTeam +[90] CSDKPlayerResource +[91] CSDKRagdoll +[89] CSDKPlayer +[143] CTEPlayerAnimEvent +[100] CSparkler +[85] CRatRaceWaypoint +[25] CBriefcaseCaptureZone +[24] CBriefcase +[0] CWeaponCubemap +[163] CWeaponCycler +[84] CRagdollPropAttached +[83] CRagdollProp +[158] CWaterBullet +[52] CFuncMonitor +[174] CWorld +[159] CWaterLODControl +[156] CVGuiScreen +[80] CPropJeep +[0] CPropVehicleChoreoGeneric +[155] CTEWorldDecal +[152] CTESpriteSpray +[151] CTESprite +[150] CTESparks +[149] CTESmoke +[147] CTEShowLine +[145] CTEProjectedDecal +[144] CTEPlayerDecal +[142] CTEPhysicsProp +[141] CTEParticleSystem +[140] CTEMuzzleFlash +[138] CTELargeFunnel +[137] CTEKillPlayerAttachments +[136] CTEImpact +[135] CTEGlowSprite +[146] CTEShatterSurface +[133] CTEFootprintDecal +[132] CTEFizz +[130] CTEExplosion +[129] CTEEnergySplash +[128] CTEEffectDispatch +[127] CTEDynamicLight +[125] CTEDecal +[124] CTEClientProjectile +[123] CTEBubbleTrail +[122] CTEBubbles +[121] CTEBSPDecal +[120] CTEBreakModel +[119] CTEBloodStream +[118] CTEBloodSprite +[117] CTEBeamSpline +[116] CTEBeamRingPoint +[115] CTEBeamRing +[114] CTEBeamPoints +[113] CTEBeamLaser +[112] CTEBeamFollow +[111] CTEBeamEnts +[110] CTEBeamEntPoint +[109] CTEBaseBeam +[108] CTEArmorRicochet +[139] CTEMetalSparks +[153] CTest_ProxyToggle_Networkable +[154] CTestTraceline +[148] CTesla +[107] CTeam +[106] CSun +[105] CSteamJet +[66] CParticlePerformanceMonitor +[101] CSpotlightEnd +[175] DustTrail +[44] CFireTrail +[181] SporeTrail +[180] SporeExplosion +[178] RocketTrail +[179] SmokeTrail +[99] CSmokeStack +[98] CSlideshowDisplay +[97] CShadowControl +[87] CSceneEntity +[86] CRopeKeyframe +[82] CRagdollManager +[81] CPropVehicleDriveable +[71] CPhysicsPropMultiplayer +[69] CPhysBoxMultiplayer +[16] CBasePropDoor +[30] CDynamicProp +[76] CPointCommentaryNode +[75] CPointCamera +[74] CPlayerResource +[73] CPlasma +[72] CPhysMagnet +[70] CPhysicsProp +[68] CPhysBox +[67] CParticleSystem +[177] ParticleSmokeGrenade +[65] CParticleFire +[176] MovieExplosion +[64] CMaterialModifyControl +[63] CLightGlow +[62] CInfoOverlayAccessor +[134] CTEGaussExplosion +[57] CFuncTrackTrain +[56] CFuncSmokeVolume +[55] CFuncRotating +[54] CFuncReflectiveGlass +[53] CFuncOccluder +[48] CFunc_LOD +[126] CTEDust +[47] CFunc_Dust +[50] CFuncConveyor +[23] CBreakableSurface +[49] CFuncAreaPortalWindow +[45] CFish +[33] CEntityFlame +[43] CFireSmoke +[41] CEnvTonemapController +[39] CEnvScreenEffect +[40] CEnvScreenOverlay +[37] CEnvProjectedTexture +[36] CEnvParticleScript +[46] CFogController +[34] CEntityParticleTrail +[32] CEntityDissolve +[38] CEnvQuadraticBeam +[31] CEmbers +[42] CEnvWind +[78] CPrecipitation +[29] CDynamicLight +[27] CColorCorrectionVolume +[26] CColorCorrection +[22] CBreakableProp +[18] CBaseTempEntity +[14] CBasePlayer +[10] CBaseFlex +[9] CBaseEntity +[8] CBaseDoor +[6] CBaseCombatCharacter +[5] CBaseAnimatingOverlay +[21] CBoneFollower +[4] CBaseAnimating +[61] CInfoLightingRelative +[0] CAI_BaseNPC +[59] CHandleTest +[0] CTeamplayRoundBasedRulesProxy +[104] CSpriteTrail +[103] CSpriteOriented +[102] CSprite +[173] CWeaponShotgun +[171] CWeaponSDKBase +[170] CWeaponMP5K +[169] CWeaponMossberg +[168] CWeaponMAC10 +[167] CWeaponM1911 +[166] CWeaponM16 +[165] CWeaponGrenade +[164] CWeaponFAL +[162] CWeaponCrowbar +[161] CWeaponBrawl +[160] CWeaponBeretta +[17] CBaseSDKGrenade +[3] CAkimboM1911 +[2] CAkimboBeretta +[1] CAkimboBase +[172] CWeaponSDKMelee +[88] CSDKGameRulesProxy +[12] CBaseGrenadeProjectile +[28] CDAViewModel +[79] CPredictedViewModel +[77] CPoseController +[58] CGameRulesProxy +[60] CInfoLadderDismount +[51] CFuncLadder +[35] CEnvDetailController +[20] CBeam +[19] CBaseViewModel +[15] CBaseProjectile +[13] CBaseParticleEntity +[11] CBaseGrenade +[7] CBaseCombatWeapon +[157] CVoteController diff --git a/detach-backtrace b/detach-backtrace new file mode 100755 index 00000000..407da3f2 --- /dev/null +++ b/detach-backtrace @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +line=$(pidof hl2_linux) +arr=($line) +inst=$1 +if [ $# == 0 ]; then + inst=0 +fi + +if [ ${#arr[@]} == 0 ]; then + echo TF2 isn\'t running! + exit +fi + +if [ $inst -gt ${#arr[@]} ] || [ $inst == ${#arr[@]} ]; then + echo wrong index! + exit +fi + +echo Running instances: "${arr[@]}" +echo Detaching from "${arr[$1]}" + +if grep -q "$(realpath bin/libcathook.so)" /proc/"${arr[$1]}"/maps; then + gdb -n -q -batch \ + -ex "attach ${arr[$1]}" \ + -ex "set \$dlopen = (void*(*)(char*, int)) dlopen" \ + -ex "set \$dlclose = (int(*)(void*)) dlclose" \ + -ex "set \$library = \$dlopen(\"$(realpath bin/libcathook.so)\", 6)" \ + -ex "print \$library" \ + -ex "sharedlibrary ." \ + -ex "call \$dlclose(\$library)" \ + -ex "call \$dlclose(\$library)" \ + -ex "continue" \ + -ex "backtrace" + echo "Detached" +else + echo "not found!" +fi diff --git a/full-class-table.json b/full-class-table.json index 7a6a8524..acbbe7ed 100644 --- a/full-class-table.json +++ b/full-class-table.json @@ -1 +1 @@ -{"CTETFParticleEffect":true,"CTETFExplosion":true,"CTETFBlood":true,"CTFTankBoss":true,"CTFBaseBoss":true,"CBossAlpha":true,"CZombie":true,"CMerasmusDancer":true,"CMerasmus":true,"CHeadlessHatman":true,"CEyeballBoss":true,"CTFWeaponSapper":true,"CTFWeaponBuilder":true,"C_TFWeaponBuilder":true,"CTFTeam":true,"CTFTauntProp":true,"CTFProjectile_Rocket":true,"CTFProjectile_Flare":true,"CTFProjectile_EnergyBall":true,"CTFProjectile_GrapplingHook":true,"CTFProjectile_HealingBolt":true,"CTFProjectile_Arrow":true,"CTFPlayerResource":true,"CTFPlayer":true,"CTFRagdoll":true,"CTEPlayerAnimEvent":true,"CTFPasstimeLogic":true,"CPasstimeBall":true,"CTFObjectiveResource":true,"CTFGlow":true,"CTEFireBullets":true,"CTFBuffBanner":true,"CTFAmmoPack":true,"CObjectTeleporter":true,"CObjectSentrygun":true,"CTFProjectile_SentryRocket":true,"CObjectSapper":true,"CObjectCartDispenser":true,"CObjectDispenser":true,"CMonsterResource":true,"CFuncRespawnRoomVisualizer":true,"CFuncRespawnRoom":true,"CFuncPasstimeGoal":true,"CFuncForceField":true,"CCaptureZone":true,"CCurrencyPack":true,"CBaseObject":true,"CTFBotHintEngineerNest":true,"CBotNPCMinion":true,"CBotNPC":true,"CRagdollPropAttached":true,"CRagdollProp":true,"NextBotCombatCharacter":true,"CWaterBullet":true,"CFuncMonitor":true,"CWorld":true,"CWaterLODControl":true,"CVGuiScreen":true,"CPropJeep":true,"CPropVehicleChoreoGeneric":true,"CTEWorldDecal":true,"CTESpriteSpray":true,"CTESprite":true,"CTESparks":true,"CTESmoke":true,"CTEShowLine":true,"CTEProjectedDecal":true,"CTEPlayerDecal":true,"CTEPhysicsProp":true,"CTEParticleSystem":true,"CTEMuzzleFlash":true,"CTELargeFunnel":true,"CTEKillPlayerAttachments":true,"CTEImpact":true,"CTEGlowSprite":true,"CTEShatterSurface":true,"CTEFootprintDecal":true,"CTEFizz":true,"CTEExplosion":true,"CTEEnergySplash":true,"CTEEffectDispatch":true,"CTEDynamicLight":true,"CTEDecal":true,"CTEClientProjectile":true,"CTEBubbleTrail":true,"CTEBubbles":true,"CTEBSPDecal":true,"CTEBreakModel":true,"CTEBloodStream":true,"CTEBloodSprite":true,"CTEBeamSpline":true,"CTEBeamRingPoint":true,"CTEBeamRing":true,"CTEBeamPoints":true,"CTEBeamLaser":true,"CTEBeamFollow":true,"CTEBeamEnts":true,"CTEBeamEntPoint":true,"CTEBaseBeam":true,"CTEArmorRicochet":true,"CTEMetalSparks":true,"CTest_ProxyToggle_Networkable":true,"CTestTraceline":true,"CTesla":true,"CTeamTrainWatcher":true,"CBaseTeamObjectiveResource":true,"CTeam":true,"CSun":true,"CSteamJet":true,"CParticlePerformanceMonitor":true,"CSpotlightEnd":true,"DustTrail":true,"CFireTrail":true,"SporeTrail":true,"SporeExplosion":true,"RocketTrail":true,"SmokeTrail":true,"CSmokeStack":true,"CSlideshowDisplay":true,"CShadowControl":true,"CSceneEntity":true,"CRopeKeyframe":true,"CRagdollManager":true,"CPropVehicleDriveable":true,"CPhysicsPropMultiplayer":true,"CPhysBoxMultiplayer":true,"CBasePropDoor":true,"CDynamicProp":true,"CPointCommentaryNode":true,"CPointCamera":true,"CPlayerResource":true,"CPlasma":true,"CPhysMagnet":true,"CPhysicsProp":true,"CPhysBox":true,"CParticleSystem":true,"ParticleSmokeGrenade":true,"CParticleFire":true,"MovieExplosion":true,"CMaterialModifyControl":true,"CLightGlow":true,"CInfoOverlayAccessor":true,"CTEGaussExplosion":true,"CFuncTrackTrain":true,"CFuncSmokeVolume":true,"CFuncRotating":true,"CFuncReflectiveGlass":true,"CFuncOccluder":true,"CFunc_LOD":true,"CTEDust":true,"CFunc_Dust":true,"CFuncConveyor":true,"CBreakableSurface":true,"CFuncAreaPortalWindow":true,"CFish":true,"CEntityFlame":true,"CFireSmoke":true,"CEnvTonemapController":true,"CEnvScreenEffect":true,"CEnvScreenOverlay":true,"CEnvProjectedTexture":true,"CEnvParticleScript":true,"CFogController":true,"CEntityParticleTrail":true,"CEntityDissolve":true,"CEnvQuadraticBeam":true,"CEmbers":true,"CEnvWind":true,"CPrecipitation":true,"CDynamicLight":true,"CColorCorrectionVolume":true,"CColorCorrection":true,"CBreakableProp":true,"CBaseTempEntity":true,"CBasePlayer":true,"CBaseFlex":true,"CBaseEntity":true,"CBaseDoor":true,"CBaseCombatCharacter":true,"CBaseAnimatingOverlay":true,"CBoneFollower":true,"CBaseAnimating":true,"CInfoLightingRelative":true,"CAI_BaseNPC":true,"CWeaponIFMSteadyCam":true,"CWeaponIFMBaseCamera":true,"CWeaponIFMBase":true,"CTFWearableLevelableItem":true,"CTFWearableDemoShield":true,"CTFWearableRobotArm":true,"CTFRobotArm":true,"CTFWrench":true,"CTFProjectile_ThrowableBreadMonster":true,"CTFProjectile_ThrowableBrick":true,"CTFProjectile_ThrowableRepel":true,"CTFProjectile_Throwable":true,"CTFThrowable":true,"CTFSyringeGun":true,"CTFKatana":true,"CTFSword":true,"CSniperDot":true,"CTFSniperRifleClassic":true,"CTFSniperRifleDecap":true,"CTFSniperRifle":true,"CTFChargedSMG":true,"CTFSMG":true,"CTFShovel":true,"CTFShotgunBuildingRescue":true,"CTFPEPBrawlerBlaster":true,"CTFSodaPopper":true,"CTFShotgun_Revenge":true,"CTFScatterGun":true,"CTFShotgun_Pyro":true,"CTFShotgun_HWG":true,"CTFShotgun_Soldier":true,"CTFShotgun":true,"CTFCrossbow":true,"CTFRocketLauncher_Mortar":true,"CTFRocketLauncher_AirStrike":true,"CTFRocketLauncher_DirectHit":true,"CTFRocketLauncher":true,"CTFRevolver":true,"CTFDRGPomson":true,"CTFRaygun":true,"CTFPistol_ScoutSecondary":true,"CTFPistol_ScoutPrimary":true,"CTFPistol_Scout":true,"CTFPistol":true,"CTFPipebombLauncher":true,"CTFWeaponPDA_Spy":true,"CTFWeaponPDA_Engineer_Destroy":true,"CTFWeaponPDA_Engineer_Build":true,"CTFWeaponPDAExpansion_Teleporter":true,"CTFWeaponPDAExpansion_Dispenser":true,"CTFWeaponPDA":true,"CPasstimeGun":true,"CTFParticleCannon":true,"CTFParachute_Secondary":true,"CTFParachute_Primary":true,"CTFParachute":true,"CTFMinigun":true,"CTFMedigunShield":true,"CWeaponMedigun":true,"CTFMechanicalArm":true,"CTFLunchBox_Drink":true,"CTFLunchBox":true,"CLaserDot":true,"CTFLaserPointer":true,"CTFKnife":true,"CTFProjectile_Cleaver":true,"CTFProjectile_JarMilk":true,"CTFProjectile_Jar":true,"CTFCleaver":true,"CTFJarMilk":true,"CTFJar":true,"CTFWeaponInvis":true,"CTFGrenadePipebombProjectile":true,"CTFCannon":true,"CTFGrenadeLauncher":true,"CTFGrapplingHook":true,"CTFFlareGun_Revenge":true,"CTFFlareGun":true,"CTFFlameRocket":true,"CTFFlameThrower":true,"CTFFists":true,"CTFFireAxe":true,"CTFCompoundBow":true,"CTFClub":true,"CTFBuffItem":true,"CTFStickBomb":true,"CTFBottle":true,"CTFBonesaw":true,"CTFBall_Ornament":true,"CTFStunBall":true,"CTFBat_Giftwrap":true,"CTFBat_Wood":true,"CTFBat_Fish":true,"CTFBat":true,"CTFBaseRocket":true,"CTFWeaponBaseMerasmusGrenade":true,"CTFWeaponBaseMelee":true,"CTFWeaponBaseGun":true,"CTFWeaponBaseGrenadeProj":true,"CTFWeaponBase":true,"CTFViewModel":true,"CRobotDispenser":true,"CTFRobotDestruction_Robot":true,"CTFReviveMarker":true,"CTFPumpkinBomb":true,"CTFProjectile_EnergyRing":true,"CTFBaseProjectile":true,"CBaseObjectUpgrade":true,"CMannVsMachineStats":true,"CTFRobotDestructionLogic":true,"CTFRobotDestruction_RobotGroup":true,"CTFRobotDestruction_RobotSpawn":true,"CTFPlayerDestructionLogic":true,"CPlayerDestructionDispenser":true,"CTFMinigameLogic":true,"CTFHalloweenMinigame_FallingPlatforms":true,"CTFHalloweenMinigame":true,"CTFMiniGame":true,"CTFWearableVM":true,"CTFWearable":true,"CTFPowerupBottle":true,"CTFItem":true,"CHalloweenSoulPack":true,"CTFGenericBomb":true,"CBonusRoundLogic":true,"CTFGameRulesProxy":true,"CTFDroppedWeapon":true,"CTFProjectile_SpellKartBats":true,"CTFProjectile_SpellKartOrb":true,"CTFHellZap":true,"CTFProjectile_SpellLightningOrb":true,"CTFProjectile_SpellTransposeTeleport":true,"CTFProjectile_SpellMeteorShower":true,"CTFProjectile_SpellSpawnBoss":true,"CTFProjectile_SpellMirv":true,"CTFProjectile_SpellPumpkin":true,"CTFProjectile_SpellSpawnHorde":true,"CTFProjectile_SpellSpawnZombie":true,"CTFProjectile_SpellBats":true,"CTFProjectile_SpellFireball":true,"CTFSpellBook":true,"CHightower_TeleportVortex":true,"CTeleportVortex":true,"CHalloweenGiftPickup":true,"CBonusDuckPickup":true,"CHalloweenPickup":true,"CCaptureFlagReturnIcon":true,"CCaptureFlag":true,"CBonusPack":true,"CHandleTest":true,"CTeamRoundTimer":true,"CTeamplayRoundBasedRulesProxy":true,"CSpriteTrail":true,"CSpriteOriented":true,"CSprite":true,"CPoseController":true,"CGameRulesProxy":true,"CInfoLadderDismount":true,"CFuncLadder":true,"CEnvDetailController":true,"CTFWearableItem":true,"CEconWearable":true,"CBaseAttributableItem":true,"CEconEntity":true,"CBeam":true,"CBaseViewModel":true,"CBaseProjectile":true,"CBaseParticleEntity":true,"CBaseGrenade":true,"CBaseCombatWeapon":true,"CVoteController":true,"CTEHL2MPFireBullets":true,"CHL2MPRagdoll":true,"CHL2MP_Player":true,"CWeaponCitizenSuitcase":true,"CWeaponCitizenPackage":true,"CWeaponAlyxGun":true,"CWeaponCubemap":true,"CWeaponGaussGun":true,"CWeaponAnnabelle":true,"CFlaregun":true,"CWeaponBugBait":true,"CWeaponBinoculars":true,"CWeaponCycler":true,"CCrossbowBolt":true,"CPropVehiclePrisonerPod":true,"CPropCrane":true,"CPropCannon":true,"CPropAirboat":true,"CFlare":true,"CTEConcussiveExplosion":true,"CNPC_Strider":true,"CScriptIntro":true,"CRotorWashEmitter":true,"CPropCombineBall":true,"CPlasmaBeamNode":true,"CNPC_RollerMine":true,"CNPC_Manhack":true,"CNPC_CombineGunship":true,"CNPC_AntlionGuard":true,"CInfoTeleporterCountdown":true,"CMortarShell":true,"CEnvStarfield":true,"CEnvHeadcrabCanister":true,"CAlyxEmpEffect":true,"CCorpse":true,"CCitadelEnergyCore":true,"CHL2_Player":true,"CBaseHLBludgeonWeapon":true,"CHLSelectFireMachineGun":true,"CHLMachineGun":true,"CBaseHelicopter":true,"CNPC_Barney":true,"CNPC_Barnacle":true,"AR2Explosion":true,"CTEAntlionDust":true,"CVortigauntEffectDispel":true,"CVortigauntChargeToken":true,"CNPC_Vortigaunt":true,"CPredictedViewModel":true,"CWeaponStunStick":true,"CWeaponSMG1":true,"CWeapon_SLAM":true,"CWeaponShotgun":true,"CWeaponRPG":true,"CWeaponPistol":true,"CWeaponPhysCannon":true,"CHL2MPMachineGun":true,"CBaseHL2MPCombatWeapon":true,"CBaseHL2MPBludgeonWeapon":true,"CWeaponHL2MPBase":true,"CWeaponFrag":true,"CWeaponCrowbar":true,"CWeaponCrossbow":true,"CWeaponAR2":true,"CWeapon357":true,"CHL2MPGameRulesProxy":true,"CHalfLife2Proxy":true,"CBaseHLCombatWeapon":true,"CTFVehicle":true,"CTFBaseDMPowerup":true,"CWeaponSpawner":true,"CTFUmbrella":true,"CTFTranq":true,"CTFSMG_Primary":true,"CTFRevolver_Secondary":true,"CTFNailgun":true,"CTFHunterRifle":true,"CTFHeavyArtillery":true,"CTFHammerfists":true,"CTFCrowbar":true,"CTFChainsaw":true,"CTEPlantBomb":true,"CTERadioIcon":true,"CPlantedC4":true,"CCSTeam":true,"CCSPlayerResource":true,"CCSPlayer":true,"CCSRagdoll":true,"CHostage":true,"CWeaponXM1014":true,"CWeaponUSP":true,"CWeaponUMP45":true,"CWeaponTMP":true,"CSmokeGrenade":true,"CWeaponSG552":true,"CWeaponSG550":true,"CWeaponScout":true,"CWeaponP90":true,"CWeaponP228":true,"CWeaponMP5Navy":true,"CWeaponMAC10":true,"CWeaponM4A1":true,"CWeaponM3":true,"CWeaponM249":true,"CKnife":true,"CHEGrenade":true,"CWeaponGlock":true,"CWeaponGalil":true,"CWeaponG3SG1":true,"CFlashbang":true,"CWeaponFiveSeven":true,"CWeaponFamas":true,"CWeaponElite":true,"CDEagle":true,"CWeaponCSBaseGun":true,"CWeaponCSBase":true,"CC4":true,"CBaseCSGrenade":true,"CWeaponAWP":true,"CWeaponAug":true,"CAK47":true,"CFootstepControl":true,"CCSGameRulesProxy":true,"CBaseCSGrenadeProjectile":true} \ No newline at end of file +{"CTETFParticleEffect":true,"CTETFExplosion":true,"CTETFBlood":true,"CTFTankBoss":true,"CTFBaseBoss":true,"CBossAlpha":true,"CZombie":true,"CMerasmusDancer":true,"CMerasmus":true,"CHeadlessHatman":true,"CEyeballBoss":true,"CTFWeaponSapper":true,"CTFWeaponBuilder":true,"C_TFWeaponBuilder":true,"CTFTeam":true,"CTFTauntProp":true,"CTFProjectile_Rocket":true,"CTFProjectile_Flare":true,"CTFProjectile_EnergyBall":true,"CTFProjectile_GrapplingHook":true,"CTFProjectile_HealingBolt":true,"CTFProjectile_Arrow":true,"CTFPlayerResource":true,"CTFPlayer":true,"CTFRagdoll":true,"CTEPlayerAnimEvent":true,"CTFPasstimeLogic":true,"CPasstimeBall":true,"CTFObjectiveResource":true,"CTFGlow":true,"CTEFireBullets":true,"CTFBuffBanner":true,"CTFAmmoPack":true,"CObjectTeleporter":true,"CObjectSentrygun":true,"CTFProjectile_SentryRocket":true,"CObjectSapper":true,"CObjectCartDispenser":true,"CObjectDispenser":true,"CMonsterResource":true,"CFuncRespawnRoomVisualizer":true,"CFuncRespawnRoom":true,"CFuncPasstimeGoal":true,"CFuncForceField":true,"CCaptureZone":true,"CCurrencyPack":true,"CBaseObject":true,"CTFBotHintEngineerNest":true,"CBotNPCMinion":true,"CBotNPC":true,"CRagdollPropAttached":true,"CRagdollProp":true,"NextBotCombatCharacter":true,"CWaterBullet":true,"CFuncMonitor":true,"CWorld":true,"CWaterLODControl":true,"CVGuiScreen":true,"CPropJeep":true,"CPropVehicleChoreoGeneric":true,"CTEWorldDecal":true,"CTESpriteSpray":true,"CTESprite":true,"CTESparks":true,"CTESmoke":true,"CTEShowLine":true,"CTEProjectedDecal":true,"CTEPlayerDecal":true,"CTEPhysicsProp":true,"CTEParticleSystem":true,"CTEMuzzleFlash":true,"CTELargeFunnel":true,"CTEKillPlayerAttachments":true,"CTEImpact":true,"CTEGlowSprite":true,"CTEShatterSurface":true,"CTEFootprintDecal":true,"CTEFizz":true,"CTEExplosion":true,"CTEEnergySplash":true,"CTEEffectDispatch":true,"CTEDynamicLight":true,"CTEDecal":true,"CTEClientProjectile":true,"CTEBubbleTrail":true,"CTEBubbles":true,"CTEBSPDecal":true,"CTEBreakModel":true,"CTEBloodStream":true,"CTEBloodSprite":true,"CTEBeamSpline":true,"CTEBeamRingPoint":true,"CTEBeamRing":true,"CTEBeamPoints":true,"CTEBeamLaser":true,"CTEBeamFollow":true,"CTEBeamEnts":true,"CTEBeamEntPoint":true,"CTEBaseBeam":true,"CTEArmorRicochet":true,"CTEMetalSparks":true,"CTest_ProxyToggle_Networkable":true,"CTestTraceline":true,"CTesla":true,"CTeamTrainWatcher":true,"CBaseTeamObjectiveResource":true,"CTeam":true,"CSun":true,"CSteamJet":true,"CParticlePerformanceMonitor":true,"CSpotlightEnd":true,"DustTrail":true,"CFireTrail":true,"SporeTrail":true,"SporeExplosion":true,"RocketTrail":true,"SmokeTrail":true,"CSmokeStack":true,"CSlideshowDisplay":true,"CShadowControl":true,"CSceneEntity":true,"CRopeKeyframe":true,"CRagdollManager":true,"CPropVehicleDriveable":true,"CPhysicsPropMultiplayer":true,"CPhysBoxMultiplayer":true,"CBasePropDoor":true,"CDynamicProp":true,"CPointCommentaryNode":true,"CPointCamera":true,"CPlayerResource":true,"CPlasma":true,"CPhysMagnet":true,"CPhysicsProp":true,"CPhysBox":true,"CParticleSystem":true,"ParticleSmokeGrenade":true,"CParticleFire":true,"MovieExplosion":true,"CMaterialModifyControl":true,"CLightGlow":true,"CInfoOverlayAccessor":true,"CTEGaussExplosion":true,"CFuncTrackTrain":true,"CFuncSmokeVolume":true,"CFuncRotating":true,"CFuncReflectiveGlass":true,"CFuncOccluder":true,"CFunc_LOD":true,"CTEDust":true,"CFunc_Dust":true,"CFuncConveyor":true,"CBreakableSurface":true,"CFuncAreaPortalWindow":true,"CFish":true,"CEntityFlame":true,"CFireSmoke":true,"CEnvTonemapController":true,"CEnvScreenEffect":true,"CEnvScreenOverlay":true,"CEnvProjectedTexture":true,"CEnvParticleScript":true,"CFogController":true,"CEntityParticleTrail":true,"CEntityDissolve":true,"CEnvQuadraticBeam":true,"CEmbers":true,"CEnvWind":true,"CPrecipitation":true,"CDynamicLight":true,"CColorCorrectionVolume":true,"CColorCorrection":true,"CBreakableProp":true,"CBaseTempEntity":true,"CBasePlayer":true,"CBaseFlex":true,"CBaseEntity":true,"CBaseDoor":true,"CBaseCombatCharacter":true,"CBaseAnimatingOverlay":true,"CBoneFollower":true,"CBaseAnimating":true,"CInfoLightingRelative":true,"CAI_BaseNPC":true,"CWeaponIFMSteadyCam":true,"CWeaponIFMBaseCamera":true,"CWeaponIFMBase":true,"CTFWearableLevelableItem":true,"CTFWearableDemoShield":true,"CTFWearableRobotArm":true,"CTFRobotArm":true,"CTFWrench":true,"CTFProjectile_ThrowableBreadMonster":true,"CTFProjectile_ThrowableBrick":true,"CTFProjectile_ThrowableRepel":true,"CTFProjectile_Throwable":true,"CTFThrowable":true,"CTFSyringeGun":true,"CTFKatana":true,"CTFSword":true,"CSniperDot":true,"CTFSniperRifleClassic":true,"CTFSniperRifleDecap":true,"CTFSniperRifle":true,"CTFChargedSMG":true,"CTFSMG":true,"CTFShovel":true,"CTFShotgunBuildingRescue":true,"CTFPEPBrawlerBlaster":true,"CTFSodaPopper":true,"CTFShotgun_Revenge":true,"CTFScatterGun":true,"CTFShotgun_Pyro":true,"CTFShotgun_HWG":true,"CTFShotgun_Soldier":true,"CTFShotgun":true,"CTFCrossbow":true,"CTFRocketLauncher_Mortar":true,"CTFRocketLauncher_AirStrike":true,"CTFRocketLauncher_DirectHit":true,"CTFRocketLauncher":true,"CTFRevolver":true,"CTFDRGPomson":true,"CTFRaygun":true,"CTFPistol_ScoutSecondary":true,"CTFPistol_ScoutPrimary":true,"CTFPistol_Scout":true,"CTFPistol":true,"CTFPipebombLauncher":true,"CTFWeaponPDA_Spy":true,"CTFWeaponPDA_Engineer_Destroy":true,"CTFWeaponPDA_Engineer_Build":true,"CTFWeaponPDAExpansion_Teleporter":true,"CTFWeaponPDAExpansion_Dispenser":true,"CTFWeaponPDA":true,"CPasstimeGun":true,"CTFParticleCannon":true,"CTFParachute_Secondary":true,"CTFParachute_Primary":true,"CTFParachute":true,"CTFMinigun":true,"CTFMedigunShield":true,"CWeaponMedigun":true,"CTFMechanicalArm":true,"CTFLunchBox_Drink":true,"CTFLunchBox":true,"CLaserDot":true,"CTFLaserPointer":true,"CTFKnife":true,"CTFProjectile_Cleaver":true,"CTFProjectile_JarMilk":true,"CTFProjectile_Jar":true,"CTFCleaver":true,"CTFJarMilk":true,"CTFJar":true,"CTFWeaponInvis":true,"CTFGrenadePipebombProjectile":true,"CTFCannon":true,"CTFGrenadeLauncher":true,"CTFGrapplingHook":true,"CTFFlareGun_Revenge":true,"CTFFlareGun":true,"CTFFlameRocket":true,"CTFFlameThrower":true,"CTFFists":true,"CTFFireAxe":true,"CTFCompoundBow":true,"CTFClub":true,"CTFBuffItem":true,"CTFStickBomb":true,"CTFBottle":true,"CTFBonesaw":true,"CTFBall_Ornament":true,"CTFStunBall":true,"CTFBat_Giftwrap":true,"CTFBat_Wood":true,"CTFBat_Fish":true,"CTFBat":true,"CTFBaseRocket":true,"CTFWeaponBaseMerasmusGrenade":true,"CTFWeaponBaseMelee":true,"CTFWeaponBaseGun":true,"CTFWeaponBaseGrenadeProj":true,"CTFWeaponBase":true,"CTFViewModel":true,"CRobotDispenser":true,"CTFRobotDestruction_Robot":true,"CTFReviveMarker":true,"CTFPumpkinBomb":true,"CTFProjectile_EnergyRing":true,"CTFBaseProjectile":true,"CBaseObjectUpgrade":true,"CMannVsMachineStats":true,"CTFRobotDestructionLogic":true,"CTFRobotDestruction_RobotGroup":true,"CTFRobotDestruction_RobotSpawn":true,"CTFPlayerDestructionLogic":true,"CPlayerDestructionDispenser":true,"CTFMinigameLogic":true,"CTFHalloweenMinigame_FallingPlatforms":true,"CTFHalloweenMinigame":true,"CTFMiniGame":true,"CTFWearableVM":true,"CTFWearable":true,"CTFPowerupBottle":true,"CTFItem":true,"CHalloweenSoulPack":true,"CTFGenericBomb":true,"CBonusRoundLogic":true,"CTFGameRulesProxy":true,"CTFDroppedWeapon":true,"CTFProjectile_SpellKartBats":true,"CTFProjectile_SpellKartOrb":true,"CTFHellZap":true,"CTFProjectile_SpellLightningOrb":true,"CTFProjectile_SpellTransposeTeleport":true,"CTFProjectile_SpellMeteorShower":true,"CTFProjectile_SpellSpawnBoss":true,"CTFProjectile_SpellMirv":true,"CTFProjectile_SpellPumpkin":true,"CTFProjectile_SpellSpawnHorde":true,"CTFProjectile_SpellSpawnZombie":true,"CTFProjectile_SpellBats":true,"CTFProjectile_SpellFireball":true,"CTFSpellBook":true,"CHightower_TeleportVortex":true,"CTeleportVortex":true,"CHalloweenGiftPickup":true,"CBonusDuckPickup":true,"CHalloweenPickup":true,"CCaptureFlagReturnIcon":true,"CCaptureFlag":true,"CBonusPack":true,"CHandleTest":true,"CTeamRoundTimer":true,"CTeamplayRoundBasedRulesProxy":true,"CSpriteTrail":true,"CSpriteOriented":true,"CSprite":true,"CPoseController":true,"CGameRulesProxy":true,"CInfoLadderDismount":true,"CFuncLadder":true,"CEnvDetailController":true,"CTFWearableItem":true,"CEconWearable":true,"CBaseAttributableItem":true,"CEconEntity":true,"CBeam":true,"CBaseViewModel":true,"CBaseProjectile":true,"CBaseParticleEntity":true,"CBaseGrenade":true,"CBaseCombatWeapon":true,"CVoteController":true,"CTEHL2MPFireBullets":true,"CHL2MPRagdoll":true,"CHL2MP_Player":true,"CWeaponCitizenSuitcase":true,"CWeaponCitizenPackage":true,"CWeaponAlyxGun":true,"CWeaponCubemap":true,"CWeaponGaussGun":true,"CWeaponAnnabelle":true,"CFlaregun":true,"CWeaponBugBait":true,"CWeaponBinoculars":true,"CWeaponCycler":true,"CCrossbowBolt":true,"CPropVehiclePrisonerPod":true,"CPropCrane":true,"CPropCannon":true,"CPropAirboat":true,"CFlare":true,"CTEConcussiveExplosion":true,"CNPC_Strider":true,"CScriptIntro":true,"CRotorWashEmitter":true,"CPropCombineBall":true,"CPlasmaBeamNode":true,"CNPC_RollerMine":true,"CNPC_Manhack":true,"CNPC_CombineGunship":true,"CNPC_AntlionGuard":true,"CInfoTeleporterCountdown":true,"CMortarShell":true,"CEnvStarfield":true,"CEnvHeadcrabCanister":true,"CAlyxEmpEffect":true,"CCorpse":true,"CCitadelEnergyCore":true,"CHL2_Player":true,"CBaseHLBludgeonWeapon":true,"CHLSelectFireMachineGun":true,"CHLMachineGun":true,"CBaseHelicopter":true,"CNPC_Barney":true,"CNPC_Barnacle":true,"AR2Explosion":true,"CTEAntlionDust":true,"CVortigauntEffectDispel":true,"CVortigauntChargeToken":true,"CNPC_Vortigaunt":true,"CPredictedViewModel":true,"CWeaponStunStick":true,"CWeaponSMG1":true,"CWeapon_SLAM":true,"CWeaponShotgun":true,"CWeaponRPG":true,"CWeaponPistol":true,"CWeaponPhysCannon":true,"CHL2MPMachineGun":true,"CBaseHL2MPCombatWeapon":true,"CBaseHL2MPBludgeonWeapon":true,"CWeaponHL2MPBase":true,"CWeaponFrag":true,"CWeaponCrowbar":true,"CWeaponCrossbow":true,"CWeaponAR2":true,"CWeapon357":true,"CHL2MPGameRulesProxy":true,"CHalfLife2Proxy":true,"CBaseHLCombatWeapon":true,"CTFVehicle":true,"CTFBaseDMPowerup":true,"CWeaponSpawner":true,"CTFUmbrella":true,"CTFTranq":true,"CTFSMG_Primary":true,"CTFRevolver_Secondary":true,"CTFNailgun":true,"CTFHunterRifle":true,"CTFHeavyArtillery":true,"CTFHammerfists":true,"CTFCrowbar":true,"CTFChainsaw":true,"CTEPlantBomb":true,"CTERadioIcon":true,"CPlantedC4":true,"CCSTeam":true,"CCSPlayerResource":true,"CCSPlayer":true,"CCSRagdoll":true,"CHostage":true,"CWeaponXM1014":true,"CWeaponUSP":true,"CWeaponUMP45":true,"CWeaponTMP":true,"CSmokeGrenade":true,"CWeaponSG552":true,"CWeaponSG550":true,"CWeaponScout":true,"CWeaponP90":true,"CWeaponP228":true,"CWeaponMP5Navy":true,"CWeaponMAC10":true,"CWeaponM4A1":true,"CWeaponM3":true,"CWeaponM249":true,"CKnife":true,"CHEGrenade":true,"CWeaponGlock":true,"CWeaponGalil":true,"CWeaponG3SG1":true,"CFlashbang":true,"CWeaponFiveSeven":true,"CWeaponFamas":true,"CWeaponElite":true,"CDEagle":true,"CWeaponCSBaseGun":true,"CWeaponCSBase":true,"CC4":true,"CBaseCSGrenade":true,"CWeaponAWP":true,"CWeaponAug":true,"CAK47":true,"CFootstepControl":true,"CCSGameRulesProxy":true,"CBaseCSGrenadeProjectile":true,"CSDKTeam_Deathmatch":true,"CSDKTeam_Red":true,"CSDKTeam_Blue":true,"CSDKTeam_Unassigned":true,"CSDKTeam":true,"CSDKPlayerResource":true,"CSDKRagdoll":true,"CSDKPlayer":true,"CSparkler":true,"CRatRaceWaypoint":true,"CBriefcaseCaptureZone":true,"CBriefcase":true,"CWeaponSDKBase":true,"CWeaponMP5K":true,"CWeaponMossberg":true,"CWeaponM1911":true,"CWeaponM16":true,"CWeaponGrenade":true,"CWeaponFAL":true,"CWeaponBrawl":true,"CWeaponBeretta":true,"CBaseSDKGrenade":true,"CAkimboM1911":true,"CAkimboBeretta":true,"CAkimboBase":true,"CWeaponSDKMelee":true,"CSDKGameRulesProxy":true,"CBaseGrenadeProjectile":true,"CDAViewModel":true} \ No newline at end of file diff --git a/generate-class-headers.js b/generate-class-headers.js index 55b3509b..71191ab0 100644 --- a/generate-class-headers.js +++ b/generate-class-headers.js @@ -1,14 +1,14 @@ -const fs = require('fs'); +const fs = require("fs"); var full_class_table = {}; try { - full_class_table = JSON.parse(fs.readFileSync('full-class-table.json').toString()); + full_class_table = JSON.parse(fs.readFileSync("full-class-table.json").toString()); } catch (e) {} -const file = fs.readFileSync(process.argv[2]).toString().split('\n'); +const file = fs.readFileSync(process.argv[2]).toString().split("\n"); const modname = process.argv[3]; -console.log('Generating info for', modname, 'from', process.argv[2]); +console.log("Generating info for", modname, "from", process.argv[2]); var classes = {}; for (var i in file) { @@ -19,7 +19,7 @@ for (var i in file) { } } -fs.writeFileSync('full-class-table.json', JSON.stringify(full_class_table)); +fs.writeFileSync("full-class-table.json", JSON.stringify(full_class_table)); var header_constexpr = `/* AUTO-GENERATED HEADER - DO NOT MODIFY @@ -50,10 +50,10 @@ namespace client_classes { `; for (var clz in full_class_table) { - var value = '0'; + var value = "0"; if (classes[clz]) value = classes[clz]; - header_constexpr += '\t\tstatic constexpr int ' + clz + ' = ' + value + ';\n'; - header += '\t\tint ' + clz + ' { ' + value + ' };\n'; + header_constexpr += "\t\tstatic constexpr int " + clz + " = " + value + ";\n"; + header += "\t\tint " + clz + " { " + value + " };\n"; } header += ` @@ -70,8 +70,8 @@ header_constexpr += ` #endif /* $mod_CONSTEXPR_AUTOGEN_HPP */`; -fs.writeFileSync('src/classinfo/' + modname + '.gen.hpp', header.replace(/\$mod/g, modname)); -fs.writeFileSync('src/classinfo/' + modname + '_constexpr.gen.hpp', header_constexpr.replace(/\$mod/g, modname)); +fs.writeFileSync("src/classinfo/" + modname + ".gen.hpp", header.replace(/\$mod/g, modname)); +fs.writeFileSync("src/classinfo/" + modname + "_constexpr.gen.hpp", header_constexpr.replace(/\$mod/g, modname)); -console.log(classes); \ No newline at end of file +console.log(classes); diff --git a/generate-dummy-header.js b/generate-dummy-header.js index d3e7e323..7fe18669 100644 --- a/generate-dummy-header.js +++ b/generate-dummy-header.js @@ -1,11 +1,11 @@ -const fs = require('fs'); +const fs = require("fs"); var full_class_table = {}; try { - full_class_table = JSON.parse(fs.readFileSync('full-class-table.json').toString()); + full_class_table = JSON.parse(fs.readFileSync("full-class-table.json").toString()); } catch (e) {} -console.log('Generating dummy class header'); +console.log("Generating dummy class header"); var header = `/* AUTO-GENERATED HEADER - DO NOT MODIFY @@ -22,7 +22,7 @@ namespace client_classes { `; for (var clz in full_class_table) { - header += '\t\tint ' + clz + ' { 0 };\n'; + header += "\t\tint " + clz + " { 0 };\n"; } header += ` @@ -33,4 +33,4 @@ header += ` #endif /* DUMMY_AUTOGEN_HPP */`; -fs.writeFileSync('src/classinfo/dummy.gen.hpp', header); \ No newline at end of file +fs.writeFileSync("src/classinfo/dummy.gen.hpp", header); diff --git a/generate-dynamic-header.js b/generate-dynamic-header.js new file mode 100644 index 00000000..ba4e377d --- /dev/null +++ b/generate-dynamic-header.js @@ -0,0 +1,73 @@ +const fs = require("fs"); + +var full_class_table = {}; +try { + full_class_table = JSON.parse(fs.readFileSync("full-class-table.json").toString()); +} catch (e) {} + +console.log("Generating dummy class header"); + +var header = `/* + AUTO-GENERATED HEADER - DO NOT MODIFY + HEADER FOR UNIVERSAL BUILD +*/ + +#ifndef DYNAMIC_AUTOGEN_HPP +#define DYNAMIC_AUTOGEN_HPP + +namespace client_classes { + + class dynamic { + public: + dynamic(); + void Populate(); +`; + +for (var clz in full_class_table) { + header += "\t\tint " + clz + " { 0 };\n"; +} + +header += ` + }; + + extern dynamic dynamic_list; +} + +#endif /* DYNAMIC_AUTOGEN_HPP */`; + +var POPULATED_MAP = ""; + +for (var clz in full_class_table) { + POPULATED_MAP += `\t\tclassid_mapping["${clz}"] = &${clz};\n`; +} + +var source = ` + +#include "dynamic.gen.hpp" +#include "../common.h" + +namespace client_classes { + +std::unordered_map classid_mapping {}; + +dynamic::dynamic() { +${POPULATED_MAP} +} + +void dynamic::Populate() { + ClientClass* cc = g_IBaseClient->GetAllClasses(); + while (cc) { + std::string name(cc->GetName()); + if (classid_mapping.find(name) != classid_mapping.end()) + *classid_mapping[name] = cc->m_ClassID; + cc = cc->m_pNext; + } +} + +dynamic dynamic_list; + +}`; + + +fs.writeFileSync("src/classinfo/dynamic.gen.hpp", header); +fs.writeFileSync("src/classinfo/dynamic.gen.cpp", source); diff --git a/install-resources.sh b/install-resources.sh deleted file mode 100755 index 7523a5eb..00000000 --- a/install-resources.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -if [ ! -d "$HOME/.cathook" ]; then - mkdir "$HOME"/.cathook -fi - -if [ ! -f "$HOME/.cathook/killsays.txt" ]; then - cp res/killsays.txt "$HOME"/.cathook -fi - -if [ ! -f "$HOME/.cathook/spam.txt" ]; then - cp res/spam.txt "$HOME"/.cathook -fi - -echo "Default killsay/spam files installed, EDIT THEM!" -xdg-open "$HOME"/.cathook diff --git a/lib/libGLEW.so b/lib/libGLEW.so new file mode 100644 index 00000000..7a9a14dc Binary files /dev/null and b/lib/libGLEW.so differ diff --git a/lib/libSDL2-2.0.so.0 b/lib/libSDL2-2.0.so.0 new file mode 100644 index 00000000..4e8ca343 Binary files /dev/null and b/lib/libSDL2-2.0.so.0 differ diff --git a/lib/libfreetype.so b/lib/libfreetype.so new file mode 100644 index 00000000..be575fee Binary files /dev/null and b/lib/libfreetype.so differ diff --git a/lib/libstdc++.so.6 b/lib/libstdc++.so.6 index 7c17d0bf..974fdf7f 100644 Binary files a/lib/libstdc++.so.6 and b/lib/libstdc++.so.6 differ diff --git a/libcathook.so b/libcathook.so deleted file mode 100755 index 00d98889..00000000 Binary files a/libcathook.so and /dev/null differ diff --git a/make-nogui.sh b/make-nogui.sh index 7acdeb48..fddbff17 100755 --- a/make-nogui.sh +++ b/make-nogui.sh @@ -1 +1,2 @@ -make -j4 -e NOGUI=1 \ No newline at end of file +#!/bin/bash +make -j4 -e NOGUI=1 diff --git a/makefile b/makefile index 6d63e0c4..5ee76eac 100644 --- a/makefile +++ b/makefile @@ -1,44 +1,136 @@ +ifndef CLANG CXX=$(shell sh -c "which g++-6 || which g++") -CXXFLAGS=-std=gnu++14 -D_GLIBCXX_USE_CXX11_ABI=0 -D_POSIX=1 -DRAD_TELEMETRY_DISABLED -DLINUX=1 -DUSE_SDL -D_LINUX=1 -DPOSIX=1 -DGNUC=1 -D_DEVELOPER=1 -DNO_MALLOC_OVERRIDE -O3 -g3 -ggdb -w -shared -Wall -Wno-unknown-pragmas -fmessage-length=0 -m32 -fvisibility=hidden -fPIC +CC=$(shell sh -c "which gcc-6 || which gcc") +LD=$(CXX) +else +CXX=clang++ +CC=clang +LD=ld.lld +endif + +DEFINES=_GLIBCXX_USE_CXX11_ABI=0 _POSIX=1 FREETYPE_GL_USE_VAO RAD_TELEMETRY_DISABLED LINUX=1 USE_SDL _LINUX=1 POSIX=1 GNUC=1 NO_MALLOC_OVERRIDE + +WARNING_FLAGS=-pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-conversion -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef +COMMON_FLAGS=-fpermissive -O3 -shared -Wno-unknown-pragmas -fmessage-length=0 -m32 -fvisibility=hidden -fPIC -march=native -mtune=native + + +ifdef CLANG +COMMON_FLAGS+=-Wno-c++11-narrowing +endif + +ifdef BUILD_DEBUG +COMMON_FLAGS+=-g3 -ggdb +else +ifndef CLANG +COMMON_FLAGS+=-flto +endif +endif + +CFLAGS=$(COMMON_FLAGS) +CXXFLAGS=-std=gnu++14 $(COMMON_FLAGS) + +ifndef NO_WARNINGS +CFLAGS+=$(WARNING_FLAGS) +CXXFLAGS+=$(WARNING_FLAGS) +else +CFLAGS+=-w +CXXFLAGS+=-w +endif + SDKFOLDER=$(realpath source-sdk-2013/mp/src) SIMPLE_IPC_DIR = $(realpath simple-ipc/src/include) -INCLUDES=-I$(SIMPLE_IPC_DIR) -I$(SDKFOLDER)/public -I$(SDKFOLDER)/mathlib -I$(SDKFOLDER)/common -I$(SDKFOLDER)/public/tier1 -I$(SDKFOLDER)/public/tier0 -I$(SDKFOLDER) -CXXFLAGS += $(INCLUDES) +INCLUDES=-Iucccccp -isystemsrc/freetype-gl -isystemsrc/imgui -isystem/usr/local/include/freetype2 -isystem/usr/include/freetype2 -I$(SIMPLE_IPC_DIR) -isystem$(SDKFOLDER)/public -isystem$(SDKFOLDER)/mathlib -isystem$(SDKFOLDER)/common -isystem$(SDKFOLDER)/public/tier1 -isystem$(SDKFOLDER)/public/tier0 -isystem$(SDKFOLDER) LIB_DIR=lib -LDFLAGS=-m32 -fno-gnu-unique -D_GLIBCXX_USE_CXX11_ABI=0 -shared -L$(realpath $(LIB_DIR)) -LDLIBS=-static -lc -lstdc++ -ltier0 -lvstdlib +LDFLAGS=-shared -L$(realpath $(LIB_DIR)) +ifdef CLANG +LDFLAGS+=-melf_i386 +else +LDFLAGS+=-m32 -fno-gnu-unique +endif + +ifndef BUILD_DEBUG +ifndef CLANG +LDFLAGS+=-flto +endif +endif +LDLIBS=-lssl -l:libSDL2-2.0.so.0 -static -l:libc.so.6 -static -l:libstdc++.so.6 -l:libtier0.so -l:libvstdlib.so -static -l:libGLEW.so -l:libfreetype.so + +OUT_NAME = libcathook.so + +ifdef TEXTMODE +$(info Compiling for text mode only!) +N_LDLIBS = -lssl -l:libSDL2-2.0.so.0 -l:libGLEW.so -l:libfreetype.so +LDLIBS := $(filter-out $(N_LDLIBS),$(LDLIBS)) +N_INCLUDES = -isystemsrc/freetype-gl -isystemsrc/imgui -isystem/usr/local/include/freetype2 -isystem/usr/include/freetype2 +INCLUDES := $(filter-out $(N_INCLUDES),$(INCLUDES)) +DEFINES += TEXTMODE=1 +#OUT_NAME := libcathook-textmode.so +endif + +ifdef TEXTMODE_STDIN +DEFINES+=-DTEXTMODE_STDIN +endif + SRC_DIR = src RES_DIR = res -OUT_NAME = libcathook.so TARGET_DIR = bin TARGET = $(TARGET_DIR)/$(OUT_NAME) -SOURCES = $(shell find $(SRC_DIR) -name "*.cpp" -print) +SOURCES = $(shell find $(SRC_DIR) -name "*.c*" -print) ifdef NOGUI $(info GUI disabled) SOURCES := $(filter-out $(shell find $(SRC_DIR)/gui -name "*.cpp" -print),$(SOURCES)) -CXXFLAGS += -DNOGUI=1 +DEFINES+=NOGUI=1 else $(info GUI enabled) endif ifdef GAME $(info Building for: $(GAME)) -CXXFLAGS += -DBUILD_GAME=$(GAME) +DEFINES+=BUILD_GAME=$(GAME) else $(info GUI enabled) endif SOURCES += $(shell find $(SIMPLE_IPC_DIR) -name "*.cpp" -print) -OBJECTS = $(SOURCES:.cpp=.o) +OBJECTS = $(patsubst %.c,%.o, $(patsubst %.cpp,%.o, $(SOURCES))) OBJECTS += $(shell find $(RES_DIR) -name "*.o" -print) -DEPENDS = $(SOURCES:.cpp=.d) +DEPENDS = $(patsubst %.c,%.d, $(patsubst %.cpp,%.d, $(SOURCES))) SRC_SUBDIRS=$(shell find $(SRC_DIR) -type d -print) GIT_COMMIT_HASH=$(shell git log -1 --pretty="%h") GIT_COMMIT_DATE=$(shell git log -1 --pretty="%ai") -CXXFLAGS += -DGIT_COMMIT_HASH="\"$(GIT_COMMIT_HASH)\"" -DGIT_COMMIT_DATE="\"$(GIT_COMMIT_DATE)\"" +DEFINES+=GIT_COMMIT_HASH="\"$(GIT_COMMIT_HASH)\"" GIT_COMMIT_DATE="\"$(GIT_COMMIT_DATE)\"" ifdef GAME -CXXFLAGS += -DGAME=$(GAME) +DEFINES+=GAME=$(GAME) +endif + +ifdef NOIPC +$(info IPC disabled) +DEFINES += NO_IPC +endif + +CXXFLAGS+=$(addprefix -D,$(DEFINES)) +CFLAGS+=$(addprefix -D,$(DEFINES)) + +CXXFLAGS+=$(INCLUDES) +CFLAGS+=$(INCLUDES) + +ifdef TEXTMODE + +N_SOURCES := hacks/ESP.cpp hacks/SkinChanger.cpp hacks/SpyAlert.cpp hacks/Radar.cpp fidgetspinner.cpp ftrender.cpp hooks/sdl.cpp drawmgr.cpp drawgl.cpp hooks/PaintTraverse.cpp EffectChams.cpp EffectGlow.cpp +N_SOURCES := $(addprefix $(SRC_DIR)/,$(N_SOURCES)) + +SOURCES := $(filter-out $(shell find $(SRC_DIR)/gui -name "*.cpp" -print),$(SOURCES)) +SOURCES := $(filter-out $(shell find $(SRC_DIR)/freetype-gl -name "*.c*" -print),$(SOURCES)) +SOURCES := $(filter-out $(shell find $(SRC_DIR)/imgui -name "*.c*" -print),$(SOURCES)) +SOURCES := $(filter-out $(N_SOURCES),$(SOURCES)) + + +else + +CXXFLAGS+=$(shell sdl2-config --cflags) +CFLAGS+=$(shell sdl2-config --cflags) + endif .PHONY: clean directories echo @@ -48,22 +140,53 @@ all: $(MAKE) $(TARGET) echo: - echo $(SOURCES) + echo $(OBJECTS) + +src/imgui/imgui_demo.o : CXXFLAGS+=-w +src/imgui/imgui_draw.o : CXXFLAGS+=-w +src/imgui/imgui_impl_sdl.o : CXXFLAGS+=-w +src/imgui/imgui.o : CXXFLAGS+=-w + +src/freetype-gl/distance-field.o : CFLAGS+=-w +src/freetype-gl/edtaa3func.o : CFLAGS+=-w +src/freetype-gl/font-manager.o : CFLAGS+=-w +src/freetype-gl/mat4.o : CFLAGS+=-w +src/freetype-gl/platform.o : CFLAGS+=-w +src/freetype-gl/shader.o : CFLAGS+=-w +src/freetype-gl/text-buffer.o : CFLAGS+=-w +src/freetype-gl/texture-atlas.o : CFLAGS+=-w +src/freetype-gl/utf8-utils.o : CFLAGS+=-w +src/freetype-gl/texture-font.o : CFLAGS+=-w +src/freetype-gl/vector.o : CFLAGS+=-w +src/freetype-gl/vertex-attribute.o : CFLAGS+=-w +src/freetype-gl/vertex-buffer.o : CFLAGS+=-w +src/sdk/checksum_md5.o : CFLAGS+=-w +src/sdk/convar.o : CFLAGS+=-w +src/sdk/KeyValues.o : CFLAGS+=-w +src/sdk/MaterialSystemUtil.o : CFLAGS+=-w +src/sdk/tier1.o : CFLAGS+=-w +src/sdk/utlbuffer.o : CFLAGS+=-w .cpp.o: @echo Compiling $< @$(CXX) $(CXXFLAGS) -c $< -o $@ + +.c.o: + @echo Compiling $< + @$(CC) $(CFLAGS) -c $< -o $@ %.d: %.cpp @$(CXX) -M $(CXXFLAGS) $< > $@ $(TARGET): $(OBJECTS) @echo Building cathook - @$(CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJECTS) $(LDLIBS) -o $(TARGET) + $(LD) -o $(TARGET) $(LDFLAGS) $(OBJECTS) $(LDLIBS) clean: find src -type f -name '*.o' -delete find src -type f -name '*.d' -delete + find simple-ipc -type f -name '*.o' -delete + find simple-ipc -type f -name '*.d' -delete rm -rf ./bin ifneq ($(MAKECMDGOALS), clean) diff --git a/res/atlas b/res/atlas new file mode 100644 index 00000000..b0bdc81f Binary files /dev/null and b/res/atlas differ diff --git a/res/atlas.png b/res/atlas.png new file mode 100644 index 00000000..6b85b00b Binary files /dev/null and b/res/atlas.png differ diff --git a/res/atlas.xcf b/res/atlas.xcf new file mode 100644 index 00000000..6467574b Binary files /dev/null and b/res/atlas.xcf differ diff --git a/res/bin/atlas.o b/res/bin/atlas.o new file mode 100644 index 00000000..784afb0f Binary files /dev/null and b/res/bin/atlas.o differ diff --git a/res/bin/crit_1.o b/res/bin/crit_1.o deleted file mode 100644 index 48be3480..00000000 Binary files a/res/bin/crit_1.o and /dev/null differ diff --git a/res/bin/crit_2.o b/res/bin/crit_2.o deleted file mode 100644 index ee7a7dcc..00000000 Binary files a/res/bin/crit_2.o and /dev/null differ diff --git a/res/bin/crit_3.o b/res/bin/crit_3.o deleted file mode 100644 index 3f30f471..00000000 Binary files a/res/bin/crit_3.o and /dev/null differ diff --git a/res/bin/crit_4.o b/res/bin/crit_4.o deleted file mode 100644 index e3501270..00000000 Binary files a/res/bin/crit_4.o and /dev/null differ diff --git a/res/bin/demoman.o b/res/bin/demoman.o deleted file mode 100644 index 03cbf69f..00000000 Binary files a/res/bin/demoman.o and /dev/null differ diff --git a/res/bin/demoman_blue.o b/res/bin/demoman_blue.o deleted file mode 100644 index 952dcb18..00000000 Binary files a/res/bin/demoman_blue.o and /dev/null differ diff --git a/res/bin/dispenser.o b/res/bin/dispenser.o deleted file mode 100644 index 299d69ea..00000000 Binary files a/res/bin/dispenser.o and /dev/null differ diff --git a/res/bin/engineer.o b/res/bin/engineer.o deleted file mode 100644 index 508a0f7a..00000000 Binary files a/res/bin/engineer.o and /dev/null differ diff --git a/res/bin/engineer_blue.o b/res/bin/engineer_blue.o deleted file mode 100644 index 3baa2333..00000000 Binary files a/res/bin/engineer_blue.o and /dev/null differ diff --git a/res/bin/flame.o b/res/bin/flame.o deleted file mode 100644 index 4b4593cd..00000000 Binary files a/res/bin/flame.o and /dev/null differ diff --git a/res/bin/heart.o b/res/bin/heart.o deleted file mode 100644 index dad592ad..00000000 Binary files a/res/bin/heart.o and /dev/null differ diff --git a/res/bin/heavy.o b/res/bin/heavy.o deleted file mode 100644 index c0245967..00000000 Binary files a/res/bin/heavy.o and /dev/null differ diff --git a/res/bin/heavy_blue.o b/res/bin/heavy_blue.o deleted file mode 100644 index 36598bc1..00000000 Binary files a/res/bin/heavy_blue.o and /dev/null differ diff --git a/res/bin/logo.o b/res/bin/logo.o deleted file mode 100644 index b1d0d35e..00000000 Binary files a/res/bin/logo.o and /dev/null differ diff --git a/res/bin/medic.o b/res/bin/medic.o deleted file mode 100644 index cacd38c0..00000000 Binary files a/res/bin/medic.o and /dev/null differ diff --git a/res/bin/medic_blue.o b/res/bin/medic_blue.o deleted file mode 100644 index e0525072..00000000 Binary files a/res/bin/medic_blue.o and /dev/null differ diff --git a/res/bin/pyro.o b/res/bin/pyro.o deleted file mode 100644 index 5cb8b122..00000000 Binary files a/res/bin/pyro.o and /dev/null differ diff --git a/res/bin/pyro_blue.o b/res/bin/pyro_blue.o deleted file mode 100644 index e12369b4..00000000 Binary files a/res/bin/pyro_blue.o and /dev/null differ diff --git a/res/bin/raindrop.o b/res/bin/raindrop.o deleted file mode 100644 index c224bbef..00000000 Binary files a/res/bin/raindrop.o and /dev/null differ diff --git a/res/bin/raindrop2.o b/res/bin/raindrop2.o deleted file mode 100644 index 2f51ed25..00000000 Binary files a/res/bin/raindrop2.o and /dev/null differ diff --git a/res/bin/scout.o b/res/bin/scout.o deleted file mode 100644 index e21dbbd9..00000000 Binary files a/res/bin/scout.o and /dev/null differ diff --git a/res/bin/scout_blue.o b/res/bin/scout_blue.o deleted file mode 100644 index 27c6f556..00000000 Binary files a/res/bin/scout_blue.o and /dev/null differ diff --git a/res/bin/sniper.o b/res/bin/sniper.o deleted file mode 100644 index 40d17088..00000000 Binary files a/res/bin/sniper.o and /dev/null differ diff --git a/res/bin/sniper_blue.o b/res/bin/sniper_blue.o deleted file mode 100644 index 0ca69252..00000000 Binary files a/res/bin/sniper_blue.o and /dev/null differ diff --git a/res/bin/snowflake.o b/res/bin/snowflake.o deleted file mode 100644 index a61666df..00000000 Binary files a/res/bin/snowflake.o and /dev/null differ diff --git a/res/bin/soldier.o b/res/bin/soldier.o deleted file mode 100644 index 89826962..00000000 Binary files a/res/bin/soldier.o and /dev/null differ diff --git a/res/bin/soldier_blue.o b/res/bin/soldier_blue.o deleted file mode 100644 index bcf795e0..00000000 Binary files a/res/bin/soldier_blue.o and /dev/null differ diff --git a/res/bin/spy.o b/res/bin/spy.o deleted file mode 100644 index dd793fd4..00000000 Binary files a/res/bin/spy.o and /dev/null differ diff --git a/res/bin/spy_blue.o b/res/bin/spy_blue.o deleted file mode 100644 index b4fd533f..00000000 Binary files a/res/bin/spy_blue.o and /dev/null differ diff --git a/res/crit_1 b/res/crit_1 deleted file mode 100644 index 5a05876e..00000000 Binary files a/res/crit_1 and /dev/null differ diff --git a/res/crit_1.png b/res/crit_1.png deleted file mode 100644 index 553abe42..00000000 Binary files a/res/crit_1.png and /dev/null differ diff --git a/res/crit_2 b/res/crit_2 deleted file mode 100644 index b1b35a20..00000000 Binary files a/res/crit_2 and /dev/null differ diff --git a/res/crit_2.png b/res/crit_2.png deleted file mode 100644 index ae31f2a0..00000000 Binary files a/res/crit_2.png and /dev/null differ diff --git a/res/crit_3 b/res/crit_3 deleted file mode 100644 index 2d12e738..00000000 Binary files a/res/crit_3 and /dev/null differ diff --git a/res/crit_3.png b/res/crit_3.png deleted file mode 100644 index 963dfaa0..00000000 Binary files a/res/crit_3.png and /dev/null differ diff --git a/res/crit_4 b/res/crit_4 deleted file mode 100644 index 686695b4..00000000 Binary files a/res/crit_4 and /dev/null differ diff --git a/res/crit_4.png b/res/crit_4.png deleted file mode 100644 index a530a534..00000000 Binary files a/res/crit_4.png and /dev/null differ diff --git a/res/demoman.jpg b/res/demoman.jpg deleted file mode 100644 index 139dbf1e..00000000 Binary files a/res/demoman.jpg and /dev/null differ diff --git a/res/demoman_blue.jpg b/res/demoman_blue.jpg deleted file mode 100644 index f7070967..00000000 Binary files a/res/demoman_blue.jpg and /dev/null differ diff --git a/res/dispenser b/res/dispenser deleted file mode 100644 index 05bf9bd6..00000000 Binary files a/res/dispenser and /dev/null differ diff --git a/res/dispenser.png b/res/dispenser.png deleted file mode 100644 index ab4b87a9..00000000 Binary files a/res/dispenser.png and /dev/null differ diff --git a/res/engineer.jpg b/res/engineer.jpg deleted file mode 100644 index 3e6072e1..00000000 Binary files a/res/engineer.jpg and /dev/null differ diff --git a/res/engineer_blue.jpg b/res/engineer_blue.jpg deleted file mode 100644 index 0318b5c7..00000000 Binary files a/res/engineer_blue.jpg and /dev/null differ diff --git a/res/flame b/res/flame deleted file mode 100644 index 656337f5..00000000 Binary files a/res/flame and /dev/null differ diff --git a/res/flame.png b/res/flame.png deleted file mode 100644 index aed66d7b..00000000 Binary files a/res/flame.png and /dev/null differ diff --git a/res/heart b/res/heart deleted file mode 100644 index ee4d16f1..00000000 Binary files a/res/heart and /dev/null differ diff --git a/res/heart.png b/res/heart.png deleted file mode 100644 index 6b7c0b1f..00000000 Binary files a/res/heart.png and /dev/null differ diff --git a/res/heavy.jpg b/res/heavy.jpg deleted file mode 100644 index 1bc57b83..00000000 Binary files a/res/heavy.jpg and /dev/null differ diff --git a/res/heavy_blue.jpg b/res/heavy_blue.jpg deleted file mode 100644 index d123c5f6..00000000 Binary files a/res/heavy_blue.jpg and /dev/null differ diff --git a/res/logo.png b/res/logo.png deleted file mode 100644 index 2fac9359..00000000 Binary files a/res/logo.png and /dev/null differ diff --git a/res/medic.jpg b/res/medic.jpg deleted file mode 100644 index 6cff759e..00000000 Binary files a/res/medic.jpg and /dev/null differ diff --git a/res/medic_blue.jpg b/res/medic_blue.jpg deleted file mode 100644 index d26c09b7..00000000 Binary files a/res/medic_blue.jpg and /dev/null differ diff --git a/res/pyro.jpg b/res/pyro.jpg deleted file mode 100644 index b4780746..00000000 Binary files a/res/pyro.jpg and /dev/null differ diff --git a/res/pyro_blue.jpg b/res/pyro_blue.jpg deleted file mode 100644 index acc1a817..00000000 Binary files a/res/pyro_blue.jpg and /dev/null differ diff --git a/res/raindrop b/res/raindrop deleted file mode 100644 index 6dfa7bbc..00000000 Binary files a/res/raindrop and /dev/null differ diff --git a/res/raindrop.png b/res/raindrop.png deleted file mode 100644 index cba5a93b..00000000 Binary files a/res/raindrop.png and /dev/null differ diff --git a/res/raindrop2 b/res/raindrop2 deleted file mode 100644 index 457c2d9c..00000000 Binary files a/res/raindrop2 and /dev/null differ diff --git a/res/raindrop2.png b/res/raindrop2.png deleted file mode 100644 index 1e1477e2..00000000 Binary files a/res/raindrop2.png and /dev/null differ diff --git a/res/scout.jpg b/res/scout.jpg deleted file mode 100644 index 0ec3b64d..00000000 Binary files a/res/scout.jpg and /dev/null differ diff --git a/res/scout_blue.jpg b/res/scout_blue.jpg deleted file mode 100644 index b53659f5..00000000 Binary files a/res/scout_blue.jpg and /dev/null differ diff --git a/res/shaders/v2f-c4f.frag b/res/shaders/v2f-c4f.frag new file mode 100644 index 00000000..89946792 --- /dev/null +++ b/res/shaders/v2f-c4f.frag @@ -0,0 +1,4 @@ +// 2D drawing shader +void main() { + gl_FragColor = gl_Color; +} diff --git a/res/shaders/v2f-c4f.vert b/res/shaders/v2f-c4f.vert new file mode 100644 index 00000000..dda5f179 --- /dev/null +++ b/res/shaders/v2f-c4f.vert @@ -0,0 +1,13 @@ +// 2D drawing shader +uniform mat4 model; +uniform mat4 view; +uniform mat4 projection; + +attribute vec2 vertex; +attribute vec4 color; + +void main() +{ + gl_FrontColor = color; + gl_Position = projection*(view*(model*vec4(vertex,0.0,1.0))); +} diff --git a/res/shaders/v2f-t2f-c4f.frag b/res/shaders/v2f-t2f-c4f.frag new file mode 100644 index 00000000..3cdf9801 --- /dev/null +++ b/res/shaders/v2f-t2f-c4f.frag @@ -0,0 +1,6 @@ +// 2D drawing shader +uniform sampler2D texture; +void main() +{ + gl_FragColor = texture2D(texture, gl_TexCoord[0].xy) * gl_Color; +} diff --git a/res/shaders/v2f-t2f-c4f.vert b/res/shaders/v2f-t2f-c4f.vert new file mode 100644 index 00000000..1927b815 --- /dev/null +++ b/res/shaders/v2f-t2f-c4f.vert @@ -0,0 +1,15 @@ +// 2D drawing shader - modified freetype-gl shader +uniform mat4 model; +uniform mat4 view; +uniform mat4 projection; + +attribute vec2 vertex; +attribute vec2 tex_coord; +attribute vec4 color; + +void main() +{ + gl_TexCoord[0].xy = tex_coord.xy; + gl_FrontColor = color; + gl_Position = projection*(view*(model*vec4(vertex,0.0,1.0))); +} diff --git a/res/shaders/v3f-t2f-c4f.frag b/res/shaders/v3f-t2f-c4f.frag new file mode 100644 index 00000000..4b37f859 --- /dev/null +++ b/res/shaders/v3f-t2f-c4f.frag @@ -0,0 +1,11 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +uniform sampler2D texture; +void main() +{ + float a = texture2D(texture, gl_TexCoord[0].xy).r; + gl_FragColor = vec4(gl_Color.rgb, gl_Color.a*a); +} diff --git a/res/shaders/v3f-t2f-c4f.vert b/res/shaders/v3f-t2f-c4f.vert new file mode 100644 index 00000000..5d0232c3 --- /dev/null +++ b/res/shaders/v3f-t2f-c4f.vert @@ -0,0 +1,18 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +uniform mat4 model; +uniform mat4 view; +uniform mat4 projection; + +attribute vec3 vertex; +attribute vec2 tex_coord; +attribute vec4 color; +void main() +{ + gl_TexCoord[0].xy = tex_coord.xy; + gl_FrontColor = color; + gl_Position = projection*(view*(model*vec4(vertex,1.0))); +} diff --git a/res/sniper.jpg b/res/sniper.jpg deleted file mode 100644 index 6189f202..00000000 Binary files a/res/sniper.jpg and /dev/null differ diff --git a/res/sniper_blue.jpg b/res/sniper_blue.jpg deleted file mode 100644 index 34fd7735..00000000 Binary files a/res/sniper_blue.jpg and /dev/null differ diff --git a/res/snowflake.png b/res/snowflake.png deleted file mode 100644 index 0fd73c18..00000000 Binary files a/res/snowflake.png and /dev/null differ diff --git a/res/soldier.jpg b/res/soldier.jpg deleted file mode 100644 index cc3bfc87..00000000 Binary files a/res/soldier.jpg and /dev/null differ diff --git a/res/soldier_blue.jpg b/res/soldier_blue.jpg deleted file mode 100644 index 810199b2..00000000 Binary files a/res/soldier_blue.jpg and /dev/null differ diff --git a/res/spy.jpg b/res/spy.jpg deleted file mode 100644 index 5ea54465..00000000 Binary files a/res/spy.jpg and /dev/null differ diff --git a/res/spy_blue.jpg b/res/spy_blue.jpg deleted file mode 100644 index 9fe91e5a..00000000 Binary files a/res/spy_blue.jpg and /dev/null differ diff --git a/src/CDumper.h b/src/CDumper.h index dd5e4bfd..ab6d62bc 100644 --- a/src/CDumper.h +++ b/src/CDumper.h @@ -8,116 +8,97 @@ #ifndef CDUMPER_H_ #define CDUMPER_H_ -#include +#include "beforecheaders.h" #include +#include +#include "aftercheaders.h" #include "logging.h" #include "fixsdk.h" #include #include -class CDumper -{ - std::fstream m_file; - - char* TypeToString(SendPropType type) - { - //logging::Info("inside..."); - char* ret = (char *)"UNKNOWN"; - //logging::Info("oh my"); - //logging::Info("ret.. %s", ret); - if (type == 0) { - ret = (char *)"INT"; - } else if (type == 1) { - ret = (char *)"FLOAT"; - } else if (type == 2) { - ret = (char *)"VECTOR3"; - } else if (type == 3) { - ret = (char *)"VECTOR2"; - } else if (type == 4) { - ret = (char *)"STRING"; - } else if (type == 5) { - ret = (char *)"ARRAY"; - } else if (type == 6) { - ret = (char *)"TABLE"; - } - //logging::Info("returning %s", ret); - return ret; - } - +class CDumper { public: - CDumper() - { - //logging::Info("opening file..."); + CDumper() { m_file.open("/tmp/netdump.txt", std::ios::out | std::ios::trunc); - //logging::Info("file: %i", m_file.good()); } - ~CDumper() - { + ~CDumper() { m_file.close(); } - void SaveDump() - { - ClientClass *pList = g_IBaseClient->GetAllClasses(); - //logging::Info("iterating..."); - while(pList) - { - DumpTable(pList->m_pRecvTable, 0); + const std::string TypeToString(SendPropType type) const { + switch (type) { + case DPT_Int: + return "INT"; + case DPT_Float: + return "FLOAT"; + case DPT_Vector: + return "VECTOR3"; + case DPT_VectorXY: + return "VECTOR2"; + case DPT_Array: + return "ARRAY"; + case DPT_String: + return "STRING"; + case DPT_DataTable: + return "TABLE"; + default: + return "UNKNOWN"; + } + } + void SaveDump() { + ClientClass *pList = g_IBaseClient->GetAllClasses(); + while (pList != nullptr) { + DumpTable(pList->m_pRecvTable, 0); pList = pList->m_pNext; } m_file.close(); } - void DumpTable(RecvTable *pTable, int iLevel) - { - if(!pTable) + void DumpTable(RecvTable *pTable, int iLevel, int parent_offset = 0) { + if (pTable == nullptr) { return; + } - //logging::Info("dumping table.. %s", pTable->GetName()); + for (int j = 0; j < iLevel; j++) { + m_file << "\t"; + } - for(int j = 0; j < iLevel; j++) - m_file << " "; + m_file << pTable->GetName() << "\n"; - m_file << pTable->GetName() << std::endl; + ++iLevel; - iLevel += 2; - - for(int i = 0; i < pTable->GetNumProps(); ++i) - { - //logging::Info("dumping prop.. %i out of %i..", i, pTable->GetNumProps()); + for(int i = 0; i < pTable->GetNumProps(); ++i) { RecvProp *pProp = pTable->GetProp(i); - //logging::Info("it has name %s", pProp->GetName()); - if(!pProp) + if (pProp == nullptr) { continue; + } - if(isdigit(pProp->GetName()[0])) + if (isdigit(pProp->GetName()[0])) { continue; + } - if(pProp->GetDataTable()) - { - DumpTable(pProp->GetDataTable(), iLevel + 1); + if (pProp->GetDataTable()) { + DumpTable(pProp->GetDataTable(), iLevel + 1, pProp->GetOffset()); } for(int j = 0; j < iLevel; j++) - m_file << " "; + m_file << "\t"; int offset = pProp->GetOffset(); - //logging::Info("offset %i", offset); SendPropType type = pProp->GetType(); - //logging::Info("type.. %i", type); - char* typestr = TypeToString(type); - //logging::Info("back from tts"); - //logging::Info("type str %s", typestr); - m_file << pProp->GetName() << " : 0x" << std::hex << offset << " [" << typestr << "]" << std::endl; + m_file << pProp->GetName() << " : 0x" << std::hex << offset << " (0x" << (parent_offset + offset) << ") [" << TypeToString(type) << "]" << "\n"; } - if(iLevel == 2) + if (iLevel == 2) m_file << std::endl; } +private: + std::fstream m_file; }; diff --git a/src/EffectChams.cpp b/src/EffectChams.cpp index 74d5f42c..c34e7ae8 100644 --- a/src/EffectChams.cpp +++ b/src/EffectChams.cpp @@ -22,7 +22,10 @@ static CatVar ammobox(CV_SWITCH, "chams_ammo", "0", "Ammoboxes", "Render chams o static CatVar buildings(CV_SWITCH, "chams_buildings", "0", "Buildings", "Render chams on buildings"); static CatVar stickies(CV_SWITCH, "chams_stickies", "0", "Stickies", "Render chams on stickybombs"); static CatVar teammate_buildings(CV_SWITCH, "chams_teammate_buildings", "0", "Teammate Buildings", "Render chams on teammates buildings"); -static CatVar weapons(CV_SWITCH, "chams_weapons", "1", "Weapons", "Render chams on players weapons"); +static CatVar recursive(CV_SWITCH, "chams_recursive", "1", "Recursive", "Render chams on weapons and cosmetics"); +static CatVar weapons_white(CV_SWITCH, "chams_weapons_white", "1", "White Weapons", "Should chams on weapons be white"); +static CatVar legit(CV_SWITCH, "chams_legit", "0", "Legit chams", "Don't show chams through walls"); +static CatVar singlepass(CV_SWITCH, "chams_singlepass", "0", "Single-pass", "Render chams only once (this disables 'darker' chams on invisible parts of player"); void EffectChams::Init() { logging::Info("Init EffectChams..."); @@ -68,7 +71,7 @@ void EffectChams::EndRenderChams() { g_IVModelRender->ForcedMaterialOverride(nullptr); } -int EffectChams::ChamsColor(IClientEntity* entity) { +rgba_t EffectChams::ChamsColor(IClientEntity* entity) { CachedEntity* ent = ENTITY(entity->entindex()); if (CE_BAD(ent)) return colors::white; if (vfunc(entity, 0xBE, 0)(entity)) { @@ -80,15 +83,15 @@ int EffectChams::ChamsColor(IClientEntity* entity) { switch (ent->m_Type) { case ENTITY_BUILDING: if (!ent->m_bEnemy && !(teammates || teammate_buildings)) { - return 0; + return colors::empty; } if (health) { return colors::Health(ent->m_iHealth, ent->m_iMaxHealth); } break; case ENTITY_PLAYER: - if (!players) return 0; - if (!ent->m_bEnemy && !teammates) return 0; + if (!players) return colors::empty; + if (!ent->m_bEnemy && !teammates) return colors::empty; if (health) { return colors::Health(ent->m_iHealth, ent->m_iMaxHealth); } @@ -102,12 +105,6 @@ bool EffectChams::ShouldRenderChams(IClientEntity* entity) { if (entity->entindex() < 0) return false; CachedEntity* ent = ENTITY(entity->entindex()); if (CE_BAD(ent)) return false; - if (weapons && vfunc(entity, 0xBE, 0)(entity)) { - IClientEntity* owner = vfunc(entity, 0x1C3, 0)(entity); - if (owner) { - return ShouldRenderChams(owner); - } - } switch (ent->m_Type) { case ENTITY_BUILDING: if (!buildings) return false; @@ -141,28 +138,58 @@ bool EffectChams::ShouldRenderChams(IClientEntity* entity) { return false; } +void EffectChams::RenderChamsRecursive(IClientEntity* entity) { + entity->DrawModel(1); + + if (!recursive) return; + + IClientEntity *attach; + int passes = 0; + + attach = g_IEntityList->GetClientEntity(*(int*)((uintptr_t)entity + netvar.m_Collision - 24) & 0xFFF); + while (attach && passes++ < 32) { + if (attach->ShouldDraw()) { + if (entity->GetClientClass()->m_ClassID == RCC_PLAYER && vfunc(attach, 190, 0)(attach)) { + if (weapons_white) { + rgba_t mod_original; + g_IVRenderView->GetColorModulation(mod_original.rgba); + g_IVRenderView->SetColorModulation(colors::white); + attach->DrawModel(1); + g_IVRenderView->SetColorModulation(mod_original.rgba); + } else { + attach->DrawModel(1); + } + } + else + attach->DrawModel(1); + } + attach = g_IEntityList->GetClientEntity(*(int*)((uintptr_t)attach + netvar.m_Collision - 20) & 0xFFF); + } +} + void EffectChams::RenderChams(int idx) { CMatRenderContextPtr ptr(GET_RENDER_CONTEXT); IClientEntity* entity = g_IEntityList->GetClientEntity(idx); if (entity && !entity->IsDormant()) { if (ShouldRenderChams(entity)) { - int color = ChamsColor(entity); - unsigned char _b = (color >> 16) & 0xFF; - unsigned char _g = (color >> 8) & 0xFF; - unsigned char _r = (color) & 0xFF; - float color_1[] = { (float)_r / 255.0f, (float)_g / 255.0f, (float)_b / 255.0f }; - float color_2[] = { color_1[0] * 0.6f, color_1[1] * 0.6f, color_1[2] * 0.6f }; - mat_unlit_z->AlphaModulate(1.0f); - ptr->DepthRange(0.0f, 0.01f); - g_IVRenderView->SetColorModulation(color_1); - g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit_z : mat_lit_z); - entity->DrawModel(1); - //((DrawModelExecute_t)(hooks::hkIVModelRender->GetMethod(hooks::offDrawModelExecute)))(_this, state, info, matrix); - mat_unlit->AlphaModulate(1.0f); - g_IVRenderView->SetColorModulation(color_2); - ptr->DepthRange(0.0f, 1.0f); - g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit : mat_lit); - entity->DrawModel(1); + rgba_t color = ChamsColor(entity); + rgba_t color_2 = color * 0.6f; + if (!legit) { + mat_unlit_z->AlphaModulate(1.0f); + ptr->DepthRange(0.0f, 0.01f); + g_IVRenderView->SetColorModulation(color_2); + g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit_z : mat_lit_z); + + RenderChamsRecursive(entity); + } + + if (legit || !singlepass) { + mat_unlit->AlphaModulate(1.0f); + g_IVRenderView->SetColorModulation(color); + ptr->DepthRange(0.0f, 1.0f); + g_IVModelRender->ForcedMaterialOverride(flat ? mat_unlit : mat_lit); + RenderChamsRecursive(entity); + } } } } diff --git a/src/EffectChams.hpp b/src/EffectChams.hpp index 946d5c71..a55fa069 100644 --- a/src/EffectChams.hpp +++ b/src/EffectChams.hpp @@ -24,11 +24,12 @@ public: inline virtual void Enable( bool bEnable ) { enabled = bEnable; }; inline virtual bool IsEnabled( ) { return enabled; }; - int ChamsColor(IClientEntity* entity); + rgba_t ChamsColor(IClientEntity* entity); bool ShouldRenderChams(IClientEntity* entity); void RenderChams(int idx); void BeginRenderChams(); void EndRenderChams(); + void RenderChamsRecursive(IClientEntity* entity); public: bool init { false }; bool drawing { false }; diff --git a/src/EffectGlow.cpp b/src/EffectGlow.cpp index de9886ed..61b6c247 100644 --- a/src/EffectGlow.cpp +++ b/src/EffectGlow.cpp @@ -34,7 +34,8 @@ static CatVar ammobox(CV_SWITCH, "glow_ammo", "0", "Ammoboxes", "Render glow on static CatVar buildings(CV_SWITCH, "glow_buildings", "0", "Buildings", "Render glow on buildings"); static CatVar stickies(CV_SWITCH, "glow_stickies", "0", "Stickies", "Render glow on stickybombs"); static CatVar teammate_buildings(CV_SWITCH, "glow_teammate_buildings", "0", "Teammate Buildings", "Render glow on teammates buildings"); -//static CatVar weapons_white(CV_SWITCH, "glow_weapons_white", "1", "White Weapon Glow", "Weapons will glow white"); +static CatVar powerups(CV_SWITCH, "glow_powerups", "1", "Powerups"); +static CatVar weapons_white(CV_SWITCH, "glow_weapons_white", "1", "White Weapon Glow", "Weapons will glow white"); struct ShaderStencilState_t { @@ -182,7 +183,7 @@ void EffectGlow::Init() { init = true; } -int EffectGlow::GlowColor(IClientEntity* entity) { +rgba_t EffectGlow::GlowColor(IClientEntity* entity) { static CachedEntity *ent; static IClientEntity *owner; @@ -241,15 +242,13 @@ bool EffectGlow::ShouldRenderGlow(IClientEntity* entity) { } break; case ENTITY_GENERIC: - switch (ent->m_ItemType) { - case ITEM_HEALTH_LARGE: - case ITEM_HEALTH_MEDIUM: - case ITEM_HEALTH_SMALL: + const auto& type = ent->m_ItemType; + if (type >= ITEM_HEALTH_SMALL && type <= ITEM_HEALTH_LARGE) { return medkits; - case ITEM_AMMO_LARGE: - case ITEM_AMMO_MEDIUM: - case ITEM_AMMO_SMALL: + } else if (type >= ITEM_AMMO_SMALL && type <= ITEM_AMMO_SMALL) { return ammobox; + } else if (type >= ITEM_POWERUP_FIRST && type <= ITEM_POWERUP_LAST) { + return powerups; } break; } @@ -333,26 +332,23 @@ void EffectGlow::DrawEntity(IClientEntity* entity) { attach = g_IEntityList->GetClientEntity(*(int*)((uintptr_t)entity + netvar.m_Collision - 24) & 0xFFF); while (attach && passes++ < 32) { if (attach->ShouldDraw()) { - attach->DrawModel(1); + if (weapons_white && entity->GetClientClass()->m_ClassID == RCC_PLAYER && vfunc(attach, 190, 0)(attach)) { + rgba_t mod_original; + g_IVRenderView->GetColorModulation(mod_original.rgba); + g_IVRenderView->SetColorModulation(colors::white); + attach->DrawModel(1); + g_IVRenderView->SetColorModulation(mod_original.rgba); + } + else + attach->DrawModel(1); } attach = g_IEntityList->GetClientEntity(*(int*)((uintptr_t)attach + netvar.m_Collision - 20) & 0xFFF); } } void EffectGlow::RenderGlow(IClientEntity* entity) { - static unsigned char _r, _g, _b; - static int color; - static float color_1[3]; - CMatRenderContextPtr ptr(GET_RENDER_CONTEXT); - color = GlowColor(entity); - _b = (color >> 16) & 0xFF; - _g = (color >> 8) & 0xFF; - _r = (color) & 0xFF; - color_1[0] = (float)_r / 255.0f; - color_1[1] = (float)_g / 255.0f; - color_1[2] = (float)_b / 255.0f; - g_IVRenderView->SetColorModulation(color_1); + g_IVRenderView->SetColorModulation(GlowColor(entity)); g_IVModelRender->ForcedMaterialOverride(mat_unlit_z); DrawEntity(entity); } diff --git a/src/EffectGlow.hpp b/src/EffectGlow.hpp index 04d29f0f..8aaff663 100644 --- a/src/EffectGlow.hpp +++ b/src/EffectGlow.hpp @@ -31,7 +31,7 @@ public: void DrawEntity(IClientEntity* entity); void DrawToStencil(IClientEntity* entity); void DrawToBuffer(IClientEntity* entity); - int GlowColor(IClientEntity* entity); + rgba_t GlowColor(IClientEntity* entity); bool ShouldRenderGlow(IClientEntity* entity); void RenderGlow(IClientEntity* entity); void BeginRenderGlow(); diff --git a/src/angles.cpp b/src/angles.cpp new file mode 100644 index 00000000..c0b870fe --- /dev/null +++ b/src/angles.cpp @@ -0,0 +1,33 @@ +/* + * angles.cpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#include "angles.hpp" + +namespace angles { + +angle_data_s data_[32]; + +void Update() { + for (int i = 1; i < 33; i++) { + auto& d = data_idx(i); + CachedEntity* ent = ENTITY(i); + if (CE_GOOD(ent) && !CE_BYTE(ent, netvar.iLifeState)) { + if (!d.good) { + memset(&d, 0, sizeof(angle_data_s)); + } + if (i == g_IEngine->GetLocalPlayer()) { + d.push(g_pUserCmd->viewangles); + } else { + d.push(CE_VECTOR(ent, netvar.m_angEyeAngles)); + } + } else { + d.good = false; + } + } +} + +} diff --git a/src/angles.hpp b/src/angles.hpp new file mode 100644 index 00000000..7aed4db9 --- /dev/null +++ b/src/angles.hpp @@ -0,0 +1,80 @@ +/* + * angles.hpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#pragma once + +#include "common.h" +#include "logging.h" + +namespace angles { + +struct angle_data_s { + static constexpr size_t count = 16; + inline void push(const Vector& angle) { + if (not angle.x and not angle.y) return; + good = true; + angles[angle_index] = angle; + if (++angle_index >= count) { + angle_index = 0; + } + /*if (angle_count > 0) { + int ai = angle_index - 2; + if (ai < 0) ai = count - 1; + float dx = std::abs(angles[ai].x - angle.x); + float dy = std::abs(angles[ai].y - angle.y); + if (sqrt(dx * dx + dy * dy) > 45.0f) { + //logging::Info("%.2f %.2f %.2f", dx, dy, sqrt(dx * dx + dy * dy)); + } + }*/ + if (angle_count < count) { + angle_count++; + } + } + inline float deviation(int steps) const { + int j = angle_index - 2; + int k = j + 1; + float hx = 0, hy = 0; + for (int i = 0; i < steps && i < angle_count; i++) { + if (j < 0) j = count + j; + if (k < 0) k = count + k; + + float dev_x = std::abs(angles[k].x - angles[j].x); + float dev_y = std::abs(angles[k].y - angles[j].y); + if (dev_x > hx) hx = dev_x; + if (dev_y > hy) hy = dev_y; + + //logging::Info("1: %.2f %.2f | 2: %.2f %.2f | dev: %.2f", angles[k].x, angles[k].y, angles[j].x, angles[j].y, sqrt(dev_x * dev_x + dev_y * dev_y)); + + --j; + --k; + } + if (hy > 180) hy = 360 - hy; + return sqrt(hx * hx + hy * hy); + } + + Vector angles[count] {}; + bool good { false }; + int angle_index { 0 }; + int angle_count { 0 }; +}; + +extern angle_data_s data_[32]; + +void Update(); + +inline angle_data_s& data_idx(int index) { + if (index < 1 || index > 32) { + throw std::out_of_range("Angle table entity index out of range"); + } + return data_[index - 1]; +} + + +inline angle_data_s& data(const CachedEntity* entity) { + return data_idx(entity->m_IDX); +} +} diff --git a/src/atlas.cpp b/src/atlas.cpp new file mode 100644 index 00000000..f1230bcc --- /dev/null +++ b/src/atlas.cpp @@ -0,0 +1,42 @@ +/* + * atlas.cpp + * + * Created on: May 20, 2017 + * Author: nullifiedcat + */ + +#ifndef TEXTMODE + +#include "atlas.hpp" + +#include "drawing.h" +#include "drawgl.hpp" +#include "logging.h" + +namespace textures { + +AtlasTexture::AtlasTexture(float x, float y, float sx, float sy) { + tex_coords[0] = ftgl::vec2{ (x + 0.5f) / atlas_width, (y + sy - 0.5f) / atlas_height }; + tex_coords[1] = ftgl::vec2{ (x - 0.5f + sx) / atlas_width, (y + 0.5f) / atlas_height }; +} + +void AtlasTexture::Draw(float x, float y, float sx, float sy) { + drawgl::TexturedRect(x, y, sx, sy, tex_coords[0].x, tex_coords[0].y, tex_coords[1].x, tex_coords[1].y); +} + +GLuint texture; + +void Init() { + glEnable(GL_TEXTURE_2D); + glGenTextures(1, &texture); + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, atlas_width, atlas_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &_binary_atlas_start); +} + +} + +#endif diff --git a/src/atlas.hpp b/src/atlas.hpp new file mode 100644 index 00000000..02552d73 --- /dev/null +++ b/src/atlas.hpp @@ -0,0 +1,38 @@ +/* + * atlas.hpp + * + * Created on: May 20, 2017 + * Author: nullifiedcat + */ + +#ifndef ATLAS_HPP_ +#define ATLAS_HPP_ + +#include +#include + +extern "C" { +#include +} + +extern char _binary_atlas_start; + +namespace textures { + +constexpr float atlas_width = 1024.0f; +constexpr float atlas_height = 512.0f; + +class AtlasTexture { +public: + AtlasTexture(float x, float y, float sx, float sy); + void Draw(float x, float y, float sx, float sy); +public: + ftgl::vec2 tex_coords[2]; +}; + +extern GLuint texture; + +void Init(); +} + +#endif /* ATLAS_HPP_ */ diff --git a/src/averager.hpp b/src/averager.hpp new file mode 100644 index 00000000..c251eb19 --- /dev/null +++ b/src/averager.hpp @@ -0,0 +1,100 @@ +/* + * averager.hpp + * + * Created on: May 26, 2017 + * Author: nullifiedcat + */ + +#ifndef AVERAGER_HPP_ +#define AVERAGER_HPP_ + +#include +#include +#include +#include +#include + +/* + * Averager class. + * Can return average of last N pushed values, older values are discarded. + */ + +template +class Averager { +public: + /* + * Initialize Averager with a given size + */ + inline Averager(size_t _size) { + resize(_size); + } + /* + * Resize the internal array of Averager + * Changes value_count_ and value_index_ so they don't become Out-Of-Bounds + */ + inline void resize(size_t _size) { + size_ = _size; + values_.resize(_size); + value_count_ = std::min(_size, value_count_); + value_index_ = std::min(_size - 1, value_index_); + } + /* + * Resets Averager state + */ + inline void reset(const T& def = 0.0f) { + value_count_ = 0; + value_index_ = 0; + value_ = def; + } + /* + * Pushes a new value and recalculates the sum, discards oldest value + */ + inline void push(T value) { + if (value_count_ > value_index_) value_ -= values_[value_index_]; + values_[value_index_++] = value; + value_ += value; + if (value_index_ > value_count_) { + value_count_ = value_index_; + } + if (value_index_ >= size_) { + value_index_ = 0; + } + } + /* + * Pushes all values in initializer list + */ + inline void push(std::initializer_list list) { + for (const auto& f : list) { + push(f); + } + } + /* + * Returns the average value, returns 0 if no values were pushed + */ + inline T average() const { + if (value_count_) + return value_ / value_count_; + else return T{}; + } + /* + * Size of internal buffer + */ + inline size_t size() const { + return size_; + } + /* + * Amount of values stored in the buffer + */ + inline size_t value_count() const { + return value_count_; + } +private: + std::vector values_; + size_t size_ { 0 }; + size_t value_count_ { 0 }; + size_t value_index_ { 0 }; + T value_ {}; +}; + + +#endif /* AVERAGER_HPP_ */ diff --git a/src/backpacktf.cpp b/src/backpacktf.cpp new file mode 100644 index 00000000..9f41faf8 --- /dev/null +++ b/src/backpacktf.cpp @@ -0,0 +1,176 @@ +/* + * backpacktf.cpp + * + * Created on: Jul 23, 2017 + * Author: nullifiedcat + */ + +#include "backpacktf.hpp" +#include "json.hpp" +#include "https_request.hpp" + +#include "common.h" + +#include "cvwrapper.h" + +#include +#include + +namespace backpacktf { + +std::unordered_map cache {}; +std::queue pending_queue {}; +std::mutex queue_mutex {}; +std::mutex cache_mutex {}; + +std::string api_key_s = ""; +bool valid_api_key = false; + +CatVar enable_bptf(CV_SWITCH, "bptf_enable", "0", "Enable backpack.tf", "Enable backpack.tf integration\nYou have to set your API key in cat_bptf_key"); +CatCommand api_key("bptf_key", "Set API Key", [](const CCommand& args) { + api_key_s = args.ArgS(); + logging::Info("API key changed!"); + valid_api_key = false; + if (api_key_s.length() != 24) { + logging::Info("API key must be exactly 24 characters long"); + valid_api_key = false; + } else { + valid_api_key = true; + } +}); + + +void store_data(unsigned id, float value, bool no_value, bool outdated_value); + +void processing_thread() { + logging::Info("[bp.tf] Starting the thread"); + while (true) { + if (enabled()) { + try { + std::vector batch {}; + int count = 0; + { + std::lock_guard lock(queue_mutex); + while (not pending_queue.empty() && ++count < 100) { + batch.push_back(pending_queue.front()); + pending_queue.pop(); + } + } + if (count) { + logging::Info("[bp.tf] Requesting data for %d users", count); + std::string id_list = ""; + for (const auto& x : batch) { + x->pending = false; + id_list += format("[U:1:", x->id, "],"); + } + // Remove trailing ',' + id_list = id_list.substr(0, id_list.length() - 1); + std::string query = format("steamids=", id_list, "&key=", api_key_s); + try { + auto sock = https::RAII_HTTPS_Socket("backpack.tf"); + std::string response = sock.get("/api/users/info/v1?" + query); + if (response.find("HTTP/1.1 200 OK\r\n") != 0) { + size_t status = response.find("\r\n"); + throw std::runtime_error("Response isn't 200 OK! It's " + response.substr(0, status)); + } + + std::string body = response.substr(response.find("\r\n\r\n") + 4); + + try { + nlohmann::json data = nlohmann::json::parse(body); + nlohmann::json users = data["users"]; + std::lock_guard lock(cache_mutex); + for (auto it = users.begin(); it != users.end(); ++it) { + unsigned userid = strtoul(it.key().substr(5).c_str(), nullptr, 10); + try { + unsigned userid = strtoul(it.key().substr(5).c_str(), nullptr, 10); + const auto& v = it.value(); + if (not v.is_object()) { + logging::Info("Data for %u (%s) is not an object!", userid, it.key()); + continue; + } + std::string name = v.at("name"); + logging::Info("Parsing data for user %u (%s)", userid, name.c_str()); + if (v.find("inventory") == v.end()) { + store_data(userid, 0, true, false); + continue; + } + const auto& inv = v.at("inventory").at("440"); + if (inv.find("value") == inv.end()) { + store_data(userid, 0, true, false); + } else { + float value = float(inv["value"]); + unsigned updated = unsigned(inv["updated"]); + store_data(userid, value * REFINED_METAL_PRICE, false, (unsigned(time(0)) - updated > OUTDATED_AGE)); + } + } catch (std::exception& ex) { + logging::Info("Error while parsing user %s: %s", it.key().c_str(), ex.what()); + } + } + } catch (std::exception& e) { + logging::Info("[bp.tf] Exception while parsing response: %s", e.what()); + } + + } catch (std::exception& e) { + logging::Info("[bp.tf] HTTPS exception: %s", e.what()); + } + } + } catch (std::exception& e) { + logging::Info("[bp.tf] Thread exception: %s", e.what()); + } + } + sleep(REQUEST_INTERVAL); + } +} + +void request_data(unsigned id) { + if (cache[id].pending) return; + cache[id].pending = true; + { + std::lock_guard lock(queue_mutex); + pending_queue.push(&cache[id]); + } +} + +bool enabled() { + return enable_bptf && valid_api_key; +} + +backpack_data_s& access_data(unsigned id) { + try { + return cache.at(id); + } catch (std::out_of_range& oor) { + cache.emplace(id, backpack_data_s {}); + cache.at(id).id = id; + return cache.at(id); + } +} + +void store_data(unsigned id, float value, bool none, bool outdated) { + auto& d = access_data(id); + d.last_request = unsigned(time(0)); + d.bad = false; + d.value = value; + d.no_value = none; + d.outdated_value = outdated; + d.pending = false; +} + +const backpack_data_s& get_data(unsigned id) { + auto& d = access_data(id); + if (d.bad || ((unsigned)time(0) - MAX_CACHE_AGE > cache[id].last_request)) { + request_data(id); + } + return d; +} + +std::thread& GetBackpackTFThread() { + static std::thread thread(processing_thread); + return thread; +} + +void init() { + GetBackpackTFThread(); +} + +} diff --git a/src/backpacktf.hpp b/src/backpacktf.hpp new file mode 100644 index 00000000..25793464 --- /dev/null +++ b/src/backpacktf.hpp @@ -0,0 +1,35 @@ +/* + * backpacktf.hpp + * + * Created on: Jul 23, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class CatVar; + +namespace backpacktf { + +constexpr float REFINED_METAL_PRICE = 0.075f; // $ +constexpr unsigned REQUEST_INTERVAL = 10; // Make a backpack.tf request every 30 seconds +constexpr unsigned MAX_CACHE_AGE = 60 * 30; +constexpr unsigned OUTDATED_AGE = 60 * 60 * 24 * 3; // After how many seconds backpack is marked "outdated" (possibly private) + +extern CatVar enable_bptf; + +struct backpack_data_s { + bool pending { false }; + bool bad { true }; + bool no_value { false }; // No recorded value + bool outdated_value { false }; // Outdated value. Private inventory? + unsigned last_request { 0 }; + float value { 0 }; + unsigned id { 0 }; +}; + +const backpack_data_s& get_data(unsigned id); +void init(); +bool enabled(); + +} diff --git a/src/base64.h b/src/base64.h new file mode 100644 index 00000000..27ad2f92 --- /dev/null +++ b/src/base64.h @@ -0,0 +1,271 @@ +#ifndef BASE64_H +#define BASE64_H + +/* + * + Copyright (C) 2013 Tomas Kislan + Copyright (C) 2013 Adam Rudd + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * + * https://github.com/tkislan/base64 + */ + +#include + +const char kBase64Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +class Base64 { + public: + static bool Encode(const std::string &in, std::string *out) { + int i = 0, j = 0; + size_t enc_len = 0; + unsigned char a3[3]; + unsigned char a4[4]; + + out->resize(EncodedLength(in)); + + int input_len = in.size(); + std::string::const_iterator input = in.begin(); + + while (input_len--) { + a3[i++] = *(input++); + if (i == 3) { + a3_to_a4(a4, a3); + + for (i = 0; i < 4; i++) { + (*out)[enc_len++] = kBase64Alphabet[a4[i]]; + } + + i = 0; + } + } + + if (i) { + for (j = i; j < 3; j++) { + a3[j] = '\0'; + } + + a3_to_a4(a4, a3); + + for (j = 0; j < i + 1; j++) { + (*out)[enc_len++] = kBase64Alphabet[a4[j]]; + } + + while ((i++ < 3)) { + (*out)[enc_len++] = '='; + } + } + + return (enc_len == out->size()); + } + + static bool Encode(const char *input, size_t input_length, char *out, size_t out_length) { + int i = 0, j = 0; + char *out_begin = out; + unsigned char a3[3]; + unsigned char a4[4]; + + size_t encoded_length = EncodedLength(input_length); + + if (out_length < encoded_length) return false; + + while (input_length--) { + a3[i++] = *input++; + if (i == 3) { + a3_to_a4(a4, a3); + + for (i = 0; i < 4; i++) { + *out++ = kBase64Alphabet[a4[i]]; + } + + i = 0; + } + } + + if (i) { + for (j = i; j < 3; j++) { + a3[j] = '\0'; + } + + a3_to_a4(a4, a3); + + for (j = 0; j < i + 1; j++) { + *out++ = kBase64Alphabet[a4[j]]; + } + + while ((i++ < 3)) { + *out++ = '='; + } + } + + return (out == (out_begin + encoded_length)); + } + + static bool Decode(const std::string &in, std::string *out) { + int i = 0, j = 0; + size_t dec_len = 0; + unsigned char a3[3]; + unsigned char a4[4]; + + int input_len = in.size(); + std::string::const_iterator input = in.begin(); + + out->resize(DecodedLength(in)); + + while (input_len--) { + if (*input == '=') { + break; + } + + a4[i++] = *(input++); + if (i == 4) { + for (i = 0; i <4; i++) { + a4[i] = b64_lookup(a4[i]); + } + + a4_to_a3(a3,a4); + + for (i = 0; i < 3; i++) { + (*out)[dec_len++] = a3[i]; + } + + i = 0; + } + } + + if (i) { + for (j = i; j < 4; j++) { + a4[j] = '\0'; + } + + for (j = 0; j < 4; j++) { + a4[j] = b64_lookup(a4[j]); + } + + a4_to_a3(a3,a4); + + for (j = 0; j < i - 1; j++) { + (*out)[dec_len++] = a3[j]; + } + } + + return (dec_len == out->size()); + } + + static bool Decode(const char *input, size_t input_length, char *out, size_t out_length) { + int i = 0, j = 0; + char *out_begin = out; + unsigned char a3[3]; + unsigned char a4[4]; + + size_t decoded_length = DecodedLength(input, input_length); + + if (out_length < decoded_length) return false; + + while (input_length--) { + if (*input == '=') { + break; + } + + a4[i++] = *(input++); + if (i == 4) { + for (i = 0; i <4; i++) { + a4[i] = b64_lookup(a4[i]); + } + + a4_to_a3(a3,a4); + + for (i = 0; i < 3; i++) { + *out++ = a3[i]; + } + + i = 0; + } + } + + if (i) { + for (j = i; j < 4; j++) { + a4[j] = '\0'; + } + + for (j = 0; j < 4; j++) { + a4[j] = b64_lookup(a4[j]); + } + + a4_to_a3(a3,a4); + + for (j = 0; j < i - 1; j++) { + *out++ = a3[j]; + } + } + + return (out == (out_begin + decoded_length)); + } + + static int DecodedLength(const char *in, size_t in_length) { + int numEq = 0; + + const char *in_end = in + in_length; + while (*--in_end == '=') ++numEq; + + return ((6 * in_length) / 8) - numEq; + } + + static int DecodedLength(const std::string &in) { + int numEq = 0; + int n = in.size(); + + for (std::string::const_reverse_iterator it = in.rbegin(); *it == '='; ++it) { + ++numEq; + } + + return ((6 * n) / 8) - numEq; + } + + inline static int EncodedLength(size_t length) { + return (length + 2 - ((length + 2) % 3)) / 3 * 4; + } + + inline static int EncodedLength(const std::string &in) { + return EncodedLength(in.length()); + } + + inline static void StripPadding(std::string *in) { + while (!in->empty() && *(in->rbegin()) == '=') in->resize(in->size() - 1); + } + + private: + static inline void a3_to_a4(unsigned char * a4, unsigned char * a3) { + a4[0] = (a3[0] & 0xfc) >> 2; + a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4); + a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6); + a4[3] = (a3[2] & 0x3f); + } + + static inline void a4_to_a3(unsigned char * a3, unsigned char * a4) { + a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4); + a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2); + a3[2] = ((a4[2] & 0x3) << 6) + a4[3]; + } + + static inline unsigned char b64_lookup(unsigned char c) { + if(c >='A' && c <='Z') return c - 'A'; + if(c >='a' && c <='z') return c - 71; + if(c >='0' && c <='9') return c + 4; + if(c == '+') return 62; + if(c == '/') return 63; + return 255; + } +}; + + + +#endif // BASE64_H diff --git a/src/chatlog.cpp b/src/chatlog.cpp new file mode 100644 index 00000000..e3d98aa3 --- /dev/null +++ b/src/chatlog.cpp @@ -0,0 +1,88 @@ +/* + * chatlog.cpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#include "common.h" +#include "init.hpp" + +#include +#include + +namespace chatlog { + +CatVar enabled(CV_SWITCH, "chat_log", "0", "Chat log", "Log chat to file"); +CatVar message_template(CV_STRING, "chat_log_template", "[%t] [U:1:%u] %n: %m", "Log template", "%u - SteamID\n%n - name\n%m - message\n%t - time"); +CatVar dont_log_spam(CV_SWITCH, "chat_log_nospam", "1", "No Spam", "Don't log your messages if spam is active"); +CatVar dont_log_ipc(CV_SWITCH, "chat_log_noipc", "1", "No IPC", "Don't log messages sent by bots"); + +class RAIILog { +public: + RAIILog() { + open(); + } + ~RAIILog() { + stream.close(); + } + void open() { + logging::Info("Trying to open log file"); + uid_t uid = geteuid(); + struct passwd *pw = getpwuid(uid); + std::string uname = ""; + if (pw) { + uname = std::string(pw->pw_name); + } + stream.open("cathook/chat-" + uname + ".log", std::ios::out | std::ios::app); + } + void log(const std::string& msg) { + if (stream.bad() or not stream.is_open()) { + logging::Info("[ERROR] RAIILog stream is bad!"); + open(); + return; + } + stream << msg << "\n"; + stream.flush(); + } + std::ofstream stream; +}; + +RAIILog& logger() { + static RAIILog object {}; + return object; +} + +void LogMessage(int eid, std::string message) { + if (!enabled) { + return; + } + if (dont_log_spam && hacks::shared::spam::spam_source and eid == g_IEngine->GetLocalPlayer()) + return; + player_info_s info; + if (not g_IEngine->GetPlayerInfo(eid, &info)) + return; + if (dont_log_ipc && playerlist::AccessData(info.friendsID).state == playerlist::k_EState::IPC) + return; + std::string name(info.name); + for (auto& x : name) { + if (x == '\n' || x == '\r') x = '*'; + } + for (auto& x : message) { + if (x == '\n' || x == '\r') x = '*'; + } + time_t current_time; + struct tm * time_info; + char timeString[9]; + time(¤t_time); + time_info = localtime(¤t_time); + strftime(timeString, sizeof(timeString), "%H:%M:%S", time_info); + std::string msg(message_template.GetString()); + ReplaceString(msg, "%t", std::string(timeString)); + ReplaceString(msg, "%u", std::to_string(info.friendsID)); + ReplaceString(msg, "%n", name); + ReplaceString(msg, "%m", message); + logger().log(msg); +} + +} diff --git a/src/chatlog.hpp b/src/chatlog.hpp new file mode 100644 index 00000000..bd5ed276 --- /dev/null +++ b/src/chatlog.hpp @@ -0,0 +1,14 @@ +/* + * chatlog.hpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#pragma once + +namespace chatlog { + +void LogMessage(int eid, std::string message); + +} diff --git a/src/chatstack.h b/src/chatstack.h index 4026a9fd..b9f6fbdb 100644 --- a/src/chatstack.h +++ b/src/chatstack.h @@ -30,6 +30,6 @@ void Reset(); extern std::stack stack; extern float last_say; -}; +} #endif /* CHATSTACK_H_ */ diff --git a/src/classinfo/classinfo.cpp b/src/classinfo/classinfo.cpp index 7624b56c..192b4266 100644 --- a/src/classinfo/classinfo.cpp +++ b/src/classinfo/classinfo.cpp @@ -30,6 +30,9 @@ void InitClassTable() { if (IsCSS()) { client_class_list = (client_classes::dummy*)&client_classes::css_list; } + if (IsDynamic()) { + client_class_list = (client_classes::dummy*)&client_classes::dynamic_list; + } if (!client_class_list) { logging::Info("FATAL: Cannot initialize class list! Game will crash if cathook is enabled."); //cathook = false; diff --git a/src/classinfo/classinfo.hpp b/src/classinfo/classinfo.hpp index 661a5a95..c74fb3b2 100644 --- a/src/classinfo/classinfo.hpp +++ b/src/classinfo/classinfo.hpp @@ -5,6 +5,9 @@ * Author: nullifiedcat */ +#ifndef CLASSINFO_HPP_ +#define CLASSINFO_HPP_ + #include "../common.h" #include "dummy.gen.hpp" @@ -13,6 +16,7 @@ #include "tf2c.gen.hpp" #include "hl2dm.gen.hpp" #include "css.gen.hpp" +#include "dynamic.gen.hpp" #include "tf2_constexpr.gen.hpp" #include "tf2c_constexpr.gen.hpp" @@ -23,15 +27,16 @@ void InitClassTable(); extern client_classes::dummy* client_class_list; -#ifndef BUILD_GAME +#if not defined(BUILD_GAME) or defined(DYNAMIC_CLASSES) #define CL_CLASS(x) (client_class_list->x) #else #define CL_CLASS(x) (client_classes_constexpr::BUILD_GAME::x) #endif -#define RCC_CLASS(tf, hl2dm, css) \ +#define RCC_CLASS(tf, hl2dm, css, def) \ (IsTF() ? CL_CLASS(tf) : (IsHL2DM() ? CL_CLASS(hl2dm) : (IsCSS() ? CL_CLASS(css) : 0))) -#define RCC_PLAYER RCC_CLASS(CTFPlayer, CHL2MP_Player, CCSPlayer) -#define RCC_PLAYERRESOURCE RCC_CLASS(CTFPlayerResource, CPlayerResource, CCSPlayerResource) +#define RCC_PLAYER RCC_CLASS(CTFPlayer, CHL2MP_Player, CCSPlayer, 0) +#define RCC_PLAYERRESOURCE RCC_CLASS(CTFPlayerResource, CPlayerResource, CCSPlayerResource, 0) +#endif /* CLASSINFO_HPP_ */ diff --git a/src/classinfo/dab.gen.hpp b/src/classinfo/dab.gen.hpp new file mode 100644 index 00000000..9609eb75 --- /dev/null +++ b/src/classinfo/dab.gen.hpp @@ -0,0 +1,527 @@ +/* + AUTO-GENERATED HEADER - DO NOT MODIFY + NON-CONSTEXPR HEADER FOR dab +*/ + +#ifndef dab_AUTOGEN_HPP +#define dab_AUTOGEN_HPP + +namespace client_classes { + + class dab { + public: + int CTETFParticleEffect { 0 }; + int CTETFExplosion { 0 }; + int CTETFBlood { 0 }; + int CTFTankBoss { 0 }; + int CTFBaseBoss { 0 }; + int CBossAlpha { 0 }; + int CZombie { 0 }; + int CMerasmusDancer { 0 }; + int CMerasmus { 0 }; + int CHeadlessHatman { 0 }; + int CEyeballBoss { 0 }; + int CTFWeaponSapper { 0 }; + int CTFWeaponBuilder { 0 }; + int C_TFWeaponBuilder { 0 }; + int CTFTeam { 0 }; + int CTFTauntProp { 0 }; + int CTFProjectile_Rocket { 0 }; + int CTFProjectile_Flare { 0 }; + int CTFProjectile_EnergyBall { 0 }; + int CTFProjectile_GrapplingHook { 0 }; + int CTFProjectile_HealingBolt { 0 }; + int CTFProjectile_Arrow { 0 }; + int CTFPlayerResource { 0 }; + int CTFPlayer { 0 }; + int CTFRagdoll { 0 }; + int CTEPlayerAnimEvent { 143 }; + int CTFPasstimeLogic { 0 }; + int CPasstimeBall { 0 }; + int CTFObjectiveResource { 0 }; + int CTFGlow { 0 }; + int CTEFireBullets { 131 }; + int CTFBuffBanner { 0 }; + int CTFAmmoPack { 0 }; + int CObjectTeleporter { 0 }; + int CObjectSentrygun { 0 }; + int CTFProjectile_SentryRocket { 0 }; + int CObjectSapper { 0 }; + int CObjectCartDispenser { 0 }; + int CObjectDispenser { 0 }; + int CMonsterResource { 0 }; + int CFuncRespawnRoomVisualizer { 0 }; + int CFuncRespawnRoom { 0 }; + int CFuncPasstimeGoal { 0 }; + int CFuncForceField { 0 }; + int CCaptureZone { 0 }; + int CCurrencyPack { 0 }; + int CBaseObject { 0 }; + int CTFBotHintEngineerNest { 0 }; + int CBotNPCMinion { 0 }; + int CBotNPC { 0 }; + int CRagdollPropAttached { 84 }; + int CRagdollProp { 83 }; + int NextBotCombatCharacter { 0 }; + int CWaterBullet { 158 }; + int CFuncMonitor { 52 }; + int CWorld { 174 }; + int CWaterLODControl { 159 }; + int CVGuiScreen { 156 }; + int CPropJeep { 80 }; + int CPropVehicleChoreoGeneric { 0 }; + int CTEWorldDecal { 155 }; + int CTESpriteSpray { 152 }; + int CTESprite { 151 }; + int CTESparks { 150 }; + int CTESmoke { 149 }; + int CTEShowLine { 147 }; + int CTEProjectedDecal { 145 }; + int CTEPlayerDecal { 144 }; + int CTEPhysicsProp { 142 }; + int CTEParticleSystem { 141 }; + int CTEMuzzleFlash { 140 }; + int CTELargeFunnel { 138 }; + int CTEKillPlayerAttachments { 137 }; + int CTEImpact { 136 }; + int CTEGlowSprite { 135 }; + int CTEShatterSurface { 146 }; + int CTEFootprintDecal { 133 }; + int CTEFizz { 132 }; + int CTEExplosion { 130 }; + int CTEEnergySplash { 129 }; + int CTEEffectDispatch { 128 }; + int CTEDynamicLight { 127 }; + int CTEDecal { 125 }; + int CTEClientProjectile { 124 }; + int CTEBubbleTrail { 123 }; + int CTEBubbles { 122 }; + int CTEBSPDecal { 121 }; + int CTEBreakModel { 120 }; + int CTEBloodStream { 119 }; + int CTEBloodSprite { 118 }; + int CTEBeamSpline { 117 }; + int CTEBeamRingPoint { 116 }; + int CTEBeamRing { 115 }; + int CTEBeamPoints { 114 }; + int CTEBeamLaser { 113 }; + int CTEBeamFollow { 112 }; + int CTEBeamEnts { 111 }; + int CTEBeamEntPoint { 110 }; + int CTEBaseBeam { 109 }; + int CTEArmorRicochet { 108 }; + int CTEMetalSparks { 139 }; + int CTest_ProxyToggle_Networkable { 153 }; + int CTestTraceline { 154 }; + int CTesla { 148 }; + int CTeamTrainWatcher { 0 }; + int CBaseTeamObjectiveResource { 0 }; + int CTeam { 107 }; + int CSun { 106 }; + int CSteamJet { 105 }; + int CParticlePerformanceMonitor { 66 }; + int CSpotlightEnd { 101 }; + int DustTrail { 175 }; + int CFireTrail { 44 }; + int SporeTrail { 181 }; + int SporeExplosion { 180 }; + int RocketTrail { 178 }; + int SmokeTrail { 179 }; + int CSmokeStack { 99 }; + int CSlideshowDisplay { 98 }; + int CShadowControl { 97 }; + int CSceneEntity { 87 }; + int CRopeKeyframe { 86 }; + int CRagdollManager { 82 }; + int CPropVehicleDriveable { 81 }; + int CPhysicsPropMultiplayer { 71 }; + int CPhysBoxMultiplayer { 69 }; + int CBasePropDoor { 16 }; + int CDynamicProp { 30 }; + int CPointCommentaryNode { 76 }; + int CPointCamera { 75 }; + int CPlayerResource { 74 }; + int CPlasma { 73 }; + int CPhysMagnet { 72 }; + int CPhysicsProp { 70 }; + int CPhysBox { 68 }; + int CParticleSystem { 67 }; + int ParticleSmokeGrenade { 177 }; + int CParticleFire { 65 }; + int MovieExplosion { 176 }; + int CMaterialModifyControl { 64 }; + int CLightGlow { 63 }; + int CInfoOverlayAccessor { 62 }; + int CTEGaussExplosion { 134 }; + int CFuncTrackTrain { 57 }; + int CFuncSmokeVolume { 56 }; + int CFuncRotating { 55 }; + int CFuncReflectiveGlass { 54 }; + int CFuncOccluder { 53 }; + int CFunc_LOD { 48 }; + int CTEDust { 126 }; + int CFunc_Dust { 47 }; + int CFuncConveyor { 50 }; + int CBreakableSurface { 23 }; + int CFuncAreaPortalWindow { 49 }; + int CFish { 45 }; + int CEntityFlame { 33 }; + int CFireSmoke { 43 }; + int CEnvTonemapController { 41 }; + int CEnvScreenEffect { 39 }; + int CEnvScreenOverlay { 40 }; + int CEnvProjectedTexture { 37 }; + int CEnvParticleScript { 36 }; + int CFogController { 46 }; + int CEntityParticleTrail { 34 }; + int CEntityDissolve { 32 }; + int CEnvQuadraticBeam { 38 }; + int CEmbers { 31 }; + int CEnvWind { 42 }; + int CPrecipitation { 78 }; + int CDynamicLight { 29 }; + int CColorCorrectionVolume { 27 }; + int CColorCorrection { 26 }; + int CBreakableProp { 22 }; + int CBaseTempEntity { 18 }; + int CBasePlayer { 14 }; + int CBaseFlex { 10 }; + int CBaseEntity { 9 }; + int CBaseDoor { 8 }; + int CBaseCombatCharacter { 6 }; + int CBaseAnimatingOverlay { 5 }; + int CBoneFollower { 21 }; + int CBaseAnimating { 4 }; + int CInfoLightingRelative { 61 }; + int CAI_BaseNPC { 0 }; + int CWeaponIFMSteadyCam { 0 }; + int CWeaponIFMBaseCamera { 0 }; + int CWeaponIFMBase { 0 }; + int CTFWearableLevelableItem { 0 }; + int CTFWearableDemoShield { 0 }; + int CTFWearableRobotArm { 0 }; + int CTFRobotArm { 0 }; + int CTFWrench { 0 }; + int CTFProjectile_ThrowableBreadMonster { 0 }; + int CTFProjectile_ThrowableBrick { 0 }; + int CTFProjectile_ThrowableRepel { 0 }; + int CTFProjectile_Throwable { 0 }; + int CTFThrowable { 0 }; + int CTFSyringeGun { 0 }; + int CTFKatana { 0 }; + int CTFSword { 0 }; + int CSniperDot { 0 }; + int CTFSniperRifleClassic { 0 }; + int CTFSniperRifleDecap { 0 }; + int CTFSniperRifle { 0 }; + int CTFChargedSMG { 0 }; + int CTFSMG { 0 }; + int CTFShovel { 0 }; + int CTFShotgunBuildingRescue { 0 }; + int CTFPEPBrawlerBlaster { 0 }; + int CTFSodaPopper { 0 }; + int CTFShotgun_Revenge { 0 }; + int CTFScatterGun { 0 }; + int CTFShotgun_Pyro { 0 }; + int CTFShotgun_HWG { 0 }; + int CTFShotgun_Soldier { 0 }; + int CTFShotgun { 0 }; + int CTFCrossbow { 0 }; + int CTFRocketLauncher_Mortar { 0 }; + int CTFRocketLauncher_AirStrike { 0 }; + int CTFRocketLauncher_DirectHit { 0 }; + int CTFRocketLauncher { 0 }; + int CTFRevolver { 0 }; + int CTFDRGPomson { 0 }; + int CTFRaygun { 0 }; + int CTFPistol_ScoutSecondary { 0 }; + int CTFPistol_ScoutPrimary { 0 }; + int CTFPistol_Scout { 0 }; + int CTFPistol { 0 }; + int CTFPipebombLauncher { 0 }; + int CTFWeaponPDA_Spy { 0 }; + int CTFWeaponPDA_Engineer_Destroy { 0 }; + int CTFWeaponPDA_Engineer_Build { 0 }; + int CTFWeaponPDAExpansion_Teleporter { 0 }; + int CTFWeaponPDAExpansion_Dispenser { 0 }; + int CTFWeaponPDA { 0 }; + int CPasstimeGun { 0 }; + int CTFParticleCannon { 0 }; + int CTFParachute_Secondary { 0 }; + int CTFParachute_Primary { 0 }; + int CTFParachute { 0 }; + int CTFMinigun { 0 }; + int CTFMedigunShield { 0 }; + int CWeaponMedigun { 0 }; + int CTFMechanicalArm { 0 }; + int CTFLunchBox_Drink { 0 }; + int CTFLunchBox { 0 }; + int CLaserDot { 0 }; + int CTFLaserPointer { 0 }; + int CTFKnife { 0 }; + int CTFProjectile_Cleaver { 0 }; + int CTFProjectile_JarMilk { 0 }; + int CTFProjectile_Jar { 0 }; + int CTFCleaver { 0 }; + int CTFJarMilk { 0 }; + int CTFJar { 0 }; + int CTFWeaponInvis { 0 }; + int CTFGrenadePipebombProjectile { 0 }; + int CTFCannon { 0 }; + int CTFGrenadeLauncher { 0 }; + int CTFGrapplingHook { 0 }; + int CTFFlareGun_Revenge { 0 }; + int CTFFlareGun { 0 }; + int CTFFlameRocket { 0 }; + int CTFFlameThrower { 0 }; + int CTFFists { 0 }; + int CTFFireAxe { 0 }; + int CTFCompoundBow { 0 }; + int CTFClub { 0 }; + int CTFBuffItem { 0 }; + int CTFStickBomb { 0 }; + int CTFBottle { 0 }; + int CTFBonesaw { 0 }; + int CTFBall_Ornament { 0 }; + int CTFStunBall { 0 }; + int CTFBat_Giftwrap { 0 }; + int CTFBat_Wood { 0 }; + int CTFBat_Fish { 0 }; + int CTFBat { 0 }; + int CTFBaseRocket { 0 }; + int CTFWeaponBaseMerasmusGrenade { 0 }; + int CTFWeaponBaseMelee { 0 }; + int CTFWeaponBaseGun { 0 }; + int CTFWeaponBaseGrenadeProj { 0 }; + int CTFWeaponBase { 0 }; + int CTFViewModel { 0 }; + int CRobotDispenser { 0 }; + int CTFRobotDestruction_Robot { 0 }; + int CTFReviveMarker { 0 }; + int CTFPumpkinBomb { 0 }; + int CTFProjectile_EnergyRing { 0 }; + int CTFBaseProjectile { 0 }; + int CBaseObjectUpgrade { 0 }; + int CMannVsMachineStats { 0 }; + int CTFRobotDestructionLogic { 0 }; + int CTFRobotDestruction_RobotGroup { 0 }; + int CTFRobotDestruction_RobotSpawn { 0 }; + int CTFPlayerDestructionLogic { 0 }; + int CPlayerDestructionDispenser { 0 }; + int CTFMinigameLogic { 0 }; + int CTFHalloweenMinigame_FallingPlatforms { 0 }; + int CTFHalloweenMinigame { 0 }; + int CTFMiniGame { 0 }; + int CTFWearableVM { 0 }; + int CTFWearable { 0 }; + int CTFPowerupBottle { 0 }; + int CTFItem { 0 }; + int CHalloweenSoulPack { 0 }; + int CTFGenericBomb { 0 }; + int CBonusRoundLogic { 0 }; + int CTFGameRulesProxy { 0 }; + int CTFDroppedWeapon { 0 }; + int CTFProjectile_SpellKartBats { 0 }; + int CTFProjectile_SpellKartOrb { 0 }; + int CTFHellZap { 0 }; + int CTFProjectile_SpellLightningOrb { 0 }; + int CTFProjectile_SpellTransposeTeleport { 0 }; + int CTFProjectile_SpellMeteorShower { 0 }; + int CTFProjectile_SpellSpawnBoss { 0 }; + int CTFProjectile_SpellMirv { 0 }; + int CTFProjectile_SpellPumpkin { 0 }; + int CTFProjectile_SpellSpawnHorde { 0 }; + int CTFProjectile_SpellSpawnZombie { 0 }; + int CTFProjectile_SpellBats { 0 }; + int CTFProjectile_SpellFireball { 0 }; + int CTFSpellBook { 0 }; + int CHightower_TeleportVortex { 0 }; + int CTeleportVortex { 0 }; + int CHalloweenGiftPickup { 0 }; + int CBonusDuckPickup { 0 }; + int CHalloweenPickup { 0 }; + int CCaptureFlagReturnIcon { 0 }; + int CCaptureFlag { 0 }; + int CBonusPack { 0 }; + int CHandleTest { 59 }; + int CTeamRoundTimer { 0 }; + int CTeamplayRoundBasedRulesProxy { 0 }; + int CSpriteTrail { 104 }; + int CSpriteOriented { 103 }; + int CSprite { 102 }; + int CPoseController { 77 }; + int CGameRulesProxy { 58 }; + int CInfoLadderDismount { 60 }; + int CFuncLadder { 51 }; + int CEnvDetailController { 35 }; + int CTFWearableItem { 0 }; + int CEconWearable { 0 }; + int CBaseAttributableItem { 0 }; + int CEconEntity { 0 }; + int CBeam { 20 }; + int CBaseViewModel { 19 }; + int CBaseProjectile { 15 }; + int CBaseParticleEntity { 13 }; + int CBaseGrenade { 11 }; + int CBaseCombatWeapon { 7 }; + int CVoteController { 157 }; + int CTEHL2MPFireBullets { 0 }; + int CHL2MPRagdoll { 0 }; + int CHL2MP_Player { 0 }; + int CWeaponCitizenSuitcase { 0 }; + int CWeaponCitizenPackage { 0 }; + int CWeaponAlyxGun { 0 }; + int CWeaponCubemap { 0 }; + int CWeaponGaussGun { 0 }; + int CWeaponAnnabelle { 0 }; + int CFlaregun { 0 }; + int CWeaponBugBait { 0 }; + int CWeaponBinoculars { 0 }; + int CWeaponCycler { 163 }; + int CCrossbowBolt { 0 }; + int CPropVehiclePrisonerPod { 0 }; + int CPropCrane { 0 }; + int CPropCannon { 0 }; + int CPropAirboat { 0 }; + int CFlare { 0 }; + int CTEConcussiveExplosion { 0 }; + int CNPC_Strider { 0 }; + int CScriptIntro { 0 }; + int CRotorWashEmitter { 0 }; + int CPropCombineBall { 0 }; + int CPlasmaBeamNode { 0 }; + int CNPC_RollerMine { 0 }; + int CNPC_Manhack { 0 }; + int CNPC_CombineGunship { 0 }; + int CNPC_AntlionGuard { 0 }; + int CInfoTeleporterCountdown { 0 }; + int CMortarShell { 0 }; + int CEnvStarfield { 0 }; + int CEnvHeadcrabCanister { 0 }; + int CAlyxEmpEffect { 0 }; + int CCorpse { 0 }; + int CCitadelEnergyCore { 0 }; + int CHL2_Player { 0 }; + int CBaseHLBludgeonWeapon { 0 }; + int CHLSelectFireMachineGun { 0 }; + int CHLMachineGun { 0 }; + int CBaseHelicopter { 0 }; + int CNPC_Barney { 0 }; + int CNPC_Barnacle { 0 }; + int AR2Explosion { 0 }; + int CTEAntlionDust { 0 }; + int CVortigauntEffectDispel { 0 }; + int CVortigauntChargeToken { 0 }; + int CNPC_Vortigaunt { 0 }; + int CPredictedViewModel { 79 }; + int CWeaponStunStick { 0 }; + int CWeaponSMG1 { 0 }; + int CWeapon_SLAM { 0 }; + int CWeaponShotgun { 173 }; + int CWeaponRPG { 0 }; + int CWeaponPistol { 0 }; + int CWeaponPhysCannon { 0 }; + int CHL2MPMachineGun { 0 }; + int CBaseHL2MPCombatWeapon { 0 }; + int CBaseHL2MPBludgeonWeapon { 0 }; + int CWeaponHL2MPBase { 0 }; + int CWeaponFrag { 0 }; + int CWeaponCrowbar { 162 }; + int CWeaponCrossbow { 0 }; + int CWeaponAR2 { 0 }; + int CWeapon357 { 0 }; + int CHL2MPGameRulesProxy { 0 }; + int CHalfLife2Proxy { 0 }; + int CBaseHLCombatWeapon { 0 }; + int CTFVehicle { 0 }; + int CTFBaseDMPowerup { 0 }; + int CWeaponSpawner { 0 }; + int CTFUmbrella { 0 }; + int CTFTranq { 0 }; + int CTFSMG_Primary { 0 }; + int CTFRevolver_Secondary { 0 }; + int CTFNailgun { 0 }; + int CTFHunterRifle { 0 }; + int CTFHeavyArtillery { 0 }; + int CTFHammerfists { 0 }; + int CTFCrowbar { 0 }; + int CTFChainsaw { 0 }; + int CTEPlantBomb { 0 }; + int CTERadioIcon { 0 }; + int CPlantedC4 { 0 }; + int CCSTeam { 0 }; + int CCSPlayerResource { 0 }; + int CCSPlayer { 0 }; + int CCSRagdoll { 0 }; + int CHostage { 0 }; + int CWeaponXM1014 { 0 }; + int CWeaponUSP { 0 }; + int CWeaponUMP45 { 0 }; + int CWeaponTMP { 0 }; + int CSmokeGrenade { 0 }; + int CWeaponSG552 { 0 }; + int CWeaponSG550 { 0 }; + int CWeaponScout { 0 }; + int CWeaponP90 { 0 }; + int CWeaponP228 { 0 }; + int CWeaponMP5Navy { 0 }; + int CWeaponMAC10 { 168 }; + int CWeaponM4A1 { 0 }; + int CWeaponM3 { 0 }; + int CWeaponM249 { 0 }; + int CKnife { 0 }; + int CHEGrenade { 0 }; + int CWeaponGlock { 0 }; + int CWeaponGalil { 0 }; + int CWeaponG3SG1 { 0 }; + int CFlashbang { 0 }; + int CWeaponFiveSeven { 0 }; + int CWeaponFamas { 0 }; + int CWeaponElite { 0 }; + int CDEagle { 0 }; + int CWeaponCSBaseGun { 0 }; + int CWeaponCSBase { 0 }; + int CC4 { 0 }; + int CBaseCSGrenade { 0 }; + int CWeaponAWP { 0 }; + int CWeaponAug { 0 }; + int CAK47 { 0 }; + int CFootstepControl { 0 }; + int CCSGameRulesProxy { 0 }; + int CBaseCSGrenadeProjectile { 0 }; + int CSDKTeam_Deathmatch { 94 }; + int CSDKTeam_Red { 95 }; + int CSDKTeam_Blue { 93 }; + int CSDKTeam_Unassigned { 96 }; + int CSDKTeam { 92 }; + int CSDKPlayerResource { 90 }; + int CSDKRagdoll { 91 }; + int CSDKPlayer { 89 }; + int CSparkler { 100 }; + int CRatRaceWaypoint { 85 }; + int CBriefcaseCaptureZone { 25 }; + int CBriefcase { 24 }; + int CWeaponSDKBase { 171 }; + int CWeaponMP5K { 170 }; + int CWeaponMossberg { 169 }; + int CWeaponM1911 { 167 }; + int CWeaponM16 { 166 }; + int CWeaponGrenade { 165 }; + int CWeaponFAL { 164 }; + int CWeaponBrawl { 161 }; + int CWeaponBeretta { 160 }; + int CBaseSDKGrenade { 17 }; + int CAkimboM1911 { 3 }; + int CAkimboBeretta { 2 }; + int CAkimboBase { 1 }; + int CWeaponSDKMelee { 172 }; + int CSDKGameRulesProxy { 88 }; + int CBaseGrenadeProjectile { 12 }; + int CDAViewModel { 28 }; + + }; + + extern dab dab_list; +} + +#endif /* dab_AUTOGEN_HPP */ \ No newline at end of file diff --git a/src/classinfo/dab_constexpr.gen.hpp b/src/classinfo/dab_constexpr.gen.hpp new file mode 100644 index 00000000..ad9a65fb --- /dev/null +++ b/src/classinfo/dab_constexpr.gen.hpp @@ -0,0 +1,525 @@ +/* + AUTO-GENERATED HEADER - DO NOT MODIFY + CONSTEXPR HEADER FOR dab +*/ + +#ifndef dab_CONSTEXPR_AUTOGEN_HPP +#define dab_CONSTEXPR_AUTOGEN_HPP + +namespace client_classes_constexpr { + + class dab { + public: + static constexpr int CTETFParticleEffect = 0; + static constexpr int CTETFExplosion = 0; + static constexpr int CTETFBlood = 0; + static constexpr int CTFTankBoss = 0; + static constexpr int CTFBaseBoss = 0; + static constexpr int CBossAlpha = 0; + static constexpr int CZombie = 0; + static constexpr int CMerasmusDancer = 0; + static constexpr int CMerasmus = 0; + static constexpr int CHeadlessHatman = 0; + static constexpr int CEyeballBoss = 0; + static constexpr int CTFWeaponSapper = 0; + static constexpr int CTFWeaponBuilder = 0; + static constexpr int C_TFWeaponBuilder = 0; + static constexpr int CTFTeam = 0; + static constexpr int CTFTauntProp = 0; + static constexpr int CTFProjectile_Rocket = 0; + static constexpr int CTFProjectile_Flare = 0; + static constexpr int CTFProjectile_EnergyBall = 0; + static constexpr int CTFProjectile_GrapplingHook = 0; + static constexpr int CTFProjectile_HealingBolt = 0; + static constexpr int CTFProjectile_Arrow = 0; + static constexpr int CTFPlayerResource = 0; + static constexpr int CTFPlayer = 0; + static constexpr int CTFRagdoll = 0; + static constexpr int CTEPlayerAnimEvent = 143; + static constexpr int CTFPasstimeLogic = 0; + static constexpr int CPasstimeBall = 0; + static constexpr int CTFObjectiveResource = 0; + static constexpr int CTFGlow = 0; + static constexpr int CTEFireBullets = 131; + static constexpr int CTFBuffBanner = 0; + static constexpr int CTFAmmoPack = 0; + static constexpr int CObjectTeleporter = 0; + static constexpr int CObjectSentrygun = 0; + static constexpr int CTFProjectile_SentryRocket = 0; + static constexpr int CObjectSapper = 0; + static constexpr int CObjectCartDispenser = 0; + static constexpr int CObjectDispenser = 0; + static constexpr int CMonsterResource = 0; + static constexpr int CFuncRespawnRoomVisualizer = 0; + static constexpr int CFuncRespawnRoom = 0; + static constexpr int CFuncPasstimeGoal = 0; + static constexpr int CFuncForceField = 0; + static constexpr int CCaptureZone = 0; + static constexpr int CCurrencyPack = 0; + static constexpr int CBaseObject = 0; + static constexpr int CTFBotHintEngineerNest = 0; + static constexpr int CBotNPCMinion = 0; + static constexpr int CBotNPC = 0; + static constexpr int CRagdollPropAttached = 84; + static constexpr int CRagdollProp = 83; + static constexpr int NextBotCombatCharacter = 0; + static constexpr int CWaterBullet = 158; + static constexpr int CFuncMonitor = 52; + static constexpr int CWorld = 174; + static constexpr int CWaterLODControl = 159; + static constexpr int CVGuiScreen = 156; + static constexpr int CPropJeep = 80; + static constexpr int CPropVehicleChoreoGeneric = 0; + static constexpr int CTEWorldDecal = 155; + static constexpr int CTESpriteSpray = 152; + static constexpr int CTESprite = 151; + static constexpr int CTESparks = 150; + static constexpr int CTESmoke = 149; + static constexpr int CTEShowLine = 147; + static constexpr int CTEProjectedDecal = 145; + static constexpr int CTEPlayerDecal = 144; + static constexpr int CTEPhysicsProp = 142; + static constexpr int CTEParticleSystem = 141; + static constexpr int CTEMuzzleFlash = 140; + static constexpr int CTELargeFunnel = 138; + static constexpr int CTEKillPlayerAttachments = 137; + static constexpr int CTEImpact = 136; + static constexpr int CTEGlowSprite = 135; + static constexpr int CTEShatterSurface = 146; + static constexpr int CTEFootprintDecal = 133; + static constexpr int CTEFizz = 132; + static constexpr int CTEExplosion = 130; + static constexpr int CTEEnergySplash = 129; + static constexpr int CTEEffectDispatch = 128; + static constexpr int CTEDynamicLight = 127; + static constexpr int CTEDecal = 125; + static constexpr int CTEClientProjectile = 124; + static constexpr int CTEBubbleTrail = 123; + static constexpr int CTEBubbles = 122; + static constexpr int CTEBSPDecal = 121; + static constexpr int CTEBreakModel = 120; + static constexpr int CTEBloodStream = 119; + static constexpr int CTEBloodSprite = 118; + static constexpr int CTEBeamSpline = 117; + static constexpr int CTEBeamRingPoint = 116; + static constexpr int CTEBeamRing = 115; + static constexpr int CTEBeamPoints = 114; + static constexpr int CTEBeamLaser = 113; + static constexpr int CTEBeamFollow = 112; + static constexpr int CTEBeamEnts = 111; + static constexpr int CTEBeamEntPoint = 110; + static constexpr int CTEBaseBeam = 109; + static constexpr int CTEArmorRicochet = 108; + static constexpr int CTEMetalSparks = 139; + static constexpr int CTest_ProxyToggle_Networkable = 153; + static constexpr int CTestTraceline = 154; + static constexpr int CTesla = 148; + static constexpr int CTeamTrainWatcher = 0; + static constexpr int CBaseTeamObjectiveResource = 0; + static constexpr int CTeam = 107; + static constexpr int CSun = 106; + static constexpr int CSteamJet = 105; + static constexpr int CParticlePerformanceMonitor = 66; + static constexpr int CSpotlightEnd = 101; + static constexpr int DustTrail = 175; + static constexpr int CFireTrail = 44; + static constexpr int SporeTrail = 181; + static constexpr int SporeExplosion = 180; + static constexpr int RocketTrail = 178; + static constexpr int SmokeTrail = 179; + static constexpr int CSmokeStack = 99; + static constexpr int CSlideshowDisplay = 98; + static constexpr int CShadowControl = 97; + static constexpr int CSceneEntity = 87; + static constexpr int CRopeKeyframe = 86; + static constexpr int CRagdollManager = 82; + static constexpr int CPropVehicleDriveable = 81; + static constexpr int CPhysicsPropMultiplayer = 71; + static constexpr int CPhysBoxMultiplayer = 69; + static constexpr int CBasePropDoor = 16; + static constexpr int CDynamicProp = 30; + static constexpr int CPointCommentaryNode = 76; + static constexpr int CPointCamera = 75; + static constexpr int CPlayerResource = 74; + static constexpr int CPlasma = 73; + static constexpr int CPhysMagnet = 72; + static constexpr int CPhysicsProp = 70; + static constexpr int CPhysBox = 68; + static constexpr int CParticleSystem = 67; + static constexpr int ParticleSmokeGrenade = 177; + static constexpr int CParticleFire = 65; + static constexpr int MovieExplosion = 176; + static constexpr int CMaterialModifyControl = 64; + static constexpr int CLightGlow = 63; + static constexpr int CInfoOverlayAccessor = 62; + static constexpr int CTEGaussExplosion = 134; + static constexpr int CFuncTrackTrain = 57; + static constexpr int CFuncSmokeVolume = 56; + static constexpr int CFuncRotating = 55; + static constexpr int CFuncReflectiveGlass = 54; + static constexpr int CFuncOccluder = 53; + static constexpr int CFunc_LOD = 48; + static constexpr int CTEDust = 126; + static constexpr int CFunc_Dust = 47; + static constexpr int CFuncConveyor = 50; + static constexpr int CBreakableSurface = 23; + static constexpr int CFuncAreaPortalWindow = 49; + static constexpr int CFish = 45; + static constexpr int CEntityFlame = 33; + static constexpr int CFireSmoke = 43; + static constexpr int CEnvTonemapController = 41; + static constexpr int CEnvScreenEffect = 39; + static constexpr int CEnvScreenOverlay = 40; + static constexpr int CEnvProjectedTexture = 37; + static constexpr int CEnvParticleScript = 36; + static constexpr int CFogController = 46; + static constexpr int CEntityParticleTrail = 34; + static constexpr int CEntityDissolve = 32; + static constexpr int CEnvQuadraticBeam = 38; + static constexpr int CEmbers = 31; + static constexpr int CEnvWind = 42; + static constexpr int CPrecipitation = 78; + static constexpr int CDynamicLight = 29; + static constexpr int CColorCorrectionVolume = 27; + static constexpr int CColorCorrection = 26; + static constexpr int CBreakableProp = 22; + static constexpr int CBaseTempEntity = 18; + static constexpr int CBasePlayer = 14; + static constexpr int CBaseFlex = 10; + static constexpr int CBaseEntity = 9; + static constexpr int CBaseDoor = 8; + static constexpr int CBaseCombatCharacter = 6; + static constexpr int CBaseAnimatingOverlay = 5; + static constexpr int CBoneFollower = 21; + static constexpr int CBaseAnimating = 4; + static constexpr int CInfoLightingRelative = 61; + static constexpr int CAI_BaseNPC = 0; + static constexpr int CWeaponIFMSteadyCam = 0; + static constexpr int CWeaponIFMBaseCamera = 0; + static constexpr int CWeaponIFMBase = 0; + static constexpr int CTFWearableLevelableItem = 0; + static constexpr int CTFWearableDemoShield = 0; + static constexpr int CTFWearableRobotArm = 0; + static constexpr int CTFRobotArm = 0; + static constexpr int CTFWrench = 0; + static constexpr int CTFProjectile_ThrowableBreadMonster = 0; + static constexpr int CTFProjectile_ThrowableBrick = 0; + static constexpr int CTFProjectile_ThrowableRepel = 0; + static constexpr int CTFProjectile_Throwable = 0; + static constexpr int CTFThrowable = 0; + static constexpr int CTFSyringeGun = 0; + static constexpr int CTFKatana = 0; + static constexpr int CTFSword = 0; + static constexpr int CSniperDot = 0; + static constexpr int CTFSniperRifleClassic = 0; + static constexpr int CTFSniperRifleDecap = 0; + static constexpr int CTFSniperRifle = 0; + static constexpr int CTFChargedSMG = 0; + static constexpr int CTFSMG = 0; + static constexpr int CTFShovel = 0; + static constexpr int CTFShotgunBuildingRescue = 0; + static constexpr int CTFPEPBrawlerBlaster = 0; + static constexpr int CTFSodaPopper = 0; + static constexpr int CTFShotgun_Revenge = 0; + static constexpr int CTFScatterGun = 0; + static constexpr int CTFShotgun_Pyro = 0; + static constexpr int CTFShotgun_HWG = 0; + static constexpr int CTFShotgun_Soldier = 0; + static constexpr int CTFShotgun = 0; + static constexpr int CTFCrossbow = 0; + static constexpr int CTFRocketLauncher_Mortar = 0; + static constexpr int CTFRocketLauncher_AirStrike = 0; + static constexpr int CTFRocketLauncher_DirectHit = 0; + static constexpr int CTFRocketLauncher = 0; + static constexpr int CTFRevolver = 0; + static constexpr int CTFDRGPomson = 0; + static constexpr int CTFRaygun = 0; + static constexpr int CTFPistol_ScoutSecondary = 0; + static constexpr int CTFPistol_ScoutPrimary = 0; + static constexpr int CTFPistol_Scout = 0; + static constexpr int CTFPistol = 0; + static constexpr int CTFPipebombLauncher = 0; + static constexpr int CTFWeaponPDA_Spy = 0; + static constexpr int CTFWeaponPDA_Engineer_Destroy = 0; + static constexpr int CTFWeaponPDA_Engineer_Build = 0; + static constexpr int CTFWeaponPDAExpansion_Teleporter = 0; + static constexpr int CTFWeaponPDAExpansion_Dispenser = 0; + static constexpr int CTFWeaponPDA = 0; + static constexpr int CPasstimeGun = 0; + static constexpr int CTFParticleCannon = 0; + static constexpr int CTFParachute_Secondary = 0; + static constexpr int CTFParachute_Primary = 0; + static constexpr int CTFParachute = 0; + static constexpr int CTFMinigun = 0; + static constexpr int CTFMedigunShield = 0; + static constexpr int CWeaponMedigun = 0; + static constexpr int CTFMechanicalArm = 0; + static constexpr int CTFLunchBox_Drink = 0; + static constexpr int CTFLunchBox = 0; + static constexpr int CLaserDot = 0; + static constexpr int CTFLaserPointer = 0; + static constexpr int CTFKnife = 0; + static constexpr int CTFProjectile_Cleaver = 0; + static constexpr int CTFProjectile_JarMilk = 0; + static constexpr int CTFProjectile_Jar = 0; + static constexpr int CTFCleaver = 0; + static constexpr int CTFJarMilk = 0; + static constexpr int CTFJar = 0; + static constexpr int CTFWeaponInvis = 0; + static constexpr int CTFGrenadePipebombProjectile = 0; + static constexpr int CTFCannon = 0; + static constexpr int CTFGrenadeLauncher = 0; + static constexpr int CTFGrapplingHook = 0; + static constexpr int CTFFlareGun_Revenge = 0; + static constexpr int CTFFlareGun = 0; + static constexpr int CTFFlameRocket = 0; + static constexpr int CTFFlameThrower = 0; + static constexpr int CTFFists = 0; + static constexpr int CTFFireAxe = 0; + static constexpr int CTFCompoundBow = 0; + static constexpr int CTFClub = 0; + static constexpr int CTFBuffItem = 0; + static constexpr int CTFStickBomb = 0; + static constexpr int CTFBottle = 0; + static constexpr int CTFBonesaw = 0; + static constexpr int CTFBall_Ornament = 0; + static constexpr int CTFStunBall = 0; + static constexpr int CTFBat_Giftwrap = 0; + static constexpr int CTFBat_Wood = 0; + static constexpr int CTFBat_Fish = 0; + static constexpr int CTFBat = 0; + static constexpr int CTFBaseRocket = 0; + static constexpr int CTFWeaponBaseMerasmusGrenade = 0; + static constexpr int CTFWeaponBaseMelee = 0; + static constexpr int CTFWeaponBaseGun = 0; + static constexpr int CTFWeaponBaseGrenadeProj = 0; + static constexpr int CTFWeaponBase = 0; + static constexpr int CTFViewModel = 0; + static constexpr int CRobotDispenser = 0; + static constexpr int CTFRobotDestruction_Robot = 0; + static constexpr int CTFReviveMarker = 0; + static constexpr int CTFPumpkinBomb = 0; + static constexpr int CTFProjectile_EnergyRing = 0; + static constexpr int CTFBaseProjectile = 0; + static constexpr int CBaseObjectUpgrade = 0; + static constexpr int CMannVsMachineStats = 0; + static constexpr int CTFRobotDestructionLogic = 0; + static constexpr int CTFRobotDestruction_RobotGroup = 0; + static constexpr int CTFRobotDestruction_RobotSpawn = 0; + static constexpr int CTFPlayerDestructionLogic = 0; + static constexpr int CPlayerDestructionDispenser = 0; + static constexpr int CTFMinigameLogic = 0; + static constexpr int CTFHalloweenMinigame_FallingPlatforms = 0; + static constexpr int CTFHalloweenMinigame = 0; + static constexpr int CTFMiniGame = 0; + static constexpr int CTFWearableVM = 0; + static constexpr int CTFWearable = 0; + static constexpr int CTFPowerupBottle = 0; + static constexpr int CTFItem = 0; + static constexpr int CHalloweenSoulPack = 0; + static constexpr int CTFGenericBomb = 0; + static constexpr int CBonusRoundLogic = 0; + static constexpr int CTFGameRulesProxy = 0; + static constexpr int CTFDroppedWeapon = 0; + static constexpr int CTFProjectile_SpellKartBats = 0; + static constexpr int CTFProjectile_SpellKartOrb = 0; + static constexpr int CTFHellZap = 0; + static constexpr int CTFProjectile_SpellLightningOrb = 0; + static constexpr int CTFProjectile_SpellTransposeTeleport = 0; + static constexpr int CTFProjectile_SpellMeteorShower = 0; + static constexpr int CTFProjectile_SpellSpawnBoss = 0; + static constexpr int CTFProjectile_SpellMirv = 0; + static constexpr int CTFProjectile_SpellPumpkin = 0; + static constexpr int CTFProjectile_SpellSpawnHorde = 0; + static constexpr int CTFProjectile_SpellSpawnZombie = 0; + static constexpr int CTFProjectile_SpellBats = 0; + static constexpr int CTFProjectile_SpellFireball = 0; + static constexpr int CTFSpellBook = 0; + static constexpr int CHightower_TeleportVortex = 0; + static constexpr int CTeleportVortex = 0; + static constexpr int CHalloweenGiftPickup = 0; + static constexpr int CBonusDuckPickup = 0; + static constexpr int CHalloweenPickup = 0; + static constexpr int CCaptureFlagReturnIcon = 0; + static constexpr int CCaptureFlag = 0; + static constexpr int CBonusPack = 0; + static constexpr int CHandleTest = 59; + static constexpr int CTeamRoundTimer = 0; + static constexpr int CTeamplayRoundBasedRulesProxy = 0; + static constexpr int CSpriteTrail = 104; + static constexpr int CSpriteOriented = 103; + static constexpr int CSprite = 102; + static constexpr int CPoseController = 77; + static constexpr int CGameRulesProxy = 58; + static constexpr int CInfoLadderDismount = 60; + static constexpr int CFuncLadder = 51; + static constexpr int CEnvDetailController = 35; + static constexpr int CTFWearableItem = 0; + static constexpr int CEconWearable = 0; + static constexpr int CBaseAttributableItem = 0; + static constexpr int CEconEntity = 0; + static constexpr int CBeam = 20; + static constexpr int CBaseViewModel = 19; + static constexpr int CBaseProjectile = 15; + static constexpr int CBaseParticleEntity = 13; + static constexpr int CBaseGrenade = 11; + static constexpr int CBaseCombatWeapon = 7; + static constexpr int CVoteController = 157; + static constexpr int CTEHL2MPFireBullets = 0; + static constexpr int CHL2MPRagdoll = 0; + static constexpr int CHL2MP_Player = 0; + static constexpr int CWeaponCitizenSuitcase = 0; + static constexpr int CWeaponCitizenPackage = 0; + static constexpr int CWeaponAlyxGun = 0; + static constexpr int CWeaponCubemap = 0; + static constexpr int CWeaponGaussGun = 0; + static constexpr int CWeaponAnnabelle = 0; + static constexpr int CFlaregun = 0; + static constexpr int CWeaponBugBait = 0; + static constexpr int CWeaponBinoculars = 0; + static constexpr int CWeaponCycler = 163; + static constexpr int CCrossbowBolt = 0; + static constexpr int CPropVehiclePrisonerPod = 0; + static constexpr int CPropCrane = 0; + static constexpr int CPropCannon = 0; + static constexpr int CPropAirboat = 0; + static constexpr int CFlare = 0; + static constexpr int CTEConcussiveExplosion = 0; + static constexpr int CNPC_Strider = 0; + static constexpr int CScriptIntro = 0; + static constexpr int CRotorWashEmitter = 0; + static constexpr int CPropCombineBall = 0; + static constexpr int CPlasmaBeamNode = 0; + static constexpr int CNPC_RollerMine = 0; + static constexpr int CNPC_Manhack = 0; + static constexpr int CNPC_CombineGunship = 0; + static constexpr int CNPC_AntlionGuard = 0; + static constexpr int CInfoTeleporterCountdown = 0; + static constexpr int CMortarShell = 0; + static constexpr int CEnvStarfield = 0; + static constexpr int CEnvHeadcrabCanister = 0; + static constexpr int CAlyxEmpEffect = 0; + static constexpr int CCorpse = 0; + static constexpr int CCitadelEnergyCore = 0; + static constexpr int CHL2_Player = 0; + static constexpr int CBaseHLBludgeonWeapon = 0; + static constexpr int CHLSelectFireMachineGun = 0; + static constexpr int CHLMachineGun = 0; + static constexpr int CBaseHelicopter = 0; + static constexpr int CNPC_Barney = 0; + static constexpr int CNPC_Barnacle = 0; + static constexpr int AR2Explosion = 0; + static constexpr int CTEAntlionDust = 0; + static constexpr int CVortigauntEffectDispel = 0; + static constexpr int CVortigauntChargeToken = 0; + static constexpr int CNPC_Vortigaunt = 0; + static constexpr int CPredictedViewModel = 79; + static constexpr int CWeaponStunStick = 0; + static constexpr int CWeaponSMG1 = 0; + static constexpr int CWeapon_SLAM = 0; + static constexpr int CWeaponShotgun = 173; + static constexpr int CWeaponRPG = 0; + static constexpr int CWeaponPistol = 0; + static constexpr int CWeaponPhysCannon = 0; + static constexpr int CHL2MPMachineGun = 0; + static constexpr int CBaseHL2MPCombatWeapon = 0; + static constexpr int CBaseHL2MPBludgeonWeapon = 0; + static constexpr int CWeaponHL2MPBase = 0; + static constexpr int CWeaponFrag = 0; + static constexpr int CWeaponCrowbar = 162; + static constexpr int CWeaponCrossbow = 0; + static constexpr int CWeaponAR2 = 0; + static constexpr int CWeapon357 = 0; + static constexpr int CHL2MPGameRulesProxy = 0; + static constexpr int CHalfLife2Proxy = 0; + static constexpr int CBaseHLCombatWeapon = 0; + static constexpr int CTFVehicle = 0; + static constexpr int CTFBaseDMPowerup = 0; + static constexpr int CWeaponSpawner = 0; + static constexpr int CTFUmbrella = 0; + static constexpr int CTFTranq = 0; + static constexpr int CTFSMG_Primary = 0; + static constexpr int CTFRevolver_Secondary = 0; + static constexpr int CTFNailgun = 0; + static constexpr int CTFHunterRifle = 0; + static constexpr int CTFHeavyArtillery = 0; + static constexpr int CTFHammerfists = 0; + static constexpr int CTFCrowbar = 0; + static constexpr int CTFChainsaw = 0; + static constexpr int CTEPlantBomb = 0; + static constexpr int CTERadioIcon = 0; + static constexpr int CPlantedC4 = 0; + static constexpr int CCSTeam = 0; + static constexpr int CCSPlayerResource = 0; + static constexpr int CCSPlayer = 0; + static constexpr int CCSRagdoll = 0; + static constexpr int CHostage = 0; + static constexpr int CWeaponXM1014 = 0; + static constexpr int CWeaponUSP = 0; + static constexpr int CWeaponUMP45 = 0; + static constexpr int CWeaponTMP = 0; + static constexpr int CSmokeGrenade = 0; + static constexpr int CWeaponSG552 = 0; + static constexpr int CWeaponSG550 = 0; + static constexpr int CWeaponScout = 0; + static constexpr int CWeaponP90 = 0; + static constexpr int CWeaponP228 = 0; + static constexpr int CWeaponMP5Navy = 0; + static constexpr int CWeaponMAC10 = 168; + static constexpr int CWeaponM4A1 = 0; + static constexpr int CWeaponM3 = 0; + static constexpr int CWeaponM249 = 0; + static constexpr int CKnife = 0; + static constexpr int CHEGrenade = 0; + static constexpr int CWeaponGlock = 0; + static constexpr int CWeaponGalil = 0; + static constexpr int CWeaponG3SG1 = 0; + static constexpr int CFlashbang = 0; + static constexpr int CWeaponFiveSeven = 0; + static constexpr int CWeaponFamas = 0; + static constexpr int CWeaponElite = 0; + static constexpr int CDEagle = 0; + static constexpr int CWeaponCSBaseGun = 0; + static constexpr int CWeaponCSBase = 0; + static constexpr int CC4 = 0; + static constexpr int CBaseCSGrenade = 0; + static constexpr int CWeaponAWP = 0; + static constexpr int CWeaponAug = 0; + static constexpr int CAK47 = 0; + static constexpr int CFootstepControl = 0; + static constexpr int CCSGameRulesProxy = 0; + static constexpr int CBaseCSGrenadeProjectile = 0; + static constexpr int CSDKTeam_Deathmatch = 94; + static constexpr int CSDKTeam_Red = 95; + static constexpr int CSDKTeam_Blue = 93; + static constexpr int CSDKTeam_Unassigned = 96; + static constexpr int CSDKTeam = 92; + static constexpr int CSDKPlayerResource = 90; + static constexpr int CSDKRagdoll = 91; + static constexpr int CSDKPlayer = 89; + static constexpr int CSparkler = 100; + static constexpr int CRatRaceWaypoint = 85; + static constexpr int CBriefcaseCaptureZone = 25; + static constexpr int CBriefcase = 24; + static constexpr int CWeaponSDKBase = 171; + static constexpr int CWeaponMP5K = 170; + static constexpr int CWeaponMossberg = 169; + static constexpr int CWeaponM1911 = 167; + static constexpr int CWeaponM16 = 166; + static constexpr int CWeaponGrenade = 165; + static constexpr int CWeaponFAL = 164; + static constexpr int CWeaponBrawl = 161; + static constexpr int CWeaponBeretta = 160; + static constexpr int CBaseSDKGrenade = 17; + static constexpr int CAkimboM1911 = 3; + static constexpr int CAkimboBeretta = 2; + static constexpr int CAkimboBase = 1; + static constexpr int CWeaponSDKMelee = 172; + static constexpr int CSDKGameRulesProxy = 88; + static constexpr int CBaseGrenadeProjectile = 12; + static constexpr int CDAViewModel = 28; + + }; +} + +#endif /* dab_CONSTEXPR_AUTOGEN_HPP */ \ No newline at end of file diff --git a/src/classinfo/dummy.gen.hpp b/src/classinfo/dummy.gen.hpp index abb60aa5..2754418e 100644 --- a/src/classinfo/dummy.gen.hpp +++ b/src/classinfo/dummy.gen.hpp @@ -489,6 +489,35 @@ namespace client_classes { int CFootstepControl { 0 }; int CCSGameRulesProxy { 0 }; int CBaseCSGrenadeProjectile { 0 }; + int CSDKTeam_Deathmatch { 0 }; + int CSDKTeam_Red { 0 }; + int CSDKTeam_Blue { 0 }; + int CSDKTeam_Unassigned { 0 }; + int CSDKTeam { 0 }; + int CSDKPlayerResource { 0 }; + int CSDKRagdoll { 0 }; + int CSDKPlayer { 0 }; + int CSparkler { 0 }; + int CRatRaceWaypoint { 0 }; + int CBriefcaseCaptureZone { 0 }; + int CBriefcase { 0 }; + int CWeaponSDKBase { 0 }; + int CWeaponMP5K { 0 }; + int CWeaponMossberg { 0 }; + int CWeaponM1911 { 0 }; + int CWeaponM16 { 0 }; + int CWeaponGrenade { 0 }; + int CWeaponFAL { 0 }; + int CWeaponBrawl { 0 }; + int CWeaponBeretta { 0 }; + int CBaseSDKGrenade { 0 }; + int CAkimboM1911 { 0 }; + int CAkimboBeretta { 0 }; + int CAkimboBase { 0 }; + int CWeaponSDKMelee { 0 }; + int CSDKGameRulesProxy { 0 }; + int CBaseGrenadeProjectile { 0 }; + int CDAViewModel { 0 }; }; diff --git a/src/classinfo/dump.cpp b/src/classinfo/dump.cpp index 1c5cc957..89275607 100644 --- a/src/classinfo/dump.cpp +++ b/src/classinfo/dump.cpp @@ -21,3 +21,7 @@ void PerformClassDump() { fclose(cd); } } + +static CatCommand populate_dynamic("debug_populate_dynamic", "Populate dynamic class table", []() { + client_classes::dynamic_list.Populate(); +}); diff --git a/src/classinfo/dynamic.gen.cpp b/src/classinfo/dynamic.gen.cpp new file mode 100644 index 00000000..7efa3365 --- /dev/null +++ b/src/classinfo/dynamic.gen.cpp @@ -0,0 +1,534 @@ + + +#include "dynamic.gen.hpp" +#include "../common.h" + +namespace client_classes { + +std::unordered_map classid_mapping {}; + +dynamic::dynamic() { + classid_mapping["CTETFParticleEffect"] = &CTETFParticleEffect; + classid_mapping["CTETFExplosion"] = &CTETFExplosion; + classid_mapping["CTETFBlood"] = &CTETFBlood; + classid_mapping["CTFTankBoss"] = &CTFTankBoss; + classid_mapping["CTFBaseBoss"] = &CTFBaseBoss; + classid_mapping["CBossAlpha"] = &CBossAlpha; + classid_mapping["CZombie"] = &CZombie; + classid_mapping["CMerasmusDancer"] = &CMerasmusDancer; + classid_mapping["CMerasmus"] = &CMerasmus; + classid_mapping["CHeadlessHatman"] = &CHeadlessHatman; + classid_mapping["CEyeballBoss"] = &CEyeballBoss; + classid_mapping["CTFWeaponSapper"] = &CTFWeaponSapper; + classid_mapping["CTFWeaponBuilder"] = &CTFWeaponBuilder; + classid_mapping["C_TFWeaponBuilder"] = &C_TFWeaponBuilder; + classid_mapping["CTFTeam"] = &CTFTeam; + classid_mapping["CTFTauntProp"] = &CTFTauntProp; + classid_mapping["CTFProjectile_Rocket"] = &CTFProjectile_Rocket; + classid_mapping["CTFProjectile_Flare"] = &CTFProjectile_Flare; + classid_mapping["CTFProjectile_EnergyBall"] = &CTFProjectile_EnergyBall; + classid_mapping["CTFProjectile_GrapplingHook"] = &CTFProjectile_GrapplingHook; + classid_mapping["CTFProjectile_HealingBolt"] = &CTFProjectile_HealingBolt; + classid_mapping["CTFProjectile_Arrow"] = &CTFProjectile_Arrow; + classid_mapping["CTFPlayerResource"] = &CTFPlayerResource; + classid_mapping["CTFPlayer"] = &CTFPlayer; + classid_mapping["CTFRagdoll"] = &CTFRagdoll; + classid_mapping["CTEPlayerAnimEvent"] = &CTEPlayerAnimEvent; + classid_mapping["CTFPasstimeLogic"] = &CTFPasstimeLogic; + classid_mapping["CPasstimeBall"] = &CPasstimeBall; + classid_mapping["CTFObjectiveResource"] = &CTFObjectiveResource; + classid_mapping["CTFGlow"] = &CTFGlow; + classid_mapping["CTEFireBullets"] = &CTEFireBullets; + classid_mapping["CTFBuffBanner"] = &CTFBuffBanner; + classid_mapping["CTFAmmoPack"] = &CTFAmmoPack; + classid_mapping["CObjectTeleporter"] = &CObjectTeleporter; + classid_mapping["CObjectSentrygun"] = &CObjectSentrygun; + classid_mapping["CTFProjectile_SentryRocket"] = &CTFProjectile_SentryRocket; + classid_mapping["CObjectSapper"] = &CObjectSapper; + classid_mapping["CObjectCartDispenser"] = &CObjectCartDispenser; + classid_mapping["CObjectDispenser"] = &CObjectDispenser; + classid_mapping["CMonsterResource"] = &CMonsterResource; + classid_mapping["CFuncRespawnRoomVisualizer"] = &CFuncRespawnRoomVisualizer; + classid_mapping["CFuncRespawnRoom"] = &CFuncRespawnRoom; + classid_mapping["CFuncPasstimeGoal"] = &CFuncPasstimeGoal; + classid_mapping["CFuncForceField"] = &CFuncForceField; + classid_mapping["CCaptureZone"] = &CCaptureZone; + classid_mapping["CCurrencyPack"] = &CCurrencyPack; + classid_mapping["CBaseObject"] = &CBaseObject; + classid_mapping["CTFBotHintEngineerNest"] = &CTFBotHintEngineerNest; + classid_mapping["CBotNPCMinion"] = &CBotNPCMinion; + classid_mapping["CBotNPC"] = &CBotNPC; + classid_mapping["CRagdollPropAttached"] = &CRagdollPropAttached; + classid_mapping["CRagdollProp"] = &CRagdollProp; + classid_mapping["NextBotCombatCharacter"] = &NextBotCombatCharacter; + classid_mapping["CWaterBullet"] = &CWaterBullet; + classid_mapping["CFuncMonitor"] = &CFuncMonitor; + classid_mapping["CWorld"] = &CWorld; + classid_mapping["CWaterLODControl"] = &CWaterLODControl; + classid_mapping["CVGuiScreen"] = &CVGuiScreen; + classid_mapping["CPropJeep"] = &CPropJeep; + classid_mapping["CPropVehicleChoreoGeneric"] = &CPropVehicleChoreoGeneric; + classid_mapping["CTEWorldDecal"] = &CTEWorldDecal; + classid_mapping["CTESpriteSpray"] = &CTESpriteSpray; + classid_mapping["CTESprite"] = &CTESprite; + classid_mapping["CTESparks"] = &CTESparks; + classid_mapping["CTESmoke"] = &CTESmoke; + classid_mapping["CTEShowLine"] = &CTEShowLine; + classid_mapping["CTEProjectedDecal"] = &CTEProjectedDecal; + classid_mapping["CTEPlayerDecal"] = &CTEPlayerDecal; + classid_mapping["CTEPhysicsProp"] = &CTEPhysicsProp; + classid_mapping["CTEParticleSystem"] = &CTEParticleSystem; + classid_mapping["CTEMuzzleFlash"] = &CTEMuzzleFlash; + classid_mapping["CTELargeFunnel"] = &CTELargeFunnel; + classid_mapping["CTEKillPlayerAttachments"] = &CTEKillPlayerAttachments; + classid_mapping["CTEImpact"] = &CTEImpact; + classid_mapping["CTEGlowSprite"] = &CTEGlowSprite; + classid_mapping["CTEShatterSurface"] = &CTEShatterSurface; + classid_mapping["CTEFootprintDecal"] = &CTEFootprintDecal; + classid_mapping["CTEFizz"] = &CTEFizz; + classid_mapping["CTEExplosion"] = &CTEExplosion; + classid_mapping["CTEEnergySplash"] = &CTEEnergySplash; + classid_mapping["CTEEffectDispatch"] = &CTEEffectDispatch; + classid_mapping["CTEDynamicLight"] = &CTEDynamicLight; + classid_mapping["CTEDecal"] = &CTEDecal; + classid_mapping["CTEClientProjectile"] = &CTEClientProjectile; + classid_mapping["CTEBubbleTrail"] = &CTEBubbleTrail; + classid_mapping["CTEBubbles"] = &CTEBubbles; + classid_mapping["CTEBSPDecal"] = &CTEBSPDecal; + classid_mapping["CTEBreakModel"] = &CTEBreakModel; + classid_mapping["CTEBloodStream"] = &CTEBloodStream; + classid_mapping["CTEBloodSprite"] = &CTEBloodSprite; + classid_mapping["CTEBeamSpline"] = &CTEBeamSpline; + classid_mapping["CTEBeamRingPoint"] = &CTEBeamRingPoint; + classid_mapping["CTEBeamRing"] = &CTEBeamRing; + classid_mapping["CTEBeamPoints"] = &CTEBeamPoints; + classid_mapping["CTEBeamLaser"] = &CTEBeamLaser; + classid_mapping["CTEBeamFollow"] = &CTEBeamFollow; + classid_mapping["CTEBeamEnts"] = &CTEBeamEnts; + classid_mapping["CTEBeamEntPoint"] = &CTEBeamEntPoint; + classid_mapping["CTEBaseBeam"] = &CTEBaseBeam; + classid_mapping["CTEArmorRicochet"] = &CTEArmorRicochet; + classid_mapping["CTEMetalSparks"] = &CTEMetalSparks; + classid_mapping["CTest_ProxyToggle_Networkable"] = &CTest_ProxyToggle_Networkable; + classid_mapping["CTestTraceline"] = &CTestTraceline; + classid_mapping["CTesla"] = &CTesla; + classid_mapping["CTeamTrainWatcher"] = &CTeamTrainWatcher; + classid_mapping["CBaseTeamObjectiveResource"] = &CBaseTeamObjectiveResource; + classid_mapping["CTeam"] = &CTeam; + classid_mapping["CSun"] = &CSun; + classid_mapping["CSteamJet"] = &CSteamJet; + classid_mapping["CParticlePerformanceMonitor"] = &CParticlePerformanceMonitor; + classid_mapping["CSpotlightEnd"] = &CSpotlightEnd; + classid_mapping["DustTrail"] = &DustTrail; + classid_mapping["CFireTrail"] = &CFireTrail; + classid_mapping["SporeTrail"] = &SporeTrail; + classid_mapping["SporeExplosion"] = &SporeExplosion; + classid_mapping["RocketTrail"] = &RocketTrail; + classid_mapping["SmokeTrail"] = &SmokeTrail; + classid_mapping["CSmokeStack"] = &CSmokeStack; + classid_mapping["CSlideshowDisplay"] = &CSlideshowDisplay; + classid_mapping["CShadowControl"] = &CShadowControl; + classid_mapping["CSceneEntity"] = &CSceneEntity; + classid_mapping["CRopeKeyframe"] = &CRopeKeyframe; + classid_mapping["CRagdollManager"] = &CRagdollManager; + classid_mapping["CPropVehicleDriveable"] = &CPropVehicleDriveable; + classid_mapping["CPhysicsPropMultiplayer"] = &CPhysicsPropMultiplayer; + classid_mapping["CPhysBoxMultiplayer"] = &CPhysBoxMultiplayer; + classid_mapping["CBasePropDoor"] = &CBasePropDoor; + classid_mapping["CDynamicProp"] = &CDynamicProp; + classid_mapping["CPointCommentaryNode"] = &CPointCommentaryNode; + classid_mapping["CPointCamera"] = &CPointCamera; + classid_mapping["CPlayerResource"] = &CPlayerResource; + classid_mapping["CPlasma"] = &CPlasma; + classid_mapping["CPhysMagnet"] = &CPhysMagnet; + classid_mapping["CPhysicsProp"] = &CPhysicsProp; + classid_mapping["CPhysBox"] = &CPhysBox; + classid_mapping["CParticleSystem"] = &CParticleSystem; + classid_mapping["ParticleSmokeGrenade"] = &ParticleSmokeGrenade; + classid_mapping["CParticleFire"] = &CParticleFire; + classid_mapping["MovieExplosion"] = &MovieExplosion; + classid_mapping["CMaterialModifyControl"] = &CMaterialModifyControl; + classid_mapping["CLightGlow"] = &CLightGlow; + classid_mapping["CInfoOverlayAccessor"] = &CInfoOverlayAccessor; + classid_mapping["CTEGaussExplosion"] = &CTEGaussExplosion; + classid_mapping["CFuncTrackTrain"] = &CFuncTrackTrain; + classid_mapping["CFuncSmokeVolume"] = &CFuncSmokeVolume; + classid_mapping["CFuncRotating"] = &CFuncRotating; + classid_mapping["CFuncReflectiveGlass"] = &CFuncReflectiveGlass; + classid_mapping["CFuncOccluder"] = &CFuncOccluder; + classid_mapping["CFunc_LOD"] = &CFunc_LOD; + classid_mapping["CTEDust"] = &CTEDust; + classid_mapping["CFunc_Dust"] = &CFunc_Dust; + classid_mapping["CFuncConveyor"] = &CFuncConveyor; + classid_mapping["CBreakableSurface"] = &CBreakableSurface; + classid_mapping["CFuncAreaPortalWindow"] = &CFuncAreaPortalWindow; + classid_mapping["CFish"] = &CFish; + classid_mapping["CEntityFlame"] = &CEntityFlame; + classid_mapping["CFireSmoke"] = &CFireSmoke; + classid_mapping["CEnvTonemapController"] = &CEnvTonemapController; + classid_mapping["CEnvScreenEffect"] = &CEnvScreenEffect; + classid_mapping["CEnvScreenOverlay"] = &CEnvScreenOverlay; + classid_mapping["CEnvProjectedTexture"] = &CEnvProjectedTexture; + classid_mapping["CEnvParticleScript"] = &CEnvParticleScript; + classid_mapping["CFogController"] = &CFogController; + classid_mapping["CEntityParticleTrail"] = &CEntityParticleTrail; + classid_mapping["CEntityDissolve"] = &CEntityDissolve; + classid_mapping["CEnvQuadraticBeam"] = &CEnvQuadraticBeam; + classid_mapping["CEmbers"] = &CEmbers; + classid_mapping["CEnvWind"] = &CEnvWind; + classid_mapping["CPrecipitation"] = &CPrecipitation; + classid_mapping["CDynamicLight"] = &CDynamicLight; + classid_mapping["CColorCorrectionVolume"] = &CColorCorrectionVolume; + classid_mapping["CColorCorrection"] = &CColorCorrection; + classid_mapping["CBreakableProp"] = &CBreakableProp; + classid_mapping["CBaseTempEntity"] = &CBaseTempEntity; + classid_mapping["CBasePlayer"] = &CBasePlayer; + classid_mapping["CBaseFlex"] = &CBaseFlex; + classid_mapping["CBaseEntity"] = &CBaseEntity; + classid_mapping["CBaseDoor"] = &CBaseDoor; + classid_mapping["CBaseCombatCharacter"] = &CBaseCombatCharacter; + classid_mapping["CBaseAnimatingOverlay"] = &CBaseAnimatingOverlay; + classid_mapping["CBoneFollower"] = &CBoneFollower; + classid_mapping["CBaseAnimating"] = &CBaseAnimating; + classid_mapping["CInfoLightingRelative"] = &CInfoLightingRelative; + classid_mapping["CAI_BaseNPC"] = &CAI_BaseNPC; + classid_mapping["CWeaponIFMSteadyCam"] = &CWeaponIFMSteadyCam; + classid_mapping["CWeaponIFMBaseCamera"] = &CWeaponIFMBaseCamera; + classid_mapping["CWeaponIFMBase"] = &CWeaponIFMBase; + classid_mapping["CTFWearableLevelableItem"] = &CTFWearableLevelableItem; + classid_mapping["CTFWearableDemoShield"] = &CTFWearableDemoShield; + classid_mapping["CTFWearableRobotArm"] = &CTFWearableRobotArm; + classid_mapping["CTFRobotArm"] = &CTFRobotArm; + classid_mapping["CTFWrench"] = &CTFWrench; + classid_mapping["CTFProjectile_ThrowableBreadMonster"] = &CTFProjectile_ThrowableBreadMonster; + classid_mapping["CTFProjectile_ThrowableBrick"] = &CTFProjectile_ThrowableBrick; + classid_mapping["CTFProjectile_ThrowableRepel"] = &CTFProjectile_ThrowableRepel; + classid_mapping["CTFProjectile_Throwable"] = &CTFProjectile_Throwable; + classid_mapping["CTFThrowable"] = &CTFThrowable; + classid_mapping["CTFSyringeGun"] = &CTFSyringeGun; + classid_mapping["CTFKatana"] = &CTFKatana; + classid_mapping["CTFSword"] = &CTFSword; + classid_mapping["CSniperDot"] = &CSniperDot; + classid_mapping["CTFSniperRifleClassic"] = &CTFSniperRifleClassic; + classid_mapping["CTFSniperRifleDecap"] = &CTFSniperRifleDecap; + classid_mapping["CTFSniperRifle"] = &CTFSniperRifle; + classid_mapping["CTFChargedSMG"] = &CTFChargedSMG; + classid_mapping["CTFSMG"] = &CTFSMG; + classid_mapping["CTFShovel"] = &CTFShovel; + classid_mapping["CTFShotgunBuildingRescue"] = &CTFShotgunBuildingRescue; + classid_mapping["CTFPEPBrawlerBlaster"] = &CTFPEPBrawlerBlaster; + classid_mapping["CTFSodaPopper"] = &CTFSodaPopper; + classid_mapping["CTFShotgun_Revenge"] = &CTFShotgun_Revenge; + classid_mapping["CTFScatterGun"] = &CTFScatterGun; + classid_mapping["CTFShotgun_Pyro"] = &CTFShotgun_Pyro; + classid_mapping["CTFShotgun_HWG"] = &CTFShotgun_HWG; + classid_mapping["CTFShotgun_Soldier"] = &CTFShotgun_Soldier; + classid_mapping["CTFShotgun"] = &CTFShotgun; + classid_mapping["CTFCrossbow"] = &CTFCrossbow; + classid_mapping["CTFRocketLauncher_Mortar"] = &CTFRocketLauncher_Mortar; + classid_mapping["CTFRocketLauncher_AirStrike"] = &CTFRocketLauncher_AirStrike; + classid_mapping["CTFRocketLauncher_DirectHit"] = &CTFRocketLauncher_DirectHit; + classid_mapping["CTFRocketLauncher"] = &CTFRocketLauncher; + classid_mapping["CTFRevolver"] = &CTFRevolver; + classid_mapping["CTFDRGPomson"] = &CTFDRGPomson; + classid_mapping["CTFRaygun"] = &CTFRaygun; + classid_mapping["CTFPistol_ScoutSecondary"] = &CTFPistol_ScoutSecondary; + classid_mapping["CTFPistol_ScoutPrimary"] = &CTFPistol_ScoutPrimary; + classid_mapping["CTFPistol_Scout"] = &CTFPistol_Scout; + classid_mapping["CTFPistol"] = &CTFPistol; + classid_mapping["CTFPipebombLauncher"] = &CTFPipebombLauncher; + classid_mapping["CTFWeaponPDA_Spy"] = &CTFWeaponPDA_Spy; + classid_mapping["CTFWeaponPDA_Engineer_Destroy"] = &CTFWeaponPDA_Engineer_Destroy; + classid_mapping["CTFWeaponPDA_Engineer_Build"] = &CTFWeaponPDA_Engineer_Build; + classid_mapping["CTFWeaponPDAExpansion_Teleporter"] = &CTFWeaponPDAExpansion_Teleporter; + classid_mapping["CTFWeaponPDAExpansion_Dispenser"] = &CTFWeaponPDAExpansion_Dispenser; + classid_mapping["CTFWeaponPDA"] = &CTFWeaponPDA; + classid_mapping["CPasstimeGun"] = &CPasstimeGun; + classid_mapping["CTFParticleCannon"] = &CTFParticleCannon; + classid_mapping["CTFParachute_Secondary"] = &CTFParachute_Secondary; + classid_mapping["CTFParachute_Primary"] = &CTFParachute_Primary; + classid_mapping["CTFParachute"] = &CTFParachute; + classid_mapping["CTFMinigun"] = &CTFMinigun; + classid_mapping["CTFMedigunShield"] = &CTFMedigunShield; + classid_mapping["CWeaponMedigun"] = &CWeaponMedigun; + classid_mapping["CTFMechanicalArm"] = &CTFMechanicalArm; + classid_mapping["CTFLunchBox_Drink"] = &CTFLunchBox_Drink; + classid_mapping["CTFLunchBox"] = &CTFLunchBox; + classid_mapping["CLaserDot"] = &CLaserDot; + classid_mapping["CTFLaserPointer"] = &CTFLaserPointer; + classid_mapping["CTFKnife"] = &CTFKnife; + classid_mapping["CTFProjectile_Cleaver"] = &CTFProjectile_Cleaver; + classid_mapping["CTFProjectile_JarMilk"] = &CTFProjectile_JarMilk; + classid_mapping["CTFProjectile_Jar"] = &CTFProjectile_Jar; + classid_mapping["CTFCleaver"] = &CTFCleaver; + classid_mapping["CTFJarMilk"] = &CTFJarMilk; + classid_mapping["CTFJar"] = &CTFJar; + classid_mapping["CTFWeaponInvis"] = &CTFWeaponInvis; + classid_mapping["CTFGrenadePipebombProjectile"] = &CTFGrenadePipebombProjectile; + classid_mapping["CTFCannon"] = &CTFCannon; + classid_mapping["CTFGrenadeLauncher"] = &CTFGrenadeLauncher; + classid_mapping["CTFGrapplingHook"] = &CTFGrapplingHook; + classid_mapping["CTFFlareGun_Revenge"] = &CTFFlareGun_Revenge; + classid_mapping["CTFFlareGun"] = &CTFFlareGun; + classid_mapping["CTFFlameRocket"] = &CTFFlameRocket; + classid_mapping["CTFFlameThrower"] = &CTFFlameThrower; + classid_mapping["CTFFists"] = &CTFFists; + classid_mapping["CTFFireAxe"] = &CTFFireAxe; + classid_mapping["CTFCompoundBow"] = &CTFCompoundBow; + classid_mapping["CTFClub"] = &CTFClub; + classid_mapping["CTFBuffItem"] = &CTFBuffItem; + classid_mapping["CTFStickBomb"] = &CTFStickBomb; + classid_mapping["CTFBottle"] = &CTFBottle; + classid_mapping["CTFBonesaw"] = &CTFBonesaw; + classid_mapping["CTFBall_Ornament"] = &CTFBall_Ornament; + classid_mapping["CTFStunBall"] = &CTFStunBall; + classid_mapping["CTFBat_Giftwrap"] = &CTFBat_Giftwrap; + classid_mapping["CTFBat_Wood"] = &CTFBat_Wood; + classid_mapping["CTFBat_Fish"] = &CTFBat_Fish; + classid_mapping["CTFBat"] = &CTFBat; + classid_mapping["CTFBaseRocket"] = &CTFBaseRocket; + classid_mapping["CTFWeaponBaseMerasmusGrenade"] = &CTFWeaponBaseMerasmusGrenade; + classid_mapping["CTFWeaponBaseMelee"] = &CTFWeaponBaseMelee; + classid_mapping["CTFWeaponBaseGun"] = &CTFWeaponBaseGun; + classid_mapping["CTFWeaponBaseGrenadeProj"] = &CTFWeaponBaseGrenadeProj; + classid_mapping["CTFWeaponBase"] = &CTFWeaponBase; + classid_mapping["CTFViewModel"] = &CTFViewModel; + classid_mapping["CRobotDispenser"] = &CRobotDispenser; + classid_mapping["CTFRobotDestruction_Robot"] = &CTFRobotDestruction_Robot; + classid_mapping["CTFReviveMarker"] = &CTFReviveMarker; + classid_mapping["CTFPumpkinBomb"] = &CTFPumpkinBomb; + classid_mapping["CTFProjectile_EnergyRing"] = &CTFProjectile_EnergyRing; + classid_mapping["CTFBaseProjectile"] = &CTFBaseProjectile; + classid_mapping["CBaseObjectUpgrade"] = &CBaseObjectUpgrade; + classid_mapping["CMannVsMachineStats"] = &CMannVsMachineStats; + classid_mapping["CTFRobotDestructionLogic"] = &CTFRobotDestructionLogic; + classid_mapping["CTFRobotDestruction_RobotGroup"] = &CTFRobotDestruction_RobotGroup; + classid_mapping["CTFRobotDestruction_RobotSpawn"] = &CTFRobotDestruction_RobotSpawn; + classid_mapping["CTFPlayerDestructionLogic"] = &CTFPlayerDestructionLogic; + classid_mapping["CPlayerDestructionDispenser"] = &CPlayerDestructionDispenser; + classid_mapping["CTFMinigameLogic"] = &CTFMinigameLogic; + classid_mapping["CTFHalloweenMinigame_FallingPlatforms"] = &CTFHalloweenMinigame_FallingPlatforms; + classid_mapping["CTFHalloweenMinigame"] = &CTFHalloweenMinigame; + classid_mapping["CTFMiniGame"] = &CTFMiniGame; + classid_mapping["CTFWearableVM"] = &CTFWearableVM; + classid_mapping["CTFWearable"] = &CTFWearable; + classid_mapping["CTFPowerupBottle"] = &CTFPowerupBottle; + classid_mapping["CTFItem"] = &CTFItem; + classid_mapping["CHalloweenSoulPack"] = &CHalloweenSoulPack; + classid_mapping["CTFGenericBomb"] = &CTFGenericBomb; + classid_mapping["CBonusRoundLogic"] = &CBonusRoundLogic; + classid_mapping["CTFGameRulesProxy"] = &CTFGameRulesProxy; + classid_mapping["CTFDroppedWeapon"] = &CTFDroppedWeapon; + classid_mapping["CTFProjectile_SpellKartBats"] = &CTFProjectile_SpellKartBats; + classid_mapping["CTFProjectile_SpellKartOrb"] = &CTFProjectile_SpellKartOrb; + classid_mapping["CTFHellZap"] = &CTFHellZap; + classid_mapping["CTFProjectile_SpellLightningOrb"] = &CTFProjectile_SpellLightningOrb; + classid_mapping["CTFProjectile_SpellTransposeTeleport"] = &CTFProjectile_SpellTransposeTeleport; + classid_mapping["CTFProjectile_SpellMeteorShower"] = &CTFProjectile_SpellMeteorShower; + classid_mapping["CTFProjectile_SpellSpawnBoss"] = &CTFProjectile_SpellSpawnBoss; + classid_mapping["CTFProjectile_SpellMirv"] = &CTFProjectile_SpellMirv; + classid_mapping["CTFProjectile_SpellPumpkin"] = &CTFProjectile_SpellPumpkin; + classid_mapping["CTFProjectile_SpellSpawnHorde"] = &CTFProjectile_SpellSpawnHorde; + classid_mapping["CTFProjectile_SpellSpawnZombie"] = &CTFProjectile_SpellSpawnZombie; + classid_mapping["CTFProjectile_SpellBats"] = &CTFProjectile_SpellBats; + classid_mapping["CTFProjectile_SpellFireball"] = &CTFProjectile_SpellFireball; + classid_mapping["CTFSpellBook"] = &CTFSpellBook; + classid_mapping["CHightower_TeleportVortex"] = &CHightower_TeleportVortex; + classid_mapping["CTeleportVortex"] = &CTeleportVortex; + classid_mapping["CHalloweenGiftPickup"] = &CHalloweenGiftPickup; + classid_mapping["CBonusDuckPickup"] = &CBonusDuckPickup; + classid_mapping["CHalloweenPickup"] = &CHalloweenPickup; + classid_mapping["CCaptureFlagReturnIcon"] = &CCaptureFlagReturnIcon; + classid_mapping["CCaptureFlag"] = &CCaptureFlag; + classid_mapping["CBonusPack"] = &CBonusPack; + classid_mapping["CHandleTest"] = &CHandleTest; + classid_mapping["CTeamRoundTimer"] = &CTeamRoundTimer; + classid_mapping["CTeamplayRoundBasedRulesProxy"] = &CTeamplayRoundBasedRulesProxy; + classid_mapping["CSpriteTrail"] = &CSpriteTrail; + classid_mapping["CSpriteOriented"] = &CSpriteOriented; + classid_mapping["CSprite"] = &CSprite; + classid_mapping["CPoseController"] = &CPoseController; + classid_mapping["CGameRulesProxy"] = &CGameRulesProxy; + classid_mapping["CInfoLadderDismount"] = &CInfoLadderDismount; + classid_mapping["CFuncLadder"] = &CFuncLadder; + classid_mapping["CEnvDetailController"] = &CEnvDetailController; + classid_mapping["CTFWearableItem"] = &CTFWearableItem; + classid_mapping["CEconWearable"] = &CEconWearable; + classid_mapping["CBaseAttributableItem"] = &CBaseAttributableItem; + classid_mapping["CEconEntity"] = &CEconEntity; + classid_mapping["CBeam"] = &CBeam; + classid_mapping["CBaseViewModel"] = &CBaseViewModel; + classid_mapping["CBaseProjectile"] = &CBaseProjectile; + classid_mapping["CBaseParticleEntity"] = &CBaseParticleEntity; + classid_mapping["CBaseGrenade"] = &CBaseGrenade; + classid_mapping["CBaseCombatWeapon"] = &CBaseCombatWeapon; + classid_mapping["CVoteController"] = &CVoteController; + classid_mapping["CTEHL2MPFireBullets"] = &CTEHL2MPFireBullets; + classid_mapping["CHL2MPRagdoll"] = &CHL2MPRagdoll; + classid_mapping["CHL2MP_Player"] = &CHL2MP_Player; + classid_mapping["CWeaponCitizenSuitcase"] = &CWeaponCitizenSuitcase; + classid_mapping["CWeaponCitizenPackage"] = &CWeaponCitizenPackage; + classid_mapping["CWeaponAlyxGun"] = &CWeaponAlyxGun; + classid_mapping["CWeaponCubemap"] = &CWeaponCubemap; + classid_mapping["CWeaponGaussGun"] = &CWeaponGaussGun; + classid_mapping["CWeaponAnnabelle"] = &CWeaponAnnabelle; + classid_mapping["CFlaregun"] = &CFlaregun; + classid_mapping["CWeaponBugBait"] = &CWeaponBugBait; + classid_mapping["CWeaponBinoculars"] = &CWeaponBinoculars; + classid_mapping["CWeaponCycler"] = &CWeaponCycler; + classid_mapping["CCrossbowBolt"] = &CCrossbowBolt; + classid_mapping["CPropVehiclePrisonerPod"] = &CPropVehiclePrisonerPod; + classid_mapping["CPropCrane"] = &CPropCrane; + classid_mapping["CPropCannon"] = &CPropCannon; + classid_mapping["CPropAirboat"] = &CPropAirboat; + classid_mapping["CFlare"] = &CFlare; + classid_mapping["CTEConcussiveExplosion"] = &CTEConcussiveExplosion; + classid_mapping["CNPC_Strider"] = &CNPC_Strider; + classid_mapping["CScriptIntro"] = &CScriptIntro; + classid_mapping["CRotorWashEmitter"] = &CRotorWashEmitter; + classid_mapping["CPropCombineBall"] = &CPropCombineBall; + classid_mapping["CPlasmaBeamNode"] = &CPlasmaBeamNode; + classid_mapping["CNPC_RollerMine"] = &CNPC_RollerMine; + classid_mapping["CNPC_Manhack"] = &CNPC_Manhack; + classid_mapping["CNPC_CombineGunship"] = &CNPC_CombineGunship; + classid_mapping["CNPC_AntlionGuard"] = &CNPC_AntlionGuard; + classid_mapping["CInfoTeleporterCountdown"] = &CInfoTeleporterCountdown; + classid_mapping["CMortarShell"] = &CMortarShell; + classid_mapping["CEnvStarfield"] = &CEnvStarfield; + classid_mapping["CEnvHeadcrabCanister"] = &CEnvHeadcrabCanister; + classid_mapping["CAlyxEmpEffect"] = &CAlyxEmpEffect; + classid_mapping["CCorpse"] = &CCorpse; + classid_mapping["CCitadelEnergyCore"] = &CCitadelEnergyCore; + classid_mapping["CHL2_Player"] = &CHL2_Player; + classid_mapping["CBaseHLBludgeonWeapon"] = &CBaseHLBludgeonWeapon; + classid_mapping["CHLSelectFireMachineGun"] = &CHLSelectFireMachineGun; + classid_mapping["CHLMachineGun"] = &CHLMachineGun; + classid_mapping["CBaseHelicopter"] = &CBaseHelicopter; + classid_mapping["CNPC_Barney"] = &CNPC_Barney; + classid_mapping["CNPC_Barnacle"] = &CNPC_Barnacle; + classid_mapping["AR2Explosion"] = &AR2Explosion; + classid_mapping["CTEAntlionDust"] = &CTEAntlionDust; + classid_mapping["CVortigauntEffectDispel"] = &CVortigauntEffectDispel; + classid_mapping["CVortigauntChargeToken"] = &CVortigauntChargeToken; + classid_mapping["CNPC_Vortigaunt"] = &CNPC_Vortigaunt; + classid_mapping["CPredictedViewModel"] = &CPredictedViewModel; + classid_mapping["CWeaponStunStick"] = &CWeaponStunStick; + classid_mapping["CWeaponSMG1"] = &CWeaponSMG1; + classid_mapping["CWeapon_SLAM"] = &CWeapon_SLAM; + classid_mapping["CWeaponShotgun"] = &CWeaponShotgun; + classid_mapping["CWeaponRPG"] = &CWeaponRPG; + classid_mapping["CWeaponPistol"] = &CWeaponPistol; + classid_mapping["CWeaponPhysCannon"] = &CWeaponPhysCannon; + classid_mapping["CHL2MPMachineGun"] = &CHL2MPMachineGun; + classid_mapping["CBaseHL2MPCombatWeapon"] = &CBaseHL2MPCombatWeapon; + classid_mapping["CBaseHL2MPBludgeonWeapon"] = &CBaseHL2MPBludgeonWeapon; + classid_mapping["CWeaponHL2MPBase"] = &CWeaponHL2MPBase; + classid_mapping["CWeaponFrag"] = &CWeaponFrag; + classid_mapping["CWeaponCrowbar"] = &CWeaponCrowbar; + classid_mapping["CWeaponCrossbow"] = &CWeaponCrossbow; + classid_mapping["CWeaponAR2"] = &CWeaponAR2; + classid_mapping["CWeapon357"] = &CWeapon357; + classid_mapping["CHL2MPGameRulesProxy"] = &CHL2MPGameRulesProxy; + classid_mapping["CHalfLife2Proxy"] = &CHalfLife2Proxy; + classid_mapping["CBaseHLCombatWeapon"] = &CBaseHLCombatWeapon; + classid_mapping["CTFVehicle"] = &CTFVehicle; + classid_mapping["CTFBaseDMPowerup"] = &CTFBaseDMPowerup; + classid_mapping["CWeaponSpawner"] = &CWeaponSpawner; + classid_mapping["CTFUmbrella"] = &CTFUmbrella; + classid_mapping["CTFTranq"] = &CTFTranq; + classid_mapping["CTFSMG_Primary"] = &CTFSMG_Primary; + classid_mapping["CTFRevolver_Secondary"] = &CTFRevolver_Secondary; + classid_mapping["CTFNailgun"] = &CTFNailgun; + classid_mapping["CTFHunterRifle"] = &CTFHunterRifle; + classid_mapping["CTFHeavyArtillery"] = &CTFHeavyArtillery; + classid_mapping["CTFHammerfists"] = &CTFHammerfists; + classid_mapping["CTFCrowbar"] = &CTFCrowbar; + classid_mapping["CTFChainsaw"] = &CTFChainsaw; + classid_mapping["CTEPlantBomb"] = &CTEPlantBomb; + classid_mapping["CTERadioIcon"] = &CTERadioIcon; + classid_mapping["CPlantedC4"] = &CPlantedC4; + classid_mapping["CCSTeam"] = &CCSTeam; + classid_mapping["CCSPlayerResource"] = &CCSPlayerResource; + classid_mapping["CCSPlayer"] = &CCSPlayer; + classid_mapping["CCSRagdoll"] = &CCSRagdoll; + classid_mapping["CHostage"] = &CHostage; + classid_mapping["CWeaponXM1014"] = &CWeaponXM1014; + classid_mapping["CWeaponUSP"] = &CWeaponUSP; + classid_mapping["CWeaponUMP45"] = &CWeaponUMP45; + classid_mapping["CWeaponTMP"] = &CWeaponTMP; + classid_mapping["CSmokeGrenade"] = &CSmokeGrenade; + classid_mapping["CWeaponSG552"] = &CWeaponSG552; + classid_mapping["CWeaponSG550"] = &CWeaponSG550; + classid_mapping["CWeaponScout"] = &CWeaponScout; + classid_mapping["CWeaponP90"] = &CWeaponP90; + classid_mapping["CWeaponP228"] = &CWeaponP228; + classid_mapping["CWeaponMP5Navy"] = &CWeaponMP5Navy; + classid_mapping["CWeaponMAC10"] = &CWeaponMAC10; + classid_mapping["CWeaponM4A1"] = &CWeaponM4A1; + classid_mapping["CWeaponM3"] = &CWeaponM3; + classid_mapping["CWeaponM249"] = &CWeaponM249; + classid_mapping["CKnife"] = &CKnife; + classid_mapping["CHEGrenade"] = &CHEGrenade; + classid_mapping["CWeaponGlock"] = &CWeaponGlock; + classid_mapping["CWeaponGalil"] = &CWeaponGalil; + classid_mapping["CWeaponG3SG1"] = &CWeaponG3SG1; + classid_mapping["CFlashbang"] = &CFlashbang; + classid_mapping["CWeaponFiveSeven"] = &CWeaponFiveSeven; + classid_mapping["CWeaponFamas"] = &CWeaponFamas; + classid_mapping["CWeaponElite"] = &CWeaponElite; + classid_mapping["CDEagle"] = &CDEagle; + classid_mapping["CWeaponCSBaseGun"] = &CWeaponCSBaseGun; + classid_mapping["CWeaponCSBase"] = &CWeaponCSBase; + classid_mapping["CC4"] = &CC4; + classid_mapping["CBaseCSGrenade"] = &CBaseCSGrenade; + classid_mapping["CWeaponAWP"] = &CWeaponAWP; + classid_mapping["CWeaponAug"] = &CWeaponAug; + classid_mapping["CAK47"] = &CAK47; + classid_mapping["CFootstepControl"] = &CFootstepControl; + classid_mapping["CCSGameRulesProxy"] = &CCSGameRulesProxy; + classid_mapping["CBaseCSGrenadeProjectile"] = &CBaseCSGrenadeProjectile; + classid_mapping["CSDKTeam_Deathmatch"] = &CSDKTeam_Deathmatch; + classid_mapping["CSDKTeam_Red"] = &CSDKTeam_Red; + classid_mapping["CSDKTeam_Blue"] = &CSDKTeam_Blue; + classid_mapping["CSDKTeam_Unassigned"] = &CSDKTeam_Unassigned; + classid_mapping["CSDKTeam"] = &CSDKTeam; + classid_mapping["CSDKPlayerResource"] = &CSDKPlayerResource; + classid_mapping["CSDKRagdoll"] = &CSDKRagdoll; + classid_mapping["CSDKPlayer"] = &CSDKPlayer; + classid_mapping["CSparkler"] = &CSparkler; + classid_mapping["CRatRaceWaypoint"] = &CRatRaceWaypoint; + classid_mapping["CBriefcaseCaptureZone"] = &CBriefcaseCaptureZone; + classid_mapping["CBriefcase"] = &CBriefcase; + classid_mapping["CWeaponSDKBase"] = &CWeaponSDKBase; + classid_mapping["CWeaponMP5K"] = &CWeaponMP5K; + classid_mapping["CWeaponMossberg"] = &CWeaponMossberg; + classid_mapping["CWeaponM1911"] = &CWeaponM1911; + classid_mapping["CWeaponM16"] = &CWeaponM16; + classid_mapping["CWeaponGrenade"] = &CWeaponGrenade; + classid_mapping["CWeaponFAL"] = &CWeaponFAL; + classid_mapping["CWeaponBrawl"] = &CWeaponBrawl; + classid_mapping["CWeaponBeretta"] = &CWeaponBeretta; + classid_mapping["CBaseSDKGrenade"] = &CBaseSDKGrenade; + classid_mapping["CAkimboM1911"] = &CAkimboM1911; + classid_mapping["CAkimboBeretta"] = &CAkimboBeretta; + classid_mapping["CAkimboBase"] = &CAkimboBase; + classid_mapping["CWeaponSDKMelee"] = &CWeaponSDKMelee; + classid_mapping["CSDKGameRulesProxy"] = &CSDKGameRulesProxy; + classid_mapping["CBaseGrenadeProjectile"] = &CBaseGrenadeProjectile; + classid_mapping["CDAViewModel"] = &CDAViewModel; + +} + +void dynamic::Populate() { + ClientClass* cc = g_IBaseClient->GetAllClasses(); + while (cc) { + std::string name(cc->GetName()); + if (classid_mapping.find(name) != classid_mapping.end()) + *classid_mapping[name] = cc->m_ClassID; + cc = cc->m_pNext; + } +} + +dynamic dynamic_list; + +} \ No newline at end of file diff --git a/src/classinfo/dynamic.gen.hpp b/src/classinfo/dynamic.gen.hpp new file mode 100644 index 00000000..0e1c4b5c --- /dev/null +++ b/src/classinfo/dynamic.gen.hpp @@ -0,0 +1,529 @@ +/* + AUTO-GENERATED HEADER - DO NOT MODIFY + HEADER FOR UNIVERSAL BUILD +*/ + +#ifndef DYNAMIC_AUTOGEN_HPP +#define DYNAMIC_AUTOGEN_HPP + +namespace client_classes { + + class dynamic { + public: + dynamic(); + void Populate(); + int CTETFParticleEffect { 0 }; + int CTETFExplosion { 0 }; + int CTETFBlood { 0 }; + int CTFTankBoss { 0 }; + int CTFBaseBoss { 0 }; + int CBossAlpha { 0 }; + int CZombie { 0 }; + int CMerasmusDancer { 0 }; + int CMerasmus { 0 }; + int CHeadlessHatman { 0 }; + int CEyeballBoss { 0 }; + int CTFWeaponSapper { 0 }; + int CTFWeaponBuilder { 0 }; + int C_TFWeaponBuilder { 0 }; + int CTFTeam { 0 }; + int CTFTauntProp { 0 }; + int CTFProjectile_Rocket { 0 }; + int CTFProjectile_Flare { 0 }; + int CTFProjectile_EnergyBall { 0 }; + int CTFProjectile_GrapplingHook { 0 }; + int CTFProjectile_HealingBolt { 0 }; + int CTFProjectile_Arrow { 0 }; + int CTFPlayerResource { 0 }; + int CTFPlayer { 0 }; + int CTFRagdoll { 0 }; + int CTEPlayerAnimEvent { 0 }; + int CTFPasstimeLogic { 0 }; + int CPasstimeBall { 0 }; + int CTFObjectiveResource { 0 }; + int CTFGlow { 0 }; + int CTEFireBullets { 0 }; + int CTFBuffBanner { 0 }; + int CTFAmmoPack { 0 }; + int CObjectTeleporter { 0 }; + int CObjectSentrygun { 0 }; + int CTFProjectile_SentryRocket { 0 }; + int CObjectSapper { 0 }; + int CObjectCartDispenser { 0 }; + int CObjectDispenser { 0 }; + int CMonsterResource { 0 }; + int CFuncRespawnRoomVisualizer { 0 }; + int CFuncRespawnRoom { 0 }; + int CFuncPasstimeGoal { 0 }; + int CFuncForceField { 0 }; + int CCaptureZone { 0 }; + int CCurrencyPack { 0 }; + int CBaseObject { 0 }; + int CTFBotHintEngineerNest { 0 }; + int CBotNPCMinion { 0 }; + int CBotNPC { 0 }; + int CRagdollPropAttached { 0 }; + int CRagdollProp { 0 }; + int NextBotCombatCharacter { 0 }; + int CWaterBullet { 0 }; + int CFuncMonitor { 0 }; + int CWorld { 0 }; + int CWaterLODControl { 0 }; + int CVGuiScreen { 0 }; + int CPropJeep { 0 }; + int CPropVehicleChoreoGeneric { 0 }; + int CTEWorldDecal { 0 }; + int CTESpriteSpray { 0 }; + int CTESprite { 0 }; + int CTESparks { 0 }; + int CTESmoke { 0 }; + int CTEShowLine { 0 }; + int CTEProjectedDecal { 0 }; + int CTEPlayerDecal { 0 }; + int CTEPhysicsProp { 0 }; + int CTEParticleSystem { 0 }; + int CTEMuzzleFlash { 0 }; + int CTELargeFunnel { 0 }; + int CTEKillPlayerAttachments { 0 }; + int CTEImpact { 0 }; + int CTEGlowSprite { 0 }; + int CTEShatterSurface { 0 }; + int CTEFootprintDecal { 0 }; + int CTEFizz { 0 }; + int CTEExplosion { 0 }; + int CTEEnergySplash { 0 }; + int CTEEffectDispatch { 0 }; + int CTEDynamicLight { 0 }; + int CTEDecal { 0 }; + int CTEClientProjectile { 0 }; + int CTEBubbleTrail { 0 }; + int CTEBubbles { 0 }; + int CTEBSPDecal { 0 }; + int CTEBreakModel { 0 }; + int CTEBloodStream { 0 }; + int CTEBloodSprite { 0 }; + int CTEBeamSpline { 0 }; + int CTEBeamRingPoint { 0 }; + int CTEBeamRing { 0 }; + int CTEBeamPoints { 0 }; + int CTEBeamLaser { 0 }; + int CTEBeamFollow { 0 }; + int CTEBeamEnts { 0 }; + int CTEBeamEntPoint { 0 }; + int CTEBaseBeam { 0 }; + int CTEArmorRicochet { 0 }; + int CTEMetalSparks { 0 }; + int CTest_ProxyToggle_Networkable { 0 }; + int CTestTraceline { 0 }; + int CTesla { 0 }; + int CTeamTrainWatcher { 0 }; + int CBaseTeamObjectiveResource { 0 }; + int CTeam { 0 }; + int CSun { 0 }; + int CSteamJet { 0 }; + int CParticlePerformanceMonitor { 0 }; + int CSpotlightEnd { 0 }; + int DustTrail { 0 }; + int CFireTrail { 0 }; + int SporeTrail { 0 }; + int SporeExplosion { 0 }; + int RocketTrail { 0 }; + int SmokeTrail { 0 }; + int CSmokeStack { 0 }; + int CSlideshowDisplay { 0 }; + int CShadowControl { 0 }; + int CSceneEntity { 0 }; + int CRopeKeyframe { 0 }; + int CRagdollManager { 0 }; + int CPropVehicleDriveable { 0 }; + int CPhysicsPropMultiplayer { 0 }; + int CPhysBoxMultiplayer { 0 }; + int CBasePropDoor { 0 }; + int CDynamicProp { 0 }; + int CPointCommentaryNode { 0 }; + int CPointCamera { 0 }; + int CPlayerResource { 0 }; + int CPlasma { 0 }; + int CPhysMagnet { 0 }; + int CPhysicsProp { 0 }; + int CPhysBox { 0 }; + int CParticleSystem { 0 }; + int ParticleSmokeGrenade { 0 }; + int CParticleFire { 0 }; + int MovieExplosion { 0 }; + int CMaterialModifyControl { 0 }; + int CLightGlow { 0 }; + int CInfoOverlayAccessor { 0 }; + int CTEGaussExplosion { 0 }; + int CFuncTrackTrain { 0 }; + int CFuncSmokeVolume { 0 }; + int CFuncRotating { 0 }; + int CFuncReflectiveGlass { 0 }; + int CFuncOccluder { 0 }; + int CFunc_LOD { 0 }; + int CTEDust { 0 }; + int CFunc_Dust { 0 }; + int CFuncConveyor { 0 }; + int CBreakableSurface { 0 }; + int CFuncAreaPortalWindow { 0 }; + int CFish { 0 }; + int CEntityFlame { 0 }; + int CFireSmoke { 0 }; + int CEnvTonemapController { 0 }; + int CEnvScreenEffect { 0 }; + int CEnvScreenOverlay { 0 }; + int CEnvProjectedTexture { 0 }; + int CEnvParticleScript { 0 }; + int CFogController { 0 }; + int CEntityParticleTrail { 0 }; + int CEntityDissolve { 0 }; + int CEnvQuadraticBeam { 0 }; + int CEmbers { 0 }; + int CEnvWind { 0 }; + int CPrecipitation { 0 }; + int CDynamicLight { 0 }; + int CColorCorrectionVolume { 0 }; + int CColorCorrection { 0 }; + int CBreakableProp { 0 }; + int CBaseTempEntity { 0 }; + int CBasePlayer { 0 }; + int CBaseFlex { 0 }; + int CBaseEntity { 0 }; + int CBaseDoor { 0 }; + int CBaseCombatCharacter { 0 }; + int CBaseAnimatingOverlay { 0 }; + int CBoneFollower { 0 }; + int CBaseAnimating { 0 }; + int CInfoLightingRelative { 0 }; + int CAI_BaseNPC { 0 }; + int CWeaponIFMSteadyCam { 0 }; + int CWeaponIFMBaseCamera { 0 }; + int CWeaponIFMBase { 0 }; + int CTFWearableLevelableItem { 0 }; + int CTFWearableDemoShield { 0 }; + int CTFWearableRobotArm { 0 }; + int CTFRobotArm { 0 }; + int CTFWrench { 0 }; + int CTFProjectile_ThrowableBreadMonster { 0 }; + int CTFProjectile_ThrowableBrick { 0 }; + int CTFProjectile_ThrowableRepel { 0 }; + int CTFProjectile_Throwable { 0 }; + int CTFThrowable { 0 }; + int CTFSyringeGun { 0 }; + int CTFKatana { 0 }; + int CTFSword { 0 }; + int CSniperDot { 0 }; + int CTFSniperRifleClassic { 0 }; + int CTFSniperRifleDecap { 0 }; + int CTFSniperRifle { 0 }; + int CTFChargedSMG { 0 }; + int CTFSMG { 0 }; + int CTFShovel { 0 }; + int CTFShotgunBuildingRescue { 0 }; + int CTFPEPBrawlerBlaster { 0 }; + int CTFSodaPopper { 0 }; + int CTFShotgun_Revenge { 0 }; + int CTFScatterGun { 0 }; + int CTFShotgun_Pyro { 0 }; + int CTFShotgun_HWG { 0 }; + int CTFShotgun_Soldier { 0 }; + int CTFShotgun { 0 }; + int CTFCrossbow { 0 }; + int CTFRocketLauncher_Mortar { 0 }; + int CTFRocketLauncher_AirStrike { 0 }; + int CTFRocketLauncher_DirectHit { 0 }; + int CTFRocketLauncher { 0 }; + int CTFRevolver { 0 }; + int CTFDRGPomson { 0 }; + int CTFRaygun { 0 }; + int CTFPistol_ScoutSecondary { 0 }; + int CTFPistol_ScoutPrimary { 0 }; + int CTFPistol_Scout { 0 }; + int CTFPistol { 0 }; + int CTFPipebombLauncher { 0 }; + int CTFWeaponPDA_Spy { 0 }; + int CTFWeaponPDA_Engineer_Destroy { 0 }; + int CTFWeaponPDA_Engineer_Build { 0 }; + int CTFWeaponPDAExpansion_Teleporter { 0 }; + int CTFWeaponPDAExpansion_Dispenser { 0 }; + int CTFWeaponPDA { 0 }; + int CPasstimeGun { 0 }; + int CTFParticleCannon { 0 }; + int CTFParachute_Secondary { 0 }; + int CTFParachute_Primary { 0 }; + int CTFParachute { 0 }; + int CTFMinigun { 0 }; + int CTFMedigunShield { 0 }; + int CWeaponMedigun { 0 }; + int CTFMechanicalArm { 0 }; + int CTFLunchBox_Drink { 0 }; + int CTFLunchBox { 0 }; + int CLaserDot { 0 }; + int CTFLaserPointer { 0 }; + int CTFKnife { 0 }; + int CTFProjectile_Cleaver { 0 }; + int CTFProjectile_JarMilk { 0 }; + int CTFProjectile_Jar { 0 }; + int CTFCleaver { 0 }; + int CTFJarMilk { 0 }; + int CTFJar { 0 }; + int CTFWeaponInvis { 0 }; + int CTFGrenadePipebombProjectile { 0 }; + int CTFCannon { 0 }; + int CTFGrenadeLauncher { 0 }; + int CTFGrapplingHook { 0 }; + int CTFFlareGun_Revenge { 0 }; + int CTFFlareGun { 0 }; + int CTFFlameRocket { 0 }; + int CTFFlameThrower { 0 }; + int CTFFists { 0 }; + int CTFFireAxe { 0 }; + int CTFCompoundBow { 0 }; + int CTFClub { 0 }; + int CTFBuffItem { 0 }; + int CTFStickBomb { 0 }; + int CTFBottle { 0 }; + int CTFBonesaw { 0 }; + int CTFBall_Ornament { 0 }; + int CTFStunBall { 0 }; + int CTFBat_Giftwrap { 0 }; + int CTFBat_Wood { 0 }; + int CTFBat_Fish { 0 }; + int CTFBat { 0 }; + int CTFBaseRocket { 0 }; + int CTFWeaponBaseMerasmusGrenade { 0 }; + int CTFWeaponBaseMelee { 0 }; + int CTFWeaponBaseGun { 0 }; + int CTFWeaponBaseGrenadeProj { 0 }; + int CTFWeaponBase { 0 }; + int CTFViewModel { 0 }; + int CRobotDispenser { 0 }; + int CTFRobotDestruction_Robot { 0 }; + int CTFReviveMarker { 0 }; + int CTFPumpkinBomb { 0 }; + int CTFProjectile_EnergyRing { 0 }; + int CTFBaseProjectile { 0 }; + int CBaseObjectUpgrade { 0 }; + int CMannVsMachineStats { 0 }; + int CTFRobotDestructionLogic { 0 }; + int CTFRobotDestruction_RobotGroup { 0 }; + int CTFRobotDestruction_RobotSpawn { 0 }; + int CTFPlayerDestructionLogic { 0 }; + int CPlayerDestructionDispenser { 0 }; + int CTFMinigameLogic { 0 }; + int CTFHalloweenMinigame_FallingPlatforms { 0 }; + int CTFHalloweenMinigame { 0 }; + int CTFMiniGame { 0 }; + int CTFWearableVM { 0 }; + int CTFWearable { 0 }; + int CTFPowerupBottle { 0 }; + int CTFItem { 0 }; + int CHalloweenSoulPack { 0 }; + int CTFGenericBomb { 0 }; + int CBonusRoundLogic { 0 }; + int CTFGameRulesProxy { 0 }; + int CTFDroppedWeapon { 0 }; + int CTFProjectile_SpellKartBats { 0 }; + int CTFProjectile_SpellKartOrb { 0 }; + int CTFHellZap { 0 }; + int CTFProjectile_SpellLightningOrb { 0 }; + int CTFProjectile_SpellTransposeTeleport { 0 }; + int CTFProjectile_SpellMeteorShower { 0 }; + int CTFProjectile_SpellSpawnBoss { 0 }; + int CTFProjectile_SpellMirv { 0 }; + int CTFProjectile_SpellPumpkin { 0 }; + int CTFProjectile_SpellSpawnHorde { 0 }; + int CTFProjectile_SpellSpawnZombie { 0 }; + int CTFProjectile_SpellBats { 0 }; + int CTFProjectile_SpellFireball { 0 }; + int CTFSpellBook { 0 }; + int CHightower_TeleportVortex { 0 }; + int CTeleportVortex { 0 }; + int CHalloweenGiftPickup { 0 }; + int CBonusDuckPickup { 0 }; + int CHalloweenPickup { 0 }; + int CCaptureFlagReturnIcon { 0 }; + int CCaptureFlag { 0 }; + int CBonusPack { 0 }; + int CHandleTest { 0 }; + int CTeamRoundTimer { 0 }; + int CTeamplayRoundBasedRulesProxy { 0 }; + int CSpriteTrail { 0 }; + int CSpriteOriented { 0 }; + int CSprite { 0 }; + int CPoseController { 0 }; + int CGameRulesProxy { 0 }; + int CInfoLadderDismount { 0 }; + int CFuncLadder { 0 }; + int CEnvDetailController { 0 }; + int CTFWearableItem { 0 }; + int CEconWearable { 0 }; + int CBaseAttributableItem { 0 }; + int CEconEntity { 0 }; + int CBeam { 0 }; + int CBaseViewModel { 0 }; + int CBaseProjectile { 0 }; + int CBaseParticleEntity { 0 }; + int CBaseGrenade { 0 }; + int CBaseCombatWeapon { 0 }; + int CVoteController { 0 }; + int CTEHL2MPFireBullets { 0 }; + int CHL2MPRagdoll { 0 }; + int CHL2MP_Player { 0 }; + int CWeaponCitizenSuitcase { 0 }; + int CWeaponCitizenPackage { 0 }; + int CWeaponAlyxGun { 0 }; + int CWeaponCubemap { 0 }; + int CWeaponGaussGun { 0 }; + int CWeaponAnnabelle { 0 }; + int CFlaregun { 0 }; + int CWeaponBugBait { 0 }; + int CWeaponBinoculars { 0 }; + int CWeaponCycler { 0 }; + int CCrossbowBolt { 0 }; + int CPropVehiclePrisonerPod { 0 }; + int CPropCrane { 0 }; + int CPropCannon { 0 }; + int CPropAirboat { 0 }; + int CFlare { 0 }; + int CTEConcussiveExplosion { 0 }; + int CNPC_Strider { 0 }; + int CScriptIntro { 0 }; + int CRotorWashEmitter { 0 }; + int CPropCombineBall { 0 }; + int CPlasmaBeamNode { 0 }; + int CNPC_RollerMine { 0 }; + int CNPC_Manhack { 0 }; + int CNPC_CombineGunship { 0 }; + int CNPC_AntlionGuard { 0 }; + int CInfoTeleporterCountdown { 0 }; + int CMortarShell { 0 }; + int CEnvStarfield { 0 }; + int CEnvHeadcrabCanister { 0 }; + int CAlyxEmpEffect { 0 }; + int CCorpse { 0 }; + int CCitadelEnergyCore { 0 }; + int CHL2_Player { 0 }; + int CBaseHLBludgeonWeapon { 0 }; + int CHLSelectFireMachineGun { 0 }; + int CHLMachineGun { 0 }; + int CBaseHelicopter { 0 }; + int CNPC_Barney { 0 }; + int CNPC_Barnacle { 0 }; + int AR2Explosion { 0 }; + int CTEAntlionDust { 0 }; + int CVortigauntEffectDispel { 0 }; + int CVortigauntChargeToken { 0 }; + int CNPC_Vortigaunt { 0 }; + int CPredictedViewModel { 0 }; + int CWeaponStunStick { 0 }; + int CWeaponSMG1 { 0 }; + int CWeapon_SLAM { 0 }; + int CWeaponShotgun { 0 }; + int CWeaponRPG { 0 }; + int CWeaponPistol { 0 }; + int CWeaponPhysCannon { 0 }; + int CHL2MPMachineGun { 0 }; + int CBaseHL2MPCombatWeapon { 0 }; + int CBaseHL2MPBludgeonWeapon { 0 }; + int CWeaponHL2MPBase { 0 }; + int CWeaponFrag { 0 }; + int CWeaponCrowbar { 0 }; + int CWeaponCrossbow { 0 }; + int CWeaponAR2 { 0 }; + int CWeapon357 { 0 }; + int CHL2MPGameRulesProxy { 0 }; + int CHalfLife2Proxy { 0 }; + int CBaseHLCombatWeapon { 0 }; + int CTFVehicle { 0 }; + int CTFBaseDMPowerup { 0 }; + int CWeaponSpawner { 0 }; + int CTFUmbrella { 0 }; + int CTFTranq { 0 }; + int CTFSMG_Primary { 0 }; + int CTFRevolver_Secondary { 0 }; + int CTFNailgun { 0 }; + int CTFHunterRifle { 0 }; + int CTFHeavyArtillery { 0 }; + int CTFHammerfists { 0 }; + int CTFCrowbar { 0 }; + int CTFChainsaw { 0 }; + int CTEPlantBomb { 0 }; + int CTERadioIcon { 0 }; + int CPlantedC4 { 0 }; + int CCSTeam { 0 }; + int CCSPlayerResource { 0 }; + int CCSPlayer { 0 }; + int CCSRagdoll { 0 }; + int CHostage { 0 }; + int CWeaponXM1014 { 0 }; + int CWeaponUSP { 0 }; + int CWeaponUMP45 { 0 }; + int CWeaponTMP { 0 }; + int CSmokeGrenade { 0 }; + int CWeaponSG552 { 0 }; + int CWeaponSG550 { 0 }; + int CWeaponScout { 0 }; + int CWeaponP90 { 0 }; + int CWeaponP228 { 0 }; + int CWeaponMP5Navy { 0 }; + int CWeaponMAC10 { 0 }; + int CWeaponM4A1 { 0 }; + int CWeaponM3 { 0 }; + int CWeaponM249 { 0 }; + int CKnife { 0 }; + int CHEGrenade { 0 }; + int CWeaponGlock { 0 }; + int CWeaponGalil { 0 }; + int CWeaponG3SG1 { 0 }; + int CFlashbang { 0 }; + int CWeaponFiveSeven { 0 }; + int CWeaponFamas { 0 }; + int CWeaponElite { 0 }; + int CDEagle { 0 }; + int CWeaponCSBaseGun { 0 }; + int CWeaponCSBase { 0 }; + int CC4 { 0 }; + int CBaseCSGrenade { 0 }; + int CWeaponAWP { 0 }; + int CWeaponAug { 0 }; + int CAK47 { 0 }; + int CFootstepControl { 0 }; + int CCSGameRulesProxy { 0 }; + int CBaseCSGrenadeProjectile { 0 }; + int CSDKTeam_Deathmatch { 0 }; + int CSDKTeam_Red { 0 }; + int CSDKTeam_Blue { 0 }; + int CSDKTeam_Unassigned { 0 }; + int CSDKTeam { 0 }; + int CSDKPlayerResource { 0 }; + int CSDKRagdoll { 0 }; + int CSDKPlayer { 0 }; + int CSparkler { 0 }; + int CRatRaceWaypoint { 0 }; + int CBriefcaseCaptureZone { 0 }; + int CBriefcase { 0 }; + int CWeaponSDKBase { 0 }; + int CWeaponMP5K { 0 }; + int CWeaponMossberg { 0 }; + int CWeaponM1911 { 0 }; + int CWeaponM16 { 0 }; + int CWeaponGrenade { 0 }; + int CWeaponFAL { 0 }; + int CWeaponBrawl { 0 }; + int CWeaponBeretta { 0 }; + int CBaseSDKGrenade { 0 }; + int CAkimboM1911 { 0 }; + int CAkimboBeretta { 0 }; + int CAkimboBase { 0 }; + int CWeaponSDKMelee { 0 }; + int CSDKGameRulesProxy { 0 }; + int CBaseGrenadeProjectile { 0 }; + int CDAViewModel { 0 }; + + }; + + extern dynamic dynamic_list; +} + +#endif /* DYNAMIC_AUTOGEN_HPP */ \ No newline at end of file diff --git a/src/colors.cpp b/src/colors.cpp new file mode 100644 index 00000000..89e93acc --- /dev/null +++ b/src/colors.cpp @@ -0,0 +1,76 @@ +/* + * colors.cpp + * + * Created on: May 22, 2017 + * Author: nullifiedcat + */ + +#include "common.h" + +rgba_t colors::EntityF(CachedEntity* ent) { + rgba_t result, plclr; + int skin; + k_EItemType type; + + using namespace colors; + result = white; + type = ent->m_ItemType; + if (type) { + if ((type >= ITEM_HEALTH_SMALL && type <= ITEM_HEALTH_LARGE) || type == ITEM_TF2C_PILL) result = green; + else if (type >= ITEM_POWERUP_FIRST && type <= ITEM_POWERUP_LAST) { + skin = RAW_ENT(ent)->GetSkin(); + if (skin == 1) result = red; + else if (skin == 2) result = blu; + else result = yellow; + } + else if (type >= ITEM_TF2C_W_FIRST && type <= ITEM_TF2C_W_LAST) { + if (CE_BYTE(ent, netvar.bRespawning)) { + result = red; + } else { + result = yellow; + } + } + else if (type == ITEM_HL_BATTERY) { + result = yellow; + } + } + + if (ent->m_iClassID == CL_CLASS(CCurrencyPack)) { + if (CE_BYTE(ent, netvar.bDistributed)) + result = red; + else + result = green; + } + + if (ent->m_Type == ENTITY_PROJECTILE) { + if (ent->m_iTeam == TEAM_BLU) result = blu; + else if (ent->m_iTeam == TEAM_RED) result = red; + if (ent->m_bCritProjectile) { + if (ent->m_iTeam == TEAM_BLU) result = blu_u; + else if (ent->m_iTeam == TEAM_RED) result = red_u; + } + } + + if (ent->m_Type == ENTITY_PLAYER || ent->m_Type == ENTITY_BUILDING) { + if (ent->m_iTeam == TEAM_BLU) result = blu; + else if (ent->m_iTeam == TEAM_RED) result = red; + if (ent->m_Type == ENTITY_PLAYER) { + if (IsPlayerInvulnerable(ent)) { + if (ent->m_iTeam == TEAM_BLU) result = blu_u; + else if (ent->m_iTeam == TEAM_RED) result = red_u; + } + if (HasCondition(ent)) { + if (ent->m_iTeam == TEAM_BLU) result = blu_v; + else if (ent->m_iTeam == TEAM_RED) result = red_v; + } + plclr = playerlist::Color(ent); + if (plclr.a) result = plclr; + } + } + + return result; +} + +rgba_t colors::RainbowCurrent() { + return colors::FromHSL(fabs(sin(g_GlobalVars->curtime / 2.0f)) * 360.0f, 0.85f, 0.9f); +} diff --git a/src/colors.hpp b/src/colors.hpp new file mode 100644 index 00000000..5bf6a50b --- /dev/null +++ b/src/colors.hpp @@ -0,0 +1,130 @@ +/* + * colors.hpp + * + * Created on: May 22, 2017 + * Author: nullifiedcat + */ + +#ifndef COLORS_HPP_ +#define COLORS_HPP_ + +class CachedEntity; + +namespace colors { + +namespace chat { + +constexpr unsigned red = 0xB8383B; +constexpr unsigned blu = 0x5885A2; + +constexpr unsigned white = 0xE6E6E6; +constexpr unsigned purple = 0x7D4071; +constexpr unsigned yellowish = 0xF0E68C; +constexpr unsigned orange = 0xCF7336; + +constexpr unsigned team(int team) { + if (team == 2) return red; + if (team == 3) return blu; + return white; +} + +} + +struct rgba_t { + union { + struct { + float r, g, b, a; + }; + float rgba[4]; + }; + + constexpr rgba_t() : r(0.0f), g(0.0f), b(0.0f), a(0.0f) {}; + constexpr rgba_t(float _r, float _g, float _b, float _a = 1.0f) : r(_r), g(_g), b(_b), a(_a) {}; + + constexpr operator bool() const { + return r || g || b || a; + } + + constexpr operator int() const = delete; + + operator float*() { + return rgba; + } + + constexpr operator const float*() const { + return rgba; + } + + constexpr rgba_t operator*(float value) const { + return rgba_t(r * value, g * value, b * value, a * value); + } + +}; + +constexpr rgba_t FromRGBA8(float r, float g, float b, float a) { + return rgba_t { r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }; +} + +constexpr rgba_t Transparent(const rgba_t& in, float multiplier = 0.5f) { + return rgba_t { in.r, in.g, in.b, in.a * multiplier }; +} + +constexpr rgba_t white = FromRGBA8(255, 255, 255, 255); +constexpr rgba_t black(0, 0, 0, 1); + +constexpr rgba_t pink = FromRGBA8(255, 105, 180, 255); + +constexpr rgba_t red = FromRGBA8(237, 42, 42, 255), blu = FromRGBA8(28, 108, 237, 255); +constexpr rgba_t red_b = FromRGBA8(64, 32, 32, 178), blu_b = FromRGBA8(32, 32, 64, 178); // Background +constexpr rgba_t red_v = FromRGBA8(196, 102, 108, 255), blu_v = FromRGBA8(102, 182, 196, 255); // Vaccinator +constexpr rgba_t red_u = FromRGBA8(216, 34, 186, 255), blu_u = FromRGBA8(167, 75, 252, 255); // Ubercharged +constexpr rgba_t yellow = FromRGBA8(255, 255, 0, 255); +constexpr rgba_t orange = FromRGBA8(255, 120, 0, 255); +constexpr rgba_t green = FromRGBA8(0, 255, 0, 255); +constexpr rgba_t empty = FromRGBA8(0, 0, 0, 0); + +constexpr rgba_t FromHSL(float h, float s, float v) { + if(s <= 0.0) { // < is bogus, just shuts up warnings + return rgba_t { v, v, v, 1.0f }; + } + float hh = h; + if(hh >= 360.0) hh = 0.0; + hh /= 60.0; + long i = long(hh); + float ff = hh - i; + float p = v * (1.0 - s); + float q = v * (1.0 - (s * ff)); + float t = v * (1.0 - (s * (1.0 - ff))); + + switch(i) { + case 0: + return rgba_t { v, t, p, 1.0f }; + case 1: + return rgba_t { q, v, p, 1.0f }; + case 2: + return rgba_t { p, v, t, 1.0f }; + case 3: + return rgba_t { p, q, v, 1.0f }; + break; + case 4: + return rgba_t { t, p, v, 1.0f }; + case 5: + default: + return rgba_t { v, p, q, 1.0f }; + } +} +constexpr rgba_t Health(int health, int max) { + float hf = float(health) / float(max); + if (hf > 1) { + return colors::FromRGBA8(64, 128, 255, 255); + } + return rgba_t { (hf <= 0.5f ? 1.0f : 1.0f - 2.0f * (hf - 0.5f)), (hf <= 0.5f ? (2.0f * hf) : 1.0f), 0.0f, 1.0f }; +} +rgba_t RainbowCurrent(); +rgba_t EntityF(CachedEntity* ent); + +} + +using rgba_t = colors::rgba_t; + +#endif /* COLORS_HPP_ */ diff --git a/src/common.h b/src/common.h index 4b008d2c..e739c8d9 100644 --- a/src/common.h +++ b/src/common.h @@ -8,10 +8,7 @@ #ifndef COMMON_H_ #define COMMON_H_ -#include - - -#ifdef LINUX +#if defined(LINUX) and not defined(NO_IPC) #define IPC_ENABLED 1 #else #undef IPC_ENABLED @@ -29,28 +26,57 @@ #include #include #include +#include #include #include #include #include #include #include + +#include "timer.hpp" +#include "averager.hpp" + #include "aftercheaders.h" + +#include "macros.hpp" +#include "colors.hpp" + +#ifndef TEXTMODE + +extern "C" { +#include +} + +#include "ftrender.hpp" +#include "drawing.h" +#include "fidgetspinner.hpp" +#include "drawgl.hpp" +#include "EffectGlow.hpp" +#include "atlas.hpp" +#include "EffectChams.hpp" +#include "drawmgr.hpp" + +#endif + #include "profiler.h" #include "offsets.hpp" -#include "drawing.h" -#include "resource.hpp" #include "entitycache.h" #include "hoovy.hpp" #include "enums.h" +#include "projlogging.hpp" +#include "ucccccp_cmds.hpp" +#include "velocity.hpp" +#include "angles.hpp" +#include "entityhitboxcache.hpp" #include "globals.h" #include "helpers.h" #include "playerlist.hpp" #include "interfaces.h" -#include "EffectGlow.hpp" #include "localplayer.h" #include "conditions.h" #include "logging.h" +#include "targethelper.h" #include "playerresource.h" #include "usercmd.h" #include "trace.h" @@ -63,18 +89,18 @@ #include "itemtypes.h" #include "chatstack.h" #include "textfile.h" -#include "EffectChams.hpp" #include "ipc.h" #include "hooks/hookedmethods.h" #include "classinfo/classinfo.hpp" #include "crits.h" +#include "textmode.hpp" +#include "backpacktf.hpp" -#if NOGUI != 1 +#if ENABLE_GUI #include "gui/GUI.h" #endif #include "hacks/hacklist.h" -#include "glowobjects.h" #include "sdk.h" @@ -88,7 +114,7 @@ constexpr T _clamp(T _min, T _max, T _val) { #include "gameinfo.hpp" -#define SQR(x) x * x +#define SQR(x) (x) * (x) #ifndef CATHOOK_BUILD_NUMBER #define CATHOOK_BUILD_NUMBER "LATEST" @@ -109,11 +135,7 @@ constexpr T _clamp(T _min, T _max, T _val) { #define DEG2RAD(x) (float)(x) * (PI / 180.0f) #endif -#if _DEVELOPER == true || __DRM_ENABLED == false #define DEBUG_SEGV false -#else -#define DEBUG_SEGV false -#endif #define STR(c) #c #if DEBUG_SEGV == true diff --git a/src/conditions.h b/src/conditions.h index b3411d8f..2717407a 100644 --- a/src/conditions.h +++ b/src/conditions.h @@ -22,7 +22,7 @@ struct condition_data_s { uint32_t cond_3; }; -enum condition { +enum condition : unsigned { TFCond_Slowed = 0, TFCond_Zoomed, TFCond_Disguising, @@ -157,16 +157,16 @@ constexpr condition_data_s CreateConditionMask(ConditionList... conds) { c3 = 0; for (const auto& cond : { conds... }) { if (cond >= 32 * 3) { - c3 |= (1 << (cond % 32)); + c3 |= (1u << (cond % 32)); } if (cond >= 32 * 2) { - c2 |= (1 << (cond % 32)); + c2 |= (1u << (cond % 32)); } if (cond >= 32 * 1) { - c1 |= (1 << (cond % 32)); + c1 |= (1u << (cond % 32)); } else { - c0 |= (1 << (cond)); + c0 |= (1u << (cond)); } } return condition_data_s { c0, c1, c2, c3 }; @@ -194,15 +194,18 @@ constexpr condition_data_s KCritBoostMask = CreateConditionMask( template inline bool CondBitCheck(condition_data_s& data) { if (cond >= 32 * 3) { - return data.cond_3 & (1 << (cond % 32)); + return data.cond_3 & (1u << (cond % 32)); } if (cond >= 32 * 2) { - return data.cond_2 & (1 << (cond % 32)); + return data.cond_2 & (1u << (cond % 32)); } if (cond >= 32 * 1) { - return data.cond_1 & (1 << (cond % 32)); + return data.cond_1 & (1u << (cond % 32)); } - return data.cond_0 & (1 << (cond)); + if (cond < 32) { + return data.cond_0 & (1u << (cond)); + } + return false; } // I haven't figured out how to pass a struct as a parameter, sorry. @@ -238,13 +241,13 @@ inline void CondBitSet(condition_data_s& data) { } } else { if (cond > 32 * 3) { - data.cond_3 &= ~(1 << (cond % 32)); + data.cond_3 &= ~(1u << (cond % 32)); } else if (cond > 32 * 2) { - data.cond_2 &= ~(1 << (cond % 32)); + data.cond_2 &= ~(1u << (cond % 32)); } else if (cond > 32 * 1) { - data.cond_1 &= ~(1 << (cond % 32)); + data.cond_1 &= ~(1u << (cond % 32)); } else { - data.cond_0 &= ~(1 << (cond)); + data.cond_0 &= ~(1u << (cond)); } } } @@ -252,7 +255,7 @@ inline void CondBitSet(condition_data_s& data) { template inline bool HasCondition(CachedEntity* ent) { IF_GAME (!IsTF()) return false; - IF_GAME (IsTF2()) { + IF_GAME (IsTF2() && cond < condition(96)) { if (CondBitCheck(CE_VAR(ent, netvar._condition_bits, condition_data_s))) return true; } return CondBitCheck(CE_VAR(ent, netvar.iCond, condition_data_s)); diff --git a/src/copypasted/CSignature.cpp b/src/copypasted/CSignature.cpp index ca5535e6..633150da 100644 --- a/src/copypasted/CSignature.cpp +++ b/src/copypasted/CSignature.cpp @@ -26,7 +26,7 @@ Elf32_Shdr *getSectionHeader(void *module, const char *sectionName) // we need to get the modules actual address from the handle Elf32_Ehdr *ehdr = (Elf32_Ehdr *)module; - Elf32_Shdr *shdr = (Elf32_Shdr *)(module + ehdr->e_shoff); + Elf32_Shdr *shdr = (Elf32_Shdr *)((unsigned)module + ehdr->e_shoff); int shNum = ehdr->e_shnum; Elf32_Shdr *strhdr = &shdr[ehdr->e_shstrndx]; @@ -35,7 +35,7 @@ Elf32_Shdr *getSectionHeader(void *module, const char *sectionName) int strtabSize = 0; if(strhdr != NULL && strhdr->sh_type == 3) { - strtab = (char *)(module + strhdr->sh_offset); + strtab = (char *)((unsigned)module + strhdr->sh_offset); if(strtab == NULL) //Log::Fatal("String table was NULL!"); @@ -99,9 +99,9 @@ uintptr_t CSignature::GetClientSignature(char* chPattern) { // we need to do this becuase (i assume that) under the hood, dlopen only loads up the sections that it needs // into memory, meaning that we cannot get the string table from the module. - static int fd = open(sharedobj::client->path, O_RDONLY); + static int fd = open(sharedobj::client().path.c_str(), O_RDONLY); static void *module = mmap(NULL, lseek(fd, 0, SEEK_END), PROT_READ, MAP_SHARED, fd, 0); - static link_map *moduleMap = sharedobj::client->lmap; + static link_map *moduleMap = sharedobj::client().lmap; //static void *module = (void *)moduleMap->l_addr; @@ -120,9 +120,9 @@ uintptr_t CSignature::GetEngineSignature(char* chPattern) { // we need to do this becuase (i assume that) under the hood, dlopen only loads up the sections that it needs // into memory, meaning that we cannot get the string table from the module. - static int fd = open(sharedobj::engine->path, O_RDONLY); + static int fd = open(sharedobj::engine().path.c_str(), O_RDONLY); static void *module = mmap(NULL, lseek(fd, 0, SEEK_END), PROT_READ, MAP_SHARED, fd, 0); - static link_map *moduleMap = sharedobj::engine->lmap; + static link_map *moduleMap = sharedobj::engine().lmap; //static void *module = (void *)moduleMap->l_addr; diff --git a/src/crits.cpp b/src/crits.cpp index 80db83db..7778a24b 100644 --- a/src/crits.cpp +++ b/src/crits.cpp @@ -49,8 +49,9 @@ bool weapon_can_crit_last = false; bool WeaponCanCrit() { IF_GAME (!IsTF()) return false; + if (CE_BAD(LOCAL_W)) return false; IClientEntity* weapon = RAW_ENT(LOCAL_W); - weapon_can_crit_last = CE_GOOD(LOCAL_W) && vfunc(weapon, 190, 0)(weapon) && vfunc(weapon, 465 + 21, 0)(weapon); + weapon_can_crit_last = vfunc(weapon, 190, 0)(weapon) && vfunc(weapon, 465 + 21, 0)(weapon); return weapon_can_crit_last; } @@ -114,12 +115,6 @@ bool IsAttackACrit(CUserCmd* cmd) { } } else if (TF2) */ { - if (!g_PredictionRandomSeed) { - uintptr_t sig = gSignatures.GetClientSignature("89 1C 24 D9 5D D4 FF 90 3C 01 00 00 89 C7 8B 06 89 34 24 C1 E7 08 FF 90 3C 01 00 00 09 C7 33 3D ? ? ? ? 39 BB 34 0B 00 00 74 0E 89 BB 34 0B 00 00 89 3C 24 E8 ? ? ? ? C7 44 24 04 0F 27 00 00"); - logging::Info("Random Seed: 0x%08x", sig + 32); - logging::Info("Random Seed: 0x%08x", *(int**)(sig + 32)); - g_PredictionRandomSeed = *reinterpret_cast(sig + (uintptr_t)32); - } if (vfunc(weapon, 1944 / 4, 0)(weapon)) { static uintptr_t CalcIsAttackCritical_s = gSignatures.GetClientSignature("55 89 E5 83 EC 28 89 5D F4 8B 5D 08 89 75 F8 89 7D FC 89 1C 24 E8 ? ? ? ? 85 C0 89 C6 74 60 8B 00 89 34 24 FF 90 E0 02 00 00 84 C0 74 51 A1 ? ? ? ? 8B 40 04"); typedef void(*CalcIsAttackCritical_t)(IClientEntity*); diff --git a/src/cvwrapper.cpp b/src/cvwrapper.cpp index becb83c7..b70cd9f9 100644 --- a/src/cvwrapper.cpp +++ b/src/cvwrapper.cpp @@ -10,6 +10,76 @@ #include "common.h" #include "sdk.h" +int CatVar::last_id { 0 }; + +int rebased_count { 0 }; + +int GetRebasedCatVarCount() { + return rebased_count; +} + +static CatCommand cfg_rebase("cfg_setbase", "Rebase config", []() { + for (auto& cv : CatVarList()) { + std::string value(cv->GetString()); + if (value != cv->defaults) { + cv->current_base = value; + rebased_count++; + } + } + logging::Info("Successfully rebased %d variables", rebased_count); +}); + +static CatCommand cfg_resetbase("cfg_resetbase", "Reset config base", []() { + for (auto& cv : CatVarList()) { + cv->current_base = cv->defaults; + } + rebased_count = 0; +}); + +static CatCommand save_settings("save", "Save settings (optional filename)", [](const CCommand& args) { + std::string filename("lastcfg"); + if (args.ArgC() > 1) { + filename = std::string(args.Arg(1)); + } + std::string path = format("tf/cfg/cat_", filename, ".cfg"); + logging::Info("Saving settings to %s", path.c_str()); + if (GetRebasedCatVarCount()) { + logging::Info("[Warning] %d CatVars are rebased!", GetRebasedCatVarCount()); + } + std::ofstream file(path, std::ios::out); + if (file.bad()) { + logging::Info("Couldn't open the file!"); + return; + } + for (const auto& i : CatVarList()) { + if (i->GetBase() != std::string(i->GetString())) { + file << CON_PREFIX << i->name << " \"" << i->GetString() << "\"\n"; + } + } + file.close(); +}); + +static CatCommand save_settings_complete("save_complete", "Save all settings (optional filename)", [](const CCommand& args) { + std::string filename("lastcfg"); + if (args.ArgC() > 1) { + filename = std::string(args.Arg(1)); + } + std::string path = format("tf/cfg/cat_", filename, ".cfg"); + logging::Info("Saving settings to %s", path.c_str()); + if (GetRebasedCatVarCount()) { + logging::Info("[Warning] %d CatVars are rebased!", GetRebasedCatVarCount()); + } + std::ofstream file(path, std::ios::out); + if (file.bad()) { + logging::Info("Couldn't open the file!"); + return; + } + for (const auto& i : CatVarList()) { + file << CON_PREFIX << i->name << " \"" << i->GetString() << "\"\n"; + } + file.close(); +}); + // Prevent initialization errors. std::vector& registrationArray() { static std::vector vector; @@ -22,13 +92,13 @@ std::vector& commandRegistrationArray() { } -CatCommand::CatCommand(std::string name, std::string help, FnCommandCallback_t callback) - : name(name), help(help), callback(callback) { +CatCommand::CatCommand(std::string _name, std::string _help, FnCommandCallback_t _callback) + : name(_name), help(_help), callback(_callback) { commandRegistrationArray().push_back(this); } -CatCommand::CatCommand(std::string name, std::string help, FnCommandCallbackVoid_t callback) - : name(name), help(help), callback_void(callback) { +CatCommand::CatCommand(std::string _name, std::string _help, FnCommandCallbackVoid_t _callback) + : name(_name), help(_help), callback_void(_callback) { commandRegistrationArray().push_back(this); } @@ -45,6 +115,7 @@ void CatCommand::Register() { else if (callback_void) cmd = new ConCommand(name_c, callback_void, help_c); else throw std::logic_error("no callback in CatCommand"); g_ICvar->RegisterConCommand(cmd); + RegisteredCommandsList().push_back(cmd); // name_c and help_c are not freed because ConCommandBase doesn't copy them } @@ -56,31 +127,28 @@ void RegisterCatCommands() { } } -CatVar::CatVar(CatVar_t type, std::string name, std::string defaults, std::string desc_short, std::string desc_long) - : type(type), name(name), defaults(defaults), desc_short(desc_short), desc_long(desc_long), enum_type(nullptr), restricted(false), callbacks{} { - min = 0.0f; - max = 0.0f; +CatVar::CatVar(CatVar_t _type, std::string _name, std::string _defaults, std::string _desc_short, std::string _desc_long) + : type(_type), name(_name), defaults(_defaults), desc_short(_desc_short), desc_long(_desc_long) { registrationArray().push_back(this); } -CatVar::CatVar(CatVar_t type, std::string name, std::string defaults, std::string desc_short, std::string desc_long, float max_val) - : type(type), name(name), defaults(defaults), desc_short(desc_short), desc_long(desc_long), enum_type(nullptr), restricted(true), callbacks{} { - min = 0.0f; +CatVar::CatVar(CatVar_t _type, std::string _name, std::string _defaults, std::string _desc_short, std::string _desc_long, float max_val) + : type(_type), name(_name), defaults(_defaults), desc_short(_desc_short), desc_long(_desc_long), restricted(true) { max = max_val; registrationArray().push_back(this); } -CatVar::CatVar(CatVar_t type, std::string name, std::string defaults, std::string desc_short, std::string desc_long, float min_val, float max_val) - : type(type), name(name), defaults(defaults), desc_short(desc_short), desc_long(desc_long), enum_type(nullptr), restricted(true), callbacks{} { +CatVar::CatVar(CatVar_t _type, std::string _name, std::string _defaults, std::string _desc_short, std::string _desc_long, float min_val, float max_val) + : type(_type), name(_name), defaults(_defaults), desc_short(_desc_short), desc_long(_desc_long), restricted(true) { min = min_val; max = max_val; registrationArray().push_back(this); } -CatVar::CatVar(CatEnum& cat_enum, std::string name, std::string defaults, std::string desc_short, std::string desc_long) - : type(CV_ENUM), name(name), defaults(defaults), desc_short(desc_short), desc_long(desc_long), enum_type(&cat_enum), restricted(true), callbacks{} { - min = cat_enum.Minimum(); - max = cat_enum.Maximum(); +CatVar::CatVar(CatEnum& cat_enum, std::string _name, std::string _defaults, std::string _desc_short, std::string _desc_long) + : type(CV_ENUM), name(_name), defaults(_defaults), desc_short(_desc_short), desc_long(_desc_long), enum_type(&cat_enum), restricted(true) { + min = cat_enum.min_value; + max = cat_enum.max_value; registrationArray().push_back(this); } @@ -91,8 +159,10 @@ void CatVar::OnRegister(CatVar::RegisterCallbackFn fn) { void CatVar::Register() { CatVarList().push_back(this); + id = last_id++; convar = CreateConVar(CON_PREFIX + name, defaults, desc_short); convar_parent = convar->m_pParent; + current_base = defaults; while (!callbacks.empty()) { callbacks.back()(this); callbacks.pop_back(); @@ -114,27 +184,19 @@ void RegisterCatVars() { } } -CatEnum::CatEnum(std::vector values, int min) : m_values(values) { - m_iMin = min; - m_iMax = min + values.size() - 1; - m_iLength = values.size(); +CatEnum::CatEnum(std::vector values, int min) : value_names(values) { + min_value = min; + max_value = min + int(values.size()) - 1; + size = int(values.size()); } std::string CatEnum::Name(int value) { - if (value - m_iMin >= 0 && value - m_iMin <= m_iMax) { - return m_values.at(value - Minimum()); + if (value >= min_value && value < max_value) { + return value_names.at(unsigned(value) - unsigned(min_value)); } return "unknown"; } -int CatEnum::Maximum() const { - return m_iMax; -} - -int CatEnum::Minimum() const { - return m_iMin; -} - std::vector& CatVarList() { static std::vector object {}; return object; diff --git a/src/cvwrapper.h b/src/cvwrapper.h index 093c833d..aa0602d3 100644 --- a/src/cvwrapper.h +++ b/src/cvwrapper.h @@ -19,13 +19,6 @@ class ConVar; #include #include "aftercheaders.h" - -//#define CREATE_CV(type, name, defaults, description) \ -// new CatVar(CreateConVar(CON_PREFIX name, defaults, description), type); - -//#define CREATE_CV_DESC(type, name, defaults, description, detailed) \ -// new CatVar(CreateConVar(CON_PREFIX name, defaults, description), type, detailed); - enum CatVar_t { CV_SWITCH, CV_INT, @@ -39,12 +32,11 @@ class CatEnum { public: CatEnum(std::vector values, int min = 0); std::string Name(int value); - int Maximum() const ; - int Minimum() const ; - const std::vector m_values; - int m_iMin; - int m_iMax; - int m_iLength; +public: + const std::vector value_names; + int min_value; + int max_value; + int size; }; class CatCommand { @@ -53,14 +45,14 @@ public: CatCommand(std::string name, std::string help, FnCommandCallbackVoid_t callback); void Register(); - +public: const std::string name; - const std::string help; - - ConCommand* cmd { nullptr }; + const std::string help { "" }; FnCommandCallback_t callback { nullptr }; FnCommandCallbackVoid_t callback_void { nullptr }; + + ConCommand* cmd { nullptr }; }; void RegisterCatCommands(); @@ -82,7 +74,6 @@ public: void Register(); typedef std::function RegisterCallbackFn; - std::vector callbacks {}; void OnRegister(RegisterCallbackFn fn); void InstallChangeCallback(FnChangeCallback_t callback); @@ -100,25 +91,42 @@ public: inline void SetValue(int value) { this->operator =(value); } inline bool KeyDown() { - return g_IInputSystem->IsButtonDown((ButtonCode_t)((int)*this)); + return g_IInputSystem->IsButtonDown(static_cast(static_cast(*this))); } - bool restricted; - float max; - float min; - bool registered {false}; + inline const std::string& GetBase() const { + return current_base; + } +public: const CatVar_t type; const std::string name; - const std::string defaults; - const std::string desc_short; - const std::string desc_long; - CatEnum* enum_type; - ConVar* convar; - ConVar* convar_parent; + const std::string defaults { "0" }; + const std::string desc_short { "" }; + const std::string desc_long { "" }; + const CatEnum* const enum_type { nullptr }; + + std::string current_base { "0" }; + + bool restricted { false }; + float min { 0.0f }; + float max { 0.0f }; + + std::vector callbacks {}; + bool registered { false }; + + ConVar* convar { nullptr }; + ConVar* convar_parent { nullptr }; + + int id { 0 }; + static int last_id; }; +std::vector& registrationArray(); +std::vector& commandRegistrationArray(); + std::vector& CatVarList(); void RegisterCatVars(); +int GetRebasedCatVarCount(); #endif /* CVWRAPPER_H_ */ diff --git a/src/drawgl.cpp b/src/drawgl.cpp new file mode 100644 index 00000000..807122a8 --- /dev/null +++ b/src/drawgl.cpp @@ -0,0 +1,177 @@ +/* + * drawgl.cpp + * + * Created on: May 21, 2017 + * Author: nullifiedcat + */ + +#include "drawgl.hpp" +#include "common.h" +#include "atlas.hpp" + +extern "C" { +#include +#include +#include +} + +namespace drawgl { + +using namespace ftgl; + +const float white[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + +vertex_buffer_t* buffer_lines; +vertex_buffer_t* buffer_triangles_plain; +vertex_buffer_t* buffer_triangles_textured; + +GLuint shader_v2fc4f; +GLuint shader_v2ft2fc4f; + +mat4 model, view, projection; + +bool ready_state = false; + +void Initialize() { + buffer_lines = vertex_buffer_new("vertex:2f,color:4f"); + buffer_triangles_plain = vertex_buffer_new("vertex:2f,color:4f"); + buffer_triangles_textured = vertex_buffer_new("vertex:2f,tex_coord:2f,color:4f"); + + mat4_set_identity(&projection); + mat4_set_identity(&view); + mat4_set_identity(&model); + mat4_set_orthographic(&projection, 0, draw::width, draw::height, 0, -1, 1); + //view.m11 = -1; + + shader_v2fc4f = shader_load("cathook/shaders/v2f-c4f.vert", "cathook/shaders/v2f-c4f.frag"); + glUseProgram(shader_v2fc4f); + { + glUniformMatrix4fv(glGetUniformLocation(shader_v2fc4f, "model"), 1, 0, model.data); + glUniformMatrix4fv(glGetUniformLocation(shader_v2fc4f, "view"), 1, 0, view.data); + glUniformMatrix4fv(glGetUniformLocation(shader_v2fc4f, "projection"), 1, 0, projection.data); + } + + shader_v2ft2fc4f = shader_load("cathook/shaders/v2f-t2f-c4f.vert", "cathook/shaders/v2f-t2f-c4f.frag"); + glUseProgram(shader_v2ft2fc4f); + { + glUniform1i(glGetUniformLocation(shader_v2ft2fc4f, "texture"), 0); + glUniformMatrix4fv(glGetUniformLocation(shader_v2ft2fc4f, "model"), 1, 0, model.data); + glUniformMatrix4fv(glGetUniformLocation(shader_v2ft2fc4f, "view"), 1, 0, view.data); + glUniformMatrix4fv(glGetUniformLocation(shader_v2ft2fc4f, "projection"), 1, 0, projection.data); + } + + glUseProgram(0); + // Texture atlas + textures::Init(); + + // Do not fucking ask. Without this, it crashes. + drawgl::Rect(0, 0, 0, 0); + drawgl::FilledRect(0, 0, 0, 0); + drawgl::TexturedRect(0, 0, 0, 0, 0, 0, 0, 0); + ready_state = true; + Render(); +} + +void FilledRect(float x, float y, float w, float h, const float* rgba) { + GLuint idx = buffer_triangles_plain->vertices->size; + // + // 3 - 2 + // | / | + // 0 - 1 + // + GLuint indices[] = { idx, idx + 1, idx + 2, idx, idx + 2, idx + 3 }; + vertex_v2c4_t vertices[] = { + { vec2{ x, y }, *reinterpret_cast(rgba) }, + { vec2{ x + w, y }, *reinterpret_cast(rgba) }, + { vec2{ x + w, y + h }, *reinterpret_cast(rgba) }, + { vec2{ x, y + h }, *reinterpret_cast(rgba) } + }; + vertex_buffer_push_back_indices(buffer_triangles_plain, indices, 6); + vertex_buffer_push_back_vertices(buffer_triangles_plain, vertices, 4); +} + +void Line(float x, float y, float dx, float dy, const float* rgba) { + GLuint idx = buffer_lines->vertices->size; + GLuint indices[] = { idx, idx + 1 }; + vertex_v2c4_t vertices[] = { + { vec2{ x, y }, *reinterpret_cast(rgba) }, + { vec2{ x + dx, y + dy }, *reinterpret_cast(rgba) } + }; + vertex_buffer_push_back_indices(buffer_lines, indices, 2); + vertex_buffer_push_back_vertices(buffer_lines, vertices, 2); +} + +void Rect(float x, float y, float w, float h, const float* rgba) { + GLuint idx = buffer_lines->vertices->size; + GLuint indices[] = { idx, idx + 1, idx + 1, idx + 2, idx + 2, idx + 3, idx + 3, idx }; + vertex_v2c4_t vertices[] = { + { vec2{ x + 0.5f, y + 0.5f }, *reinterpret_cast(rgba) }, + { vec2{ x + w, y + 0.5f }, *reinterpret_cast(rgba) }, + { vec2{ x + w, y + h - 0.375f }, *reinterpret_cast(rgba) }, + { vec2{ x + 0.5f, y + h - 0.375f }, *reinterpret_cast(rgba) } + }; + vertex_buffer_push_back_indices(buffer_lines, indices, 8); + vertex_buffer_push_back_vertices(buffer_lines, vertices, 4); +} + +void TexturedRect(float x, float y, float w, float h, float u, float v, float u2, float v2, const float* rgba) { + GLuint idx = buffer_triangles_textured->vertices->size; + GLuint indices[] = { idx, idx + 1, idx + 2, idx, idx + 2, idx + 3 }; + vertex_v2t2c4_t vertices[] = { + { vec2{ x, y }, vec2{ u, v2 }, *reinterpret_cast(rgba) }, + { vec2{ x + w, y }, vec2{ u2, v2 }, *reinterpret_cast(rgba) }, + { vec2{ x + w, y + h }, vec2{ u2, v }, *reinterpret_cast(rgba) }, + { vec2{ x, y + h }, vec2{ u, v }, *reinterpret_cast(rgba) } + }; + vertex_buffer_push_back_indices(buffer_triangles_textured, indices, 6); + vertex_buffer_push_back_vertices(buffer_triangles_textured, vertices, 4); +} + +void Refresh() { + vertex_buffer_clear(buffer_triangles_plain); + vertex_buffer_clear(buffer_triangles_textured); + vertex_buffer_clear(buffer_lines); +} + +void PreRender() { + glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT | GL_TEXTURE_BIT | GL_COLOR_BUFFER_BIT); + + glEnable(GL_BLEND); + glEnable(GL_TEXTURE_2D); + glDisable(GL_ALPHA_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glDisable(GL_LIGHTING); + glDisable(GL_STENCIL_TEST); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); + + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_EDGE_FLAG_ARRAY); + glDisableClientState(GL_FOG_COORD_ARRAY); + glDisableClientState(GL_SECONDARY_COLOR_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_NORMAL_ARRAY); + + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_INDEX_ARRAY); +} + +void PostRender() { + glUseProgram(0); + glBindTexture(GL_TEXTURE_2D, 0); + glPopClientAttrib(); + glPopAttrib(); +} + +void Render() { + glUseProgram(shader_v2fc4f); + vertex_buffer_render(buffer_triangles_plain, GL_TRIANGLES); + vertex_buffer_render(buffer_lines, GL_LINES); + glUseProgram(shader_v2ft2fc4f); + glBindTexture(GL_TEXTURE_2D, textures::texture); + vertex_buffer_render(buffer_triangles_textured, GL_TRIANGLES); +} + +} diff --git a/src/drawgl.hpp b/src/drawgl.hpp new file mode 100644 index 00000000..e2c76067 --- /dev/null +++ b/src/drawgl.hpp @@ -0,0 +1,55 @@ +/* + * drawgl.hpp + * + * Created on: May 21, 2017 + * Author: nullifiedcat + */ + +#ifndef DRAWGL_HPP_ +#define DRAWGL_HPP_ + +#include "drawing.h" + +extern "C" { +#include "freetype-gl/vec234.h" +#include "freetype-gl/vertex-buffer.h" +} + +namespace drawgl { + +struct vertex_v2c4_t { + ftgl::vec2 xy; + ftgl::vec4 rgba; +}; + +struct vertex_v2t2c4_t { + ftgl::vec2 xy; + ftgl::vec2 st; + ftgl::vec4 rgba; +}; + + +extern ftgl::vertex_buffer_t* buffer_lines; +extern ftgl::vertex_buffer_t* buffer_triangles_plain; +extern ftgl::vertex_buffer_t* buffer_triangles_textured; + +extern const float white[4]; + +void Initialize(); + +void FilledRect(float x, float y, float w, float h, const float* rgba = white); +void Line(float x, float y, float dx, float dy, const float* rgba = white); +void Rect(float x, float y, float w, float h, const float* rgba = white); +void TexturedRect(float x, float y, float w, float h, float u, float v, float u2, float v2, const float* rgba = white); + +void Refresh(); +void Render(); + +void PreRender(); +void PostRender(); + +extern bool ready_state; + +} + +#endif /* DRAWGL_HPP_ */ diff --git a/src/drawing.cpp b/src/drawing.cpp index bcced739..169a7466 100644 --- a/src/drawing.cpp +++ b/src/drawing.cpp @@ -5,15 +5,21 @@ * Author: nullifiedcat */ +#ifndef TEXTMODE + #include "common.h" #include "sdk.h" +#include "ftrender.hpp" + +#include std::array side_strings; std::array center_strings; -std::array side_strings_colors { 0 }; -std::array center_strings_colors { 0 }; -int side_strings_count { 0 }; -int center_strings_count { 0 }; +std::array side_strings_colors { colors::empty }; +std::array center_strings_colors { colors::empty }; +size_t side_strings_count { 0 }; +size_t center_strings_count { 0 }; + void InitStrings() { ResetStrings(); @@ -24,197 +30,57 @@ void ResetStrings() { center_strings_count = 0; } -void AddSideString(const std::string& string, int color) { +void AddSideString(const std::string& string, const rgba_t& color) { side_strings[side_strings_count] = string; side_strings_colors[side_strings_count] = color; - side_strings_count++; + ++side_strings_count; } void DrawStrings() { int y { 8 }; - for (int i = 0; i < side_strings_count; i++) { - draw::String(fonts::ESP, 8, y, side_strings_colors[i], 2, side_strings[i]); - y += 14; + for (size_t i = 0; i < side_strings_count; ++i) { + FTGL_Draw(side_strings[i], 8, y, fonts::ftgl_ESP, side_strings_colors[i]); + y += fonts::ftgl_ESP->height + 1; } y = draw::height / 2; - for (int i = 0; i < center_strings_count; i++) { - draw::String(fonts::ESP, draw::width / 2, y, center_strings_colors[i], 2, center_strings[i]); - y += 14; + for (size_t i = 0; i < center_strings_count; ++i) { + int sx; + FTGL_StringLength(center_strings[i], fonts::ftgl_ESP, &sx, nullptr); + FTGL_Draw(center_strings[i], (draw::width - sx) / 2, y, fonts::ftgl_ESP, center_strings_colors[i]); + y += fonts::ftgl_ESP->height + 1; } - //logging::Info("Drawing strings done: %d %ul", y, fonts::ESP); } -void AddCenterString(const std::string& string, int color) { +void AddCenterString(const std::string& string, const rgba_t& color) { center_strings[center_strings_count] = string; center_strings_colors[center_strings_count] = color; - center_strings_count++; + ++center_strings_count; } // TODO globals int draw::width = 0; int draw::height = 0; - -int colors::EntityF(CachedEntity* ent) { - int result, skin, plclr; - k_EItemType type; - - using namespace colors; - result = white; - type = ent->m_ItemType; - if (type) { - if (type >= ITEM_HEALTH_SMALL && type <= ITEM_HEALTH_LARGE || type == ITEM_TF2C_PILL) result = green; - else if (type >= ITEM_POWERUP_FIRST && type <= ITEM_POWERUP_LAST) { - skin = RAW_ENT(ent)->GetSkin(); - if (skin == 1) result = red; - else if (skin == 2) result = blu; - else result = yellow; - } - else if (type >= ITEM_TF2C_W_FIRST && type <= ITEM_TF2C_W_LAST) { - if (CE_BYTE(ent, netvar.bRespawning)) { - result = red; - } else { - result = yellow; - } - } - else if (type == ITEM_HL_BATTERY) { - result = yellow; - } - } - - if (ent->m_iClassID == CL_CLASS(CCurrencyPack)) { - if (CE_BYTE(ent, netvar.bDistributed)) - result = red; - else - result = green; - } - - if (ent->m_Type == ENTITY_PROJECTILE) { - if (ent->m_iTeam == TEAM_BLU) result = blu; - else if (ent->m_iTeam == TEAM_RED) result = red; - if (ent->m_bCritProjectile) { - if (ent->m_iTeam == TEAM_BLU) result = blu_u; - else if (ent->m_iTeam == TEAM_RED) result = red_u; - } - } - - if (ent->m_Type == ENTITY_PLAYER || ent->m_Type == ENTITY_BUILDING) { - if (ent->m_iTeam == TEAM_BLU) result = blu; - else if (ent->m_iTeam == TEAM_RED) result = red; - if (ent->m_Type == ENTITY_PLAYER) { - if (IsPlayerInvulnerable(ent)) { - if (ent->m_iTeam == TEAM_BLU) result = blu_u; - else if (ent->m_iTeam == TEAM_RED) result = red_u; - } - if (HasCondition(ent)) { - if (ent->m_iTeam == TEAM_BLU) result = blu_v; - else if (ent->m_iTeam == TEAM_RED) result = red_v; - } - plclr = playerlist::Color(ent); - if (plclr) result = plclr; - } - } - - return result; -} - -int colors::RainbowCurrent() { - return colors::FromHSL(fabs(sin(g_GlobalVars->curtime / 2.0f)) * 360.0f, 0.85f, 0.9f); -} - -int colors::FromHSL(float h, float s, float v) { - double hh, p, q, t, ff; - long i; - - if(s <= 0.0) { // < is bogus, just shuts up warnings - return colors::Create(v * 255, v * 255, v * 255, 255); - } - hh = h; - if(hh >= 360.0) hh = 0.0; - hh /= 60.0; - i = (long)hh; - ff = hh - i; - p = v * (1.0 - s); - q = v * (1.0 - (s * ff)); - t = v * (1.0 - (s * (1.0 - ff))); - - switch(i) { - case 0: - return colors::Create(v * 255, t * 255, p * 255, 255); - case 1: - return colors::Create(q * 255, v * 255, p * 255, 255); - case 2: - return colors::Create(p * 255, v * 255, t * 255, 255); - case 3: - return colors::Create(p * 255, q * 255, v * 255, 255); - break; - case 4: - return colors::Create(t * 255, p * 255, v * 255, 255); - case 5: - default: - return colors::Create(v * 255, p * 255, q * 255, 255); - } -} - -int colors::Health(int health, int max) { - float hf; - hf = (float)health / (float)max; - if (hf > 1) { - return colors::Create(64, 128, 255, 255); - } - return colors::Create((hf <= 0.5 ? 1.0 : 1.0 - 2 * (hf - 0.5)) * 255, (hf <= 0.5 ? (2 * hf) : 1) * 255, 0, 255); -} - -void draw::DrawRect(int x, int y, int w, int h, int color) { - g_ISurface->DrawSetColor(*reinterpret_cast(&color)); - g_ISurface->DrawFilledRect(x, y, x + w, y + h); -} +float draw::fov = 90.0f; namespace fonts { -unsigned long ESP = 0; -unsigned long MENU = 0; -unsigned long MENU_BIG = 0; - -const std::vector fonts = {"Tahoma Bold", "Tahoma", "TF2 Build", "Verdana", "Verdana Bold", "Arial", "Courier New", "Ubuntu Mono Bold"}; -CatEnum family_enum(fonts); -CatVar esp_family(family_enum, "font_esp_family", "2", "ESP font", "ESP font family"); -CatVar esp_height(CV_INT, "font_esp_height", "14", "ESP height", "ESP font height"); - -void Update() { - fonts::ESP = g_ISurface->CreateFont(); - g_ISurface->SetFontGlyphSet(fonts::ESP, fonts::fonts[_clamp(0, 7, (int)fonts::esp_family)].c_str(), (int)fonts::esp_height, 0, 0, 0, 0); // or Ubuntu Mono Bold - //g_ISurface->ResetFontCaches(); -} +ftgl::texture_font_t* ftgl_ESP = nullptr; +CatVar esp_ftgl_font(CV_STRING, "font_ftgl_esp", "opensans-bold", "FTGL Font"); } void draw::Initialize() { - fonts::ESP = g_ISurface->CreateFont(); - fonts::MENU = g_ISurface->CreateFont(); - fonts::MENU_BIG = g_ISurface->CreateFont(); if (!draw::width || !draw::height) { g_IEngine->GetScreenSize(draw::width, draw::height); } - const auto install_callback_fn = [](CatVar* var) { - var->convar_parent->InstallChangeCallback([](IConVar* var, const char* pOldValue, float flOldValue) { - fonts::Update(); - }); - }; + FTGL_PreInit(); - fonts::esp_family.OnRegister(install_callback_fn); - fonts::esp_height.OnRegister(install_callback_fn); - - fonts::Update(); - g_ISurface->SetFontGlyphSet(fonts::ESP, fonts::fonts[_clamp(0, 5, (int)fonts::esp_family)].c_str(), (int)fonts::esp_height, 0, 0, 0, 0); - g_ISurface->SetFontGlyphSet(fonts::MENU, "Verdana", 12, 0, 0, 0, 0); - g_ISurface->SetFontGlyphSet(fonts::MENU_BIG, "Verdana Bold", 30, 0, 0, 0, 0x0); -} - -void draw::DrawLine(int x, int y, int dx, int dy, int color) { - g_ISurface->DrawSetColor(*reinterpret_cast(&color)); - g_ISurface->DrawLine(x, y, x + dx, y + dy); + fonts::esp_ftgl_font.InstallChangeCallback([](IConVar* var, const char* pOldValue, float flOldValue) { + FTGL_ChangeFont(&fonts::ftgl_ESP, fonts::esp_ftgl_font.GetString()); + (void)flOldValue; + }); } bool draw::EntityCenterToScreen(CachedEntity* entity, Vector& out) { @@ -229,10 +95,14 @@ bool draw::EntityCenterToScreen(CachedEntity* entity, Vector& out) { return succ; } -bool draw::WorldToScreen(Vector& origin, Vector& screen) { - float w, odw; +VMatrix wts {}; - const VMatrix& wts = g_IEngine->WorldToScreenMatrix(); +void draw::UpdateWTS() { + memcpy(&wts, &g_IEngine->WorldToScreenMatrix(), sizeof(VMatrix)); +} + +bool draw::WorldToScreen(const Vector& origin, Vector& screen) { + float w, odw; screen.z = 0; w = wts[3][0] * origin[0] + wts[3][1] * origin[1] + wts[3][2] * origin[2] + wts[3][3]; if (w > 0.001) { @@ -244,96 +114,4 @@ bool draw::WorldToScreen(Vector& origin, Vector& screen) { return false; } -void draw::OutlineRect(int x, int y, int w, int h, int color) { - g_ISurface->DrawSetColor(*reinterpret_cast(&color)); - g_ISurface->DrawOutlinedRect(x, y, x + w, y + h); -} - -void draw::GetStringLength(unsigned long font, char* string, int& length, int& height) { - wchar_t buf[512]; - memset(buf, 0, sizeof(wchar_t) * 512); - mbstowcs(buf, string, strlen(string)); - g_ISurface->GetTextSize(font, buf, length, height); -} - -void draw::String (unsigned long font, int x, int y, int color, int shadow, const char* text) { - bool newlined; - int w, h, s, n; - char ch[512]; - wchar_t string[512]; - size_t len; - - newlined = false; - len = strlen(text); - for (int i = 0; i < len; i++) { - if (text[i] == '\n') { - newlined = true; break; - } - } - if (newlined) { - memset(ch, 0, sizeof(char) * 512); - GetStringLength(font, "W", w, h); - strncpy(ch, text, 511); - s = 0; - n = 0; - for (int i = 0; i < len; i++) { - if (ch[i] == '\n') { - ch[i] = 0; - draw::String(font, x, y + n * (h), color, shadow, &ch[0] + s); - n++; - s = i + 1; - } - } - draw::String(font, x, y + n * (h), color, shadow, &ch[0] + s); - } else { - memset(string, 0, sizeof(wchar_t) * 512); - mbstowcs(string, text, 511); - draw::WString(font, x, y, color, shadow, string); - } -} - -void draw::String(unsigned long font, int x, int y, int color, int shadow, std::string text) { - draw::String(font, x, y, color, shadow, text.c_str()); -} -CatVar fast_outline(CV_SWITCH, "fast_outline", "0", "Fast font outline", "Use only single repaint to increase performance"); -void draw::WString(unsigned long font, int x, int y, int color, int shadow, const wchar_t* text) { - unsigned char alpha; - int black_t; - - if (shadow) { - alpha = (color >> 24); - black_t = ((alpha == 255) ? colors::black : colors::Create(0, 0, 0, alpha / shadow)); - if (shadow > 0) { - draw::WString(font, x + 1, y + 1, black_t, false, text); - } - if (shadow > 1 && !fast_outline) { - draw::WString(font, x - 1, y + 1, black_t, false, text); - draw::WString(font, x - 1, y - 1, black_t, false, text); - draw::WString(font, x + 1, y - 1, black_t, false, text); - draw::WString(font, x + 1, y, black_t, false, text); - draw::WString(font, x, y + 1, black_t, false, text); - draw::WString(font, x, y - 1, black_t, false, text); - draw::WString(font, x - 1, y, black_t, false, text); - } - } - g_ISurface->DrawSetTextPos(x, y); - g_ISurface->DrawSetTextColor(*reinterpret_cast(&color)); - g_ISurface->DrawSetTextFont(font); - g_ISurface->DrawUnicodeString(text); -} - -void draw::FString(unsigned long font, int x, int y, int color, int shadow, const char* text, ...) { - va_list list; - char buffer[2048] = { '\0' }; - va_start(list, text); - vsprintf(buffer, text, list); - va_end(list); - draw::String(font, x, y, color, shadow, buffer); -} - -std::pair draw::GetStringLength(unsigned long font, std::string string) { - int l, h; - draw::GetStringLength(font, (char*)string.c_str(), l, h); - return std::make_pair(l, h); -} - +#endif diff --git a/src/drawing.h b/src/drawing.h index 850855f9..0dab6891 100644 --- a/src/drawing.h +++ b/src/drawing.h @@ -8,11 +8,11 @@ #ifndef DRAWING_H_ #define DRAWING_H_ -#include "beforecheaders.h" -#include -#include -#include -#include "aftercheaders.h" +#include "common.h" + +extern "C" { +#include +} class CachedEntity; class Vector; @@ -22,92 +22,32 @@ class CatEnum; namespace fonts { -// FIXME add menu fonts -extern unsigned long ESP; -extern unsigned long MENU; -extern unsigned long MENU_BIG; - -void Update(); - -extern const std::vector fonts; -extern CatEnum family_enum; -extern CatVar esp_family; -extern CatVar esp_height; - -} - -namespace colors { - -constexpr int Create(int r, int g, int b, int a) { - unsigned char _r = (r) & 0xFF; - unsigned char _g = (g) & 0xFF; - unsigned char _b = (b) & 0xFF; - unsigned char _a = (a) & 0xFF; - return (int)(_r) | (int)(_g << 8) | (int)(_b << 16) | (int)(_a << 24); -} - -constexpr int Transparent(int base, float mod = 0.5f) { - unsigned char _a = (base >> 24) & 0xFF; - unsigned char _b = (base >> 16) & 0xFF; - unsigned char _g = (base >> 8) & 0xFF; - unsigned char _r = (base) & 0xFF; - return Create(_r, _g, _b, (int)((float)(_a) * mod)); -} - -constexpr int pink = Create(255, 105, 180, 255); - -constexpr int white = Create(255, 255, 255, 255); -constexpr int black = Create(0, 0, 0, 255); - -constexpr int red = Create(237, 42, 42, 255), blu = Create(28, 108, 237, 255); -constexpr int red_b = Create(64, 32, 32, 178), blu_b = Create(32, 32, 64, 178); // Background -constexpr int red_v = Create(196, 102, 108, 255), blu_v = Create(102, 182, 196, 255); // Vaccinator -constexpr int red_u = Create(216, 34, 186, 255), blu_u = Create(167, 75, 252, 255); // Ubercharged -constexpr int yellow = Create(255, 255, 0, 255); -constexpr int orange = Create(255, 120, 0, 255); -constexpr int green = Create(0, 255, 0, 255); - -int FromHSL(float h, float s, float l); -int RainbowCurrent(); -int Health(int health, int max); -int EntityF(CachedEntity* ent); +extern ftgl::texture_font_t* ftgl_ESP; } void InitStrings(); void ResetStrings(); -void AddCenterString(const std::string& string, int color = 0xFFFFFFFF); -void AddSideString(const std::string& string, int color = 0xFFFFFFFF); +void AddCenterString(const std::string& string, const rgba_t& color = colors::white); +void AddSideString(const std::string& string, const rgba_t& color = colors::white); void DrawStrings(); namespace draw { extern int width; extern int height; +extern float fov; void Initialize(); -void String (unsigned long font, int x, int y, int color, int shadow, const char* text); -void String (unsigned long font, int x, int y, int color, int shadow, std::string text); -void WString(unsigned long font, int x, int y, int color, int shadow, const wchar_t* text); -void FString(unsigned long font, int x, int y, int color, int shadow, const char* text, ...); - -/*void DrawString(unsigned long font, int x, int y, Color color, const wchar_t* text); -void DrawString(int x, int y, Color color, Color background, bool center, const char* text, ...); -void DrawString(int x, int y, Color color, const char* text, ...);*/ -void DrawRect(int x, int y, int w, int h, int color); -void DrawLine(int x, int y, int dx, int dy, int color); -bool WorldToScreen(Vector &origin, Vector &screen); +void UpdateWTS(); +bool WorldToScreen(const Vector &origin, Vector &screen); bool EntityCenterToScreen(CachedEntity* entity, Vector& out); -void OutlineRect(int x, int y, int w, int h, int color); -void GetStringLength(unsigned long font, char* string, int& length, int& height); -std::pair GetStringLength(unsigned long font, std::string string); -//void DrawString(unsigned font_handle, int x, int y, Color color, const char* text, ...); } -#if NOGUI == 1 -constexpr int GUIColor() { +#if not ENABLE_GUI +constexpr rgba_t GUIColor() { return colors::white; } #endif diff --git a/src/drawmgr.cpp b/src/drawmgr.cpp new file mode 100644 index 00000000..d6af567e --- /dev/null +++ b/src/drawmgr.cpp @@ -0,0 +1,108 @@ +/* + * drawmgr.cpp + * + * Created on: May 22, 2017 + * Author: nullifiedcat + */ + +#include "common.h" +#include "hack.h" + +void BeginCheatVisuals() { + std::lock_guard draw_lock(drawing_mutex); + if (drawgl::ready_state) { + FTGL_NewFrame(); + drawgl::Refresh(); + ResetStrings(); + } +} + +std::mutex drawing_mutex; + +CatVar info_text(CV_SWITCH, "info", "1", "Show info", "Show cathook version in top left corner"); + +void DrawCheatVisuals() { + std::lock_guard draw_lock(drawing_mutex); + if (drawgl::ready_state) { + { + PROF_SECTION(DRAW_misc); + SAFE_CALL(hacks::shared::misc::DrawText()); + } + if (info_text) { + PROF_SECTION(DRAW_info); + std::string name_s, reason_s; + PROF_SECTION(PT_info_text); + AddSideString("cathook by nullifiedcat", colors::RainbowCurrent()); + AddSideString(hack::GetVersion(), GUIColor()); // github commit and date + AddSideString(hack::GetType(), GUIColor()); // Compile type +#if ENABLE_GUI + AddSideString("Press 'INSERT' or 'F11' key to open/close cheat menu.", GUIColor()); + AddSideString("Use mouse to navigate in menu.", GUIColor()); +#endif + if (!g_IEngine->IsInGame() +#if ENABLE_GUI + || g_pGUI->Visible() +#endif + ) { + name_s = force_name.GetString(); + if (name_s.length() < 3) name_s = "*Not Set*"; + reason_s = disconnect_reason.GetString(); + if (reason_s.length() < 3) reason_s = "*Not Set*"; + AddSideString(""); // foolish + AddSideString(format("Custom Name: ", name_s), GUIColor()); + AddSideString(format("Custom Disconnect Reason: ", reason_s), GUIColor()); + } + } + if (CE_GOOD(g_pLocalPlayer->entity) && !g_Settings.bInvalid) { + PROF_SECTION(PT_total_hacks); + { + PROF_SECTION(DRAW_aimbot); + hacks::shared::aimbot::DrawText(); + } + IF_GAME(IsTF2()) { + PROF_SECTION(DRAW_skinchanger); + SAFE_CALL(hacks::tf2::skinchanger::DrawText()); + } + IF_GAME(IsTF()) { + PROF_SECTION(DRAW_radar); + SAFE_CALL(hacks::tf::radar::Draw()); + } + IF_GAME(IsTF2()) { + PROF_SECTION(DRAW_healarrows); + hacks::tf2::healarrow::Draw(); + } + { + PROF_SECTION(DRAW_walkbot); + hacks::shared::walkbot::Draw(); + } + IF_GAME(IsTF()) { + PROF_SECTION(PT_antidisguise); + SAFE_CALL(hacks::tf2::antidisguise::Draw()); + } + IF_GAME(IsTF()) { + PROF_SECTION(PT_spyalert); + SAFE_CALL(hacks::tf::spyalert::Draw()); + } +#ifdef IPC_ENABLED + IF_GAME(IsTF()) SAFE_CALL(hacks::shared::followbot::Draw()); +#endif + { + PROF_SECTION(DRAW_esp); + hacks::shared::esp::Draw(); + } + DrawSpinner(); + Prediction_PaintTraverse(); + } + { + PROF_SECTION(DRAW_strings); + DrawStrings(); + } + } + +} + +void EndCheatVisuals() { + if (drawgl::ready_state) { + + } +} diff --git a/src/drawmgr.hpp b/src/drawmgr.hpp new file mode 100644 index 00000000..f4b72c35 --- /dev/null +++ b/src/drawmgr.hpp @@ -0,0 +1,21 @@ +/* + * drawmgr.hpp + * + * Created on: May 22, 2017 + * Author: nullifiedcat + */ + +#ifndef DRAWMGR_HPP_ +#define DRAWMGR_HPP_ + +#include "beforecheaders.h" +#include +#include "aftercheaders.h" + +extern std::mutex drawing_mutex; + +void BeginCheatVisuals(); +void DrawCheatVisuals(); +void EndCheatVisuals(); + +#endif /* DRAWMGR_HPP_ */ diff --git a/src/entitycache.cpp b/src/entitycache.cpp index 82931150..01478f3f 100644 --- a/src/entitycache.cpp +++ b/src/entitycache.cpp @@ -13,8 +13,8 @@ // This method of const'ing the index is weird. CachedEntity::CachedEntity() : - m_IDX(((unsigned)this - (unsigned)&entity_cache::array) / sizeof(CachedEntity)), - hitboxes(this) { + m_IDX(int(((unsigned)this - (unsigned)&entity_cache::array) / sizeof(CachedEntity))), + hitboxes(hitbox_cache::Get(unsigned(m_IDX))) { #if PROXY_ENTITY != true m_pEntity = nullptr; #endif @@ -39,60 +39,86 @@ void CachedEntity::Reset() { m_lLastSeen = 0; m_lSeenTicks = 0; memset(&player_info, 0, sizeof(player_info_s)); - memset(&m_Bones, 0, sizeof(matrix3x4_t) * 128); - m_bBonesSetup = false; m_vecAcceleration.Zero(); m_vecVOrigin.Zero(); m_vecVelocity.Zero(); m_fLastUpdate = 0; - hitboxes.Reset(); } CachedEntity::~CachedEntity() {} -IClientEntity* CachedEntity::InternalEntity() { - return g_IEntityList->GetClientEntity(m_IDX); -} +static CatVar ve_window(CV_FLOAT, "debug_ve_window", "0", "VE Window"); +static CatVar ve_smooth(CV_SWITCH, "debug_ve_smooth", "1", "VE Smoothing"); +static CatVar ve_averager_size(CV_INT, "debug_ve_averaging", "8", "VE Averaging"); void CachedEntity::Update() { SEGV_BEGIN - if (!RAW_ENT(this)) return; + + auto raw = RAW_ENT(this); + + if (!raw) return; #if PROXY_ENTITY != true m_pEntity = g_IEntityList->GetClientEntity(idx); if (!m_pEntity) { return; } #endif - m_iClassID = RAW_ENT(this)->GetClientClass()->m_ClassID; - //if (TF2 && EstimateAbsVelocity) EstimateAbsVelocity(m_pEntity, m_vecVelocity); - /*if ((gvars->realtime - m_fLastUpdate) >= 0.05f) { - //if (gvars->tickcount - m_nLastTick > 1) { - //logging::Info("Running %i ticks behind!", gvars->tickcount - m_nLastTick); - //} - //Vector velnew = (origin - m_vecVOrigin) * (0.05f / (m_fLastUpdate - gvars->realtime)) * 20; - Vector velnew; - if (EstimateAbsVelocity) - EstimateAbsVelocity(m_pEntity, velnew); - m_vecAcceleration = (velnew - m_vecVelocity); - m_vecVelocity = (m_vecVelocity + velnew) / 2; - //logging::Info("Multiplier for %i: %f", m_IDX, (0.1f / (m_fLastUpdate - gvars->realtime))); + bool dormant = raw->IsDormant(); + bool dormant_state_changed = dormant != was_dormant; + was_dormant = dormant; + m_iClassID = raw->GetClientClass()->m_ClassID; + m_vecOrigin = raw->GetAbsOrigin(); + /*float simtime = CE_FLOAT(this, netvar.m_flSimulationTime); + float deltat = (simtime - m_fLastUpdate); + if (ve_smooth) { + // + if (dormant_state_changed) { + velocity_averager.reset(0); + velocity_is_valid = false; + } + if (size_t(int(ve_averager_size)) != velocity_averager.size()) { + velocity_averager.resize(size_t(int(ve_averager_size))); + velocity_averager.reset(0); + } + } + if (!dormant && deltat > (float)ve_window) { + ICollideable* ca = RAW_ENT(this)->GetCollideable(); + Vector origin = m_vecOrigin; + if (ca) { + origin = ca->GetCollisionOrigin(); + } + Vector delta = origin - m_vecVOrigin; + Vector velnew = delta / deltat; + m_vecAcceleration = velnew - m_vecVelocity; + if (ve_smooth) { + if (velocity_is_valid) { + static Vector zero {0.0f, 0.0f, 0.0f}; + float length = velnew.Length(); + velocity_averager.push(length); + Vector normalized = (length ? (velnew / length) : zero); + m_vecVelocity = normalized * velocity_averager.average(); + //m_vecVelocity = velocity_averager.average(); + } else { + EstimateAbsVelocity(RAW_ENT(this), m_vecVelocity); + //velocity_averager.push(m_vecVelocity); + velocity_is_valid = true; + } + } else + m_vecVelocity = velnew; m_vecVOrigin = origin; - m_fLastUpdate = gvars->realtime; + m_fLastUpdate = simtime; }*/ - m_vecOrigin = RAW_ENT(this)->GetAbsOrigin(); m_ItemType = ITEM_NONE; m_lSeenTicks = 0; m_lLastSeen = 0; + hitboxes.Update(); + m_bGrenadeProjectile = false; - m_bBonesSetup = false; - m_bVisCheckComplete = false; - SAFE_CALL(hitboxes.Update()); - if (m_iClassID == RCC_PLAYER) { m_Type = EntityType::ENTITY_PLAYER; } else if (m_iClassID == CL_CLASS(CTFGrenadePipebombProjectile) || @@ -139,23 +165,23 @@ void CachedEntity::Update() { if (m_Type == EntityType::ENTITY_PROJECTILE) { m_bCritProjectile = IsProjectileCrit(this); - m_iTeam = CE_INT(this, netvar.iTeamNum); + m_iTeam = NET_INT(raw, netvar.iTeamNum); m_bEnemy = (m_iTeam != g_pLocalPlayer->team); } if (m_Type == EntityType::ENTITY_PLAYER) { - m_bAlivePlayer = !(NET_BYTE(RAW_ENT(this), netvar.iLifeState)); + m_bAlivePlayer = !(NET_BYTE(raw, netvar.iLifeState)); g_IEngine->GetPlayerInfo(m_IDX, &player_info); - m_iTeam = CE_INT(this, netvar.iTeamNum); // TODO + m_iTeam = NET_INT(raw, netvar.iTeamNum); // TODO m_bEnemy = (m_iTeam != g_pLocalPlayer->team); - m_iHealth = CE_INT(this, netvar.iHealth); + m_iHealth = NET_INT(raw, netvar.iHealth); m_iMaxHealth = g_pPlayerResource->GetMaxHealth(this); } if (m_Type == EntityType::ENTITY_BUILDING) { - m_iTeam = CE_INT(this, netvar.iTeamNum); // TODO + m_iTeam = NET_INT(raw, netvar.iTeamNum); // TODO m_bEnemy = (m_iTeam != g_pLocalPlayer->team); - m_iHealth = CE_INT(this, netvar.iBuildingHealth); - m_iMaxHealth = CE_INT(this, netvar.iBuildingMaxHealth); + m_iHealth = NET_INT(raw, netvar.iBuildingHealth); + m_iMaxHealth = NET_INT(raw, netvar.iBuildingMaxHealth); } SEGV_END_INFO("Updating entity"); } @@ -206,29 +232,6 @@ bool CachedEntity::IsVisible() { return false; } -static CatEnum setupbones_time_enum({ "ZERO", "CURTIME", "LP SERVERTIME", "SIMTIME" }); -static CatVar setupbones_time(setupbones_time_enum, "setupbones_time", "3", "Setupbones", "Defines setupbones 4th argument, change it if your aimbot misses, idk!!"); - -matrix3x4_t* CachedEntity::GetBones() { - static float bones_setup_time = 0.0f; - switch ((int)setupbones_time) { - case 1: - bones_setup_time = g_GlobalVars->curtime; - break; - case 2: - if (CE_GOOD(LOCAL_E)) - bones_setup_time = g_GlobalVars->interval_per_tick * CE_INT(LOCAL_E, netvar.nTickBase); - break; - case 3: - if (CE_GOOD(this)) - bones_setup_time = CE_FLOAT(this, netvar.m_flSimulationTime); - } - if (!m_bBonesSetup) { - m_bBonesSetup = RAW_ENT(this)->SetupBones(m_Bones, MAXSTUDIOBONES, 0x100, bones_setup_time); // gvars->curtime - } - return m_Bones; -} - namespace entity_cache { CachedEntity array[MAX_ENTITIES] {}; diff --git a/src/entitycache.h b/src/entitycache.h index 12e623f9..def67f51 100644 --- a/src/entitycache.h +++ b/src/entitycache.h @@ -10,9 +10,18 @@ #include "enums.h" #include "itemtypes.h" +#include "interfaces.h" +#include "entityhitboxcache.hpp" #include "fixsdk.h" + +#include "beforecheaders.h" +#include "averager.hpp" +#include "aftercheaders.h" + #include #include +#include +#include #include struct matrix3x4_t; @@ -29,7 +38,7 @@ struct mstudiobbox_t; #define PROXY_ENTITY true #if PROXY_ENTITY == true -#define RAW_ENT(ce) ((ce) ? (ce)->InternalEntity() : nullptr) +#define RAW_ENT(ce) ce->InternalEntity() #else #define RAW_ENT(ce) ce->m_pEntity #endif @@ -42,7 +51,7 @@ struct mstudiobbox_t; #define CE_BYTE(entity, offset) CE_VAR(entity, offset, unsigned char) #define CE_VECTOR(entity, offset) CE_VAR(entity, offset, Vector) -#define CE_GOOD(entity) (!g_Settings.bInvalid && dynamic_cast(entity) && entity->m_iClassID && RAW_ENT(entity) && !RAW_ENT(entity)->IsDormant()) +#define CE_GOOD(entity) (entity && !g_Settings.bInvalid && entity->Good()) #define CE_BAD(entity) (!CE_GOOD(entity)) #define IDX_GOOD(idx) (idx >= 0 && idx <= HIGHEST_ENTITY && idx < MAX_ENTITIES) @@ -51,58 +60,41 @@ struct mstudiobbox_t; #define HIGHEST_ENTITY (entity_cache::max) #define ENTITY(idx) (&entity_cache::Get(idx)) -struct CachedHitbox { - Vector min; - Vector max; - Vector center; - mstudiobbox_t* bbox; -}; - -#define CACHE_MAX_HITBOXES 64 - -class EntityHitboxCache { -public: - EntityHitboxCache(CachedEntity* parent); - ~EntityHitboxCache(); - - CachedHitbox* GetHitbox(int id); - void Update(); - void InvalidateCache(); - bool VisibilityCheck(int id); - void Init(); - int GetNumHitboxes(); - void Reset(); - - bool m_VisCheckValidationFlags[CACHE_MAX_HITBOXES] { false }; - bool m_VisCheck[CACHE_MAX_HITBOXES] { false }; - bool m_CacheValidationFlags[CACHE_MAX_HITBOXES] { false }; - CachedHitbox m_CacheInternal[CACHE_MAX_HITBOXES] {}; - - int m_nNumHitboxes; - bool m_bModelSet; - bool m_bInit; - bool m_bSuccess; - - mstudiohitboxset_t* m_pHitboxSet; - model_t* m_pLastModel; - CachedEntity* parent_ref; // TODO FIXME turn this into an actual reference -}; - class CachedEntity { public: CachedEntity(); ~CachedEntity(); - void Update(); + __attribute__((hot)) void Update(); bool IsVisible(); - matrix3x4_t* GetBones(); - IClientEntity* InternalEntity(); void Reset(); + __attribute__((always_inline, hot, const)) IClientEntity* InternalEntity() const { + return g_IEntityList->GetClientEntity(m_IDX); + } + __attribute__((always_inline, hot, const)) inline bool Good() const { + if (!m_iClassID) return false; + IClientEntity* const entity = InternalEntity(); + return entity && !entity->IsDormant(); + } + template + __attribute__((always_inline, hot, const)) inline T& var(uintptr_t offset) const { + return *reinterpret_cast(uintptr_t(RAW_ENT(this)) + offset); + } + + const int m_IDX; + + int m_iClassID { 0 }; + + Vector m_vecOrigin { 0 }; + int m_iTeam { 0 }; + bool m_bAlivePlayer { false }; + bool m_bEnemy { false }; + int m_iMaxHealth { 0 }; + int m_iHealth { 0 }; // Entity fields start here EntityType m_Type { ENTITY_GENERIC }; - int m_iClassID { 0 }; float m_flDistance { 0.0f }; bool m_bCritProjectile { false }; @@ -111,33 +103,19 @@ public: bool m_bAnyHitboxVisible { false }; bool m_bVisCheckComplete { false }; - Vector m_vecOrigin { 0 }; - k_EItemType m_ItemType { ITEM_NONE }; - int m_iTeam { 0 }; - bool m_bAlivePlayer { false }; - bool m_bEnemy { false }; - int m_iMaxHealth { 0 }; - int m_iHealth { 0 }; unsigned long m_lSeenTicks { 0 }; unsigned long m_lLastSeen { 0 }; - - player_info_s player_info {}; - matrix3x4_t m_Bones[128]; // MAXSTUDIOBONES - bool m_bBonesSetup { false }; - - // Players, Buildings, Stickies - - - // Entity fields end here. - - const int m_IDX; Vector m_vecVOrigin { 0 }; Vector m_vecVelocity { 0 }; Vector m_vecAcceleration { 0 }; float m_fLastUpdate { 0.0f }; - EntityHitboxCache hitboxes; + hitbox_cache::EntityHitboxCache& hitboxes; + player_info_s player_info {}; + Averager velocity_averager { 8 }; + bool was_dormant { true }; + bool velocity_is_valid { false }; #if PROXY_ENTITY != true IClientEntity* m_pEntity { nullptr }; #endif diff --git a/src/entityhitboxcache.cpp b/src/entityhitboxcache.cpp index 8c3ee827..a265a900 100644 --- a/src/entityhitboxcache.cpp +++ b/src/entityhitboxcache.cpp @@ -7,11 +7,11 @@ #include "common.h" -EntityHitboxCache::EntityHitboxCache(CachedEntity* parent) { - InvalidateCache(); - parent_ref = parent; - m_bModelSet = false; - m_nNumHitboxes = 0; +namespace hitbox_cache { + +EntityHitboxCache::EntityHitboxCache() : + parent_ref(&entity_cache::Get(((unsigned)this - (unsigned)&hitbox_cache::array) / sizeof(EntityHitboxCache))) { + Reset(); } int EntityHitboxCache::GetNumHitboxes() { @@ -23,6 +23,7 @@ int EntityHitboxCache::GetNumHitboxes() { EntityHitboxCache::~EntityHitboxCache() {} void EntityHitboxCache::InvalidateCache() { + bones_setup = false; for (int i = 0; i < CACHE_MAX_HITBOXES; i++) { m_CacheValidationFlags[i] = false; m_VisCheckValidationFlags[i] = false; @@ -78,17 +79,42 @@ bool EntityHitboxCache::VisibilityCheck(int id) { return m_VisCheck[id]; } +static CatEnum setupbones_time_enum({ "ZERO", "CURTIME", "LP SERVERTIME", "SIMTIME" }); +static CatVar setupbones_time(setupbones_time_enum, "setupbones_time", "1", "Setupbones", "Defines setupbones 4th argument, change it if your aimbot misses, idk!!"); + +matrix3x4_t* EntityHitboxCache::GetBones() { + static float bones_setup_time = 0.0f; + switch ((int)setupbones_time) { + case 1: + bones_setup_time = g_GlobalVars->curtime; + break; + case 2: + if (CE_GOOD(LOCAL_E)) + bones_setup_time = g_GlobalVars->interval_per_tick * CE_INT(LOCAL_E, netvar.nTickBase); + break; + case 3: + if (CE_GOOD(parent_ref)) + bones_setup_time = CE_FLOAT(parent_ref, netvar.m_flSimulationTime); + } + if (!bones_setup) { + bones_setup = RAW_ENT(parent_ref)->SetupBones(bones, MAXSTUDIOBONES, 0x100, bones_setup_time); + } + return bones; +} + void EntityHitboxCache::Reset() { memset(m_VisCheck, 0, sizeof(bool) * CACHE_MAX_HITBOXES); memset(m_VisCheckValidationFlags, 0, sizeof(bool) * CACHE_MAX_HITBOXES); memset(m_CacheValidationFlags, 0, sizeof(bool) * CACHE_MAX_HITBOXES); memset(m_CacheInternal, 0, sizeof(CachedHitbox) * CACHE_MAX_HITBOXES); + memset(&bones, 0, sizeof(matrix3x4_t) * 128); m_nNumHitboxes = 0; m_bInit = false; m_bModelSet = false; m_bSuccess = false; m_pHitboxSet = nullptr; m_pLastModel = nullptr; + bones_setup = false; } CachedHitbox* EntityHitboxCache::GetHitbox(int id) { @@ -101,11 +127,23 @@ CachedHitbox* EntityHitboxCache::GetHitbox(int id) { box = m_pHitboxSet->pHitbox(id); if (!box) return 0; if (box->bone < 0 || box->bone >= MAXSTUDIOBONES) return 0; - VectorTransform(box->bbmin, parent_ref->GetBones()[box->bone], m_CacheInternal[id].min); - VectorTransform(box->bbmax, parent_ref->GetBones()[box->bone], m_CacheInternal[id].max); + VectorTransform(box->bbmin, GetBones()[box->bone], m_CacheInternal[id].min); + VectorTransform(box->bbmax, GetBones()[box->bone], m_CacheInternal[id].max); m_CacheInternal[id].bbox = box; m_CacheInternal[id].center = (m_CacheInternal[id].min + m_CacheInternal[id].max) / 2; m_CacheValidationFlags[id] = true; } return &m_CacheInternal[id]; } + +EntityHitboxCache array[MAX_ENTITIES] {}; + +void Update() { + +} + +void Invalidate() { + +} + +} diff --git a/src/entityhitboxcache.hpp b/src/entityhitboxcache.hpp new file mode 100644 index 00000000..ce491268 --- /dev/null +++ b/src/entityhitboxcache.hpp @@ -0,0 +1,69 @@ +/* + * entityhitboxcache.hpp + * + * Created on: May 25, 2017 + * Author: nullifiedcat + */ + +#ifndef ENTITYHITBOXCACHE_HPP_ +#define ENTITYHITBOXCACHE_HPP_ + +#include "entitycache.h" + +#include +#include +#include +#include + +#define CACHE_MAX_HITBOXES 64 + +namespace hitbox_cache { + +struct CachedHitbox { + Vector min; + Vector max; + Vector center; + mstudiobbox_t* bbox; +}; + +class EntityHitboxCache { +public: + EntityHitboxCache(); + ~EntityHitboxCache(); + + CachedHitbox* GetHitbox(int id); + void Update(); + void InvalidateCache(); + bool VisibilityCheck(int id); + void Init(); + int GetNumHitboxes(); + void Reset(); + matrix3x4_t* GetBones(); + + int m_nNumHitboxes; + bool m_bModelSet; + bool m_bInit; + bool m_bSuccess; + + mstudiohitboxset_t* m_pHitboxSet; + model_t* m_pLastModel; + CachedEntity* parent_ref; // TODO FIXME turn this into an actual reference + + bool m_VisCheckValidationFlags[CACHE_MAX_HITBOXES] { false }; + bool m_VisCheck[CACHE_MAX_HITBOXES] { false }; + bool m_CacheValidationFlags[CACHE_MAX_HITBOXES] { false }; + CachedHitbox m_CacheInternal[CACHE_MAX_HITBOXES] {}; + + matrix3x4_t bones[128]; + bool bones_setup { false }; +}; + +extern EntityHitboxCache array[2048]; +inline EntityHitboxCache& Get(unsigned i) { + if (i > 2048) throw std::out_of_range("Requested out-of-range entity hitbox cache entry!"); + return array[i]; +} + +} + +#endif /* ENTITYHITBOXCACHE_HPP_ */ diff --git a/src/entitywrap.cpp b/src/entitywrap.cpp deleted file mode 100644 index 6c9a20b7..00000000 --- a/src/entitywrap.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* - * entitywrap.cpp - * - * Created on: Mar 18, 2017 - * Author: nullifiedcat - */ - -#include "entitywrap.h" - -#include "common.h" - -EntityWrapper::EntityWrapper(int idx) : idx(idx) {} - -bool EntityWrapper::good() const { - return idx < g_IEntityList->GetHighestEntityIndex() && g_IEntityList->GetClientEntity(idx); -} - -IClientEntity* EntityWrapper::operator ->() const { - IClientEntity* ret = g_IEntityList->GetClientEntity(idx); - if (!ret) throw std::runtime_error("referencing null entity"); - return ret; -} diff --git a/src/entitywrap.h b/src/entitywrap.h deleted file mode 100644 index aca17bce..00000000 --- a/src/entitywrap.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * entitywrap.h - * - * Created on: Mar 18, 2017 - * Author: nullifiedcat - */ - -#ifndef ENTITYWRAP_H_ -#define ENTITYWRAP_H_ - -class IClientEntity; - -class EntityWrapper { -public: - EntityWrapper(int idx); - - bool good() const; - IClientEntity* operator->() const; - - const int idx; -}; - -#endif /* ENTITYWRAP_H_ */ diff --git a/src/fidgetspinner.cpp b/src/fidgetspinner.cpp new file mode 100644 index 00000000..99e69c77 --- /dev/null +++ b/src/fidgetspinner.cpp @@ -0,0 +1,98 @@ +/* + * fidgetspinner.cpp + * + * Created on: Jul 4, 2017 + * Author: nullifiedcat + */ + +#include "fidgetspinner.hpp" + +CatVar enable_spinner(CV_SWITCH, "fidgetspinner", "0", "Fidget Spinner", "Part of Cathook Autism Awareness program"); +std::vector spinner_states {}; + +float spinning_speed = 0.0f; +float angle = 0; + +// DEBUG +/*CatCommand add_spinner_speed("fidgetspinner_debug_speedup", "Add speed", []() { + spinning_speed += 100.0f; +});*/ + +class SpinnerListener : public IGameEventListener { +public: + virtual void FireGameEvent(KeyValues* event) { + std::string name(event->GetName()); + if (name == "player_death") { + int attacker = event->GetInt("attacker"); + int eid = g_IEngine->GetPlayerForUserID(attacker); + if (eid == g_IEngine->GetLocalPlayer()) { + spinning_speed += 300.0f; + //logging::Info("Spinning %.2f", spinning_speed); + } + } + } +}; + +SpinnerListener listener; + +void InitSpinner() { + for (int i = 0; i < 4; i++) + spinner_states.emplace_back(i * 64, textures::atlas_height - 64 * 4, 64, 64); + g_IGameEventManager->AddListener(&listener, false); +} + +CatVar spinner_speed_cap(CV_FLOAT, "fidgetspinner_speed_cap", "30", "Speed cap"); +CatVar spinner_speed_scale(CV_FLOAT, "fidgetspinner_speed_scale", "0.03", "Speed scale"); +CatVar spinner_decay_speed(CV_FLOAT, "fidgetspinner_decay_speed", "0.1", "Decay speed"); +CatVar spinner_scale(CV_FLOAT, "fidgetspinner_scale", "32", "Spinner Size"); +CatVar spinner_min_speed(CV_FLOAT, "fidgetspinner_min_speed", "2", "Spinner Min Speed"); + +void DrawSpinner() { + if (not enable_spinner) return; + spinning_speed -= (spinning_speed > 150.0f) ? float(spinner_decay_speed) : float(spinner_decay_speed) / 2.0f; + if (spinning_speed < float(spinner_min_speed)) spinning_speed = float(spinner_min_speed); + if (spinning_speed > 1000) spinning_speed = 1000; + float real_speed = 0; + const float speed_cap(spinner_speed_cap); + if (spinning_speed < 250) real_speed = speed_cap * (spinning_speed / 250.0f); + else if (spinning_speed < 500) real_speed = speed_cap - (speed_cap - 10) * ((spinning_speed - 250.0f) / 250.0f); + else if (spinning_speed < 750) real_speed = 10 + (speed_cap - 20) * ((spinning_speed - 500.0f) / 250.0f); + else real_speed = (speed_cap - 10) + 10 * ((spinning_speed - 750.0f) / 250.0f); + const float speed_scale(spinner_speed_scale); + const float size(spinner_scale); + ftgl::vec2 positions[4] = { + { -size, -size }, + { size, -size }, + { size, size }, + { -size, size} + }; + angle += speed_scale * real_speed; + for (int i = 0; i < 4; i++) { + float x = positions[i].x; + float y = positions[i].y; + positions[i].x = x * cos(angle) - y * sin(angle); + positions[i].y = x * sin(angle) + y * cos(angle); + positions[i].x += draw::width / 2; + positions[i].y += draw::height / 2; + } + int state = min(3, spinning_speed / 250.0f); + + // Paste from drawgl:: + using namespace drawgl; + using namespace ftgl; + + const auto& u1v1 = spinner_states[state].tex_coords[0]; + const auto& u2v2 = spinner_states[state].tex_coords[1]; + GLuint idx = buffer_triangles_textured->vertices->size; + GLuint indices[] = { idx, idx + 1, idx + 2, idx, idx + 2, idx + 3 }; + vertex_v2t2c4_t vertices[] = { + { vec2{ positions[0].x, positions[0].y }, vec2{ u1v1.x, u2v2.y }, *reinterpret_cast(&colors::white) }, + { vec2{ positions[1].x, positions[1].y }, vec2{ u2v2.x, u2v2.y }, *reinterpret_cast(&colors::white) }, + { vec2{ positions[2].x, positions[2].y }, vec2{ u2v2.x, u1v1.y }, *reinterpret_cast(&colors::white) }, + { vec2{ positions[3].x, positions[3].y }, vec2{ u1v1.x, u1v1.y }, *reinterpret_cast(&colors::white) } + }; + vertex_buffer_push_back_indices(buffer_triangles_textured, indices, 6); + vertex_buffer_push_back_vertices(buffer_triangles_textured, vertices, 4); + if (angle > PI * 4) angle -= PI * 4; + +} diff --git a/src/fidgetspinner.hpp b/src/fidgetspinner.hpp new file mode 100644 index 00000000..b0d0bf15 --- /dev/null +++ b/src/fidgetspinner.hpp @@ -0,0 +1,19 @@ +/* + * fidgetspinner.hpp + * + * Created on: Jul 4, 2017 + * Author: nullifiedcat + */ + +#pragma once + +#include "common.h" +#include "atlas.hpp" + +class CatVar; + +extern CatVar enable_spinner; +extern std::vector spinner_states; + +void InitSpinner(); +void DrawSpinner(); diff --git a/src/freetype-gl/distance-field.c b/src/freetype-gl/distance-field.c new file mode 100644 index 00000000..336c766e --- /dev/null +++ b/src/freetype-gl/distance-field.c @@ -0,0 +1,105 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include +#include "edtaa3func.h" + + +double * +make_distance_mapd( double *data, unsigned int width, unsigned int height ) +{ + short * xdist = (short *) malloc( width * height * sizeof(short) ); + short * ydist = (short *) malloc( width * height * sizeof(short) ); + double * gx = (double *) calloc( width * height, sizeof(double) ); + double * gy = (double *) calloc( width * height, sizeof(double) ); + double * outside = (double *) calloc( width * height, sizeof(double) ); + double * inside = (double *) calloc( width * height, sizeof(double) ); + double vmin = DBL_MAX; + unsigned int i; + + // Compute outside = edtaa3(bitmap); % Transform background (0's) + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, outside); + for( i=0; i +vmin) outside[i] = +vmin; + data[i] = (outside[i]+vmin)/(2*vmin); + } + + free( xdist ); + free( ydist ); + free( gx ); + free( gy ); + free( outside ); + free( inside ); + return data; +} + +unsigned char * +make_distance_mapb( unsigned char *img, + unsigned int width, unsigned int height ) +{ + double * data = (double *) calloc( width * height, sizeof(double) ); + unsigned char *out = (unsigned char *) malloc( width * height * sizeof(unsigned char) ); + unsigned int i; + + // find minimimum and maximum values + double img_min = DBL_MAX; + double img_max = DBL_MIN; + + for( i=0; i img_max) + img_max = v; + if (v < img_min) + img_min = v; + } + + // Map values from 0 - 255 to 0.0 - 1.0 + for( i=0; iExample Usage: + * @code + * #include "distance-field.h" + * + * int main( int arrgc, char *argv[] ) + * { + * int width = 512; + * int height = 512; + * unsigned char *image = create_greyscale_image(width, height); + * + * image = make_distance_map( image, width, height ); + * + * return 0; + * } + * @endcode + * + * @{ + */ + +/** + * Create a distance file from the given image. + * + * @param img A greyscale image. + * @param width The width of the given image. + * @param height The height of the given image. + * + * @return A newly allocated distance field. This image must + * be freed after usage. + * + */ +double * +make_distance_mapd( double *img, + unsigned int width, unsigned int height ); + +unsigned char * +make_distance_mapb( unsigned char *img, + unsigned int width, unsigned int height ); + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* __DISTANCE_FIELD_H__ */ diff --git a/src/freetype-gl/edtaa3func.c b/src/freetype-gl/edtaa3func.c new file mode 100644 index 00000000..fa41a9e0 --- /dev/null +++ b/src/freetype-gl/edtaa3func.c @@ -0,0 +1,576 @@ +/* + * edtaa3() + * + * Sweep-and-update Euclidean distance transform of an + * image. Positive pixels are treated as object pixels, + * zero or negative pixels are treated as background. + * An attempt is made to treat antialiased edges correctly. + * The input image must have pixels in the range [0,1], + * and the antialiased image should be a box-filter + * sampling of the ideal, crisp edge. + * If the antialias region is more than 1 pixel wide, + * the result from this transform will be inaccurate. + * + * By Stefan Gustavson (stefan.gustavson@gmail.com). + * + * Originally written in 1994, based on a verbal + * description of the SSED8 algorithm published in the + * PhD dissertation of Ingemar Ragnemalm. This is his + * algorithm, I only implemented it in C. + * + * Updated in 2004 to treat border pixels correctly, + * and cleaned up the code to improve readability. + * + * Updated in 2009 to handle anti-aliased edges. + * + * Updated in 2011 to avoid a corner case infinite loop. + * + * Updated 2012 to change license from LGPL to MIT. + * + * Updated 2014 to fix a bug with the 'gy' gradient computation. + * + */ + +/* + Copyright (C) 2009-2012 Stefan Gustavson (stefan.gustavson@gmail.com) + The code in this file is distributed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +#include +#include "edtaa3func.h" + +/* + * Compute the local gradient at edge pixels using convolution filters. + * The gradient is computed only at edge pixels. At other places in the + * image, it is never used, and it's mostly zero anyway. + */ +void computegradient(double *img, int w, int h, double *gx, double *gy) +{ + int i,j,k,p,q; + double glength, phi, phiscaled, ascaled, errsign, pfrac, qfrac, err0, err1, err; +#define SQRT2 1.4142136 + for(i = 1; i < h-1; i++) { // Avoid edges where the kernels would spill over + for(j = 1; j < w-1; j++) { + k = i*w + j; + if((img[k]>0.0) && (img[k]<1.0)) { // Compute gradient for edge pixels only + gx[k] = -img[k-w-1] - SQRT2*img[k-1] - img[k+w-1] + img[k-w+1] + SQRT2*img[k+1] + img[k+w+1]; + gy[k] = -img[k-w-1] - SQRT2*img[k-w] - img[k-w+1] + img[k+w-1] + SQRT2*img[k+w] + img[k+w+1]; + glength = gx[k]*gx[k] + gy[k]*gy[k]; + if(glength > 0.0) { // Avoid division by zero + glength = sqrt(glength); + gx[k]=gx[k]/glength; + gy[k]=gy[k]/glength; + } + } + } + } + // TODO: Compute reasonable values for gx, gy also around the image edges. + // (These are zero now, which reduces the accuracy for a 1-pixel wide region + // around the image edge.) 2x2 kernels would be suitable for this. +} + +/* + * A somewhat tricky function to approximate the distance to an edge in a + * certain pixel, with consideration to either the local gradient (gx,gy) + * or the direction to the pixel (dx,dy) and the pixel greyscale value a. + * The latter alternative, using (dx,dy), is the metric used by edtaa2(). + * Using a local estimate of the edge gradient (gx,gy) yields much better + * accuracy at and near edges, and reduces the error even at distant pixels + * provided that the gradient direction is accurately estimated. + */ +double edgedf(double gx, double gy, double a) +{ + double df, glength, temp, a1; + + if ((gx == 0) || (gy == 0)) { // Either A) gu or gv are zero, or B) both + df = 0.5-a; // Linear approximation is A) correct or B) a fair guess + } else { + glength = sqrt(gx*gx + gy*gy); + if(glength>0) { + gx = gx/glength; + gy = gy/glength; + } + /* Everything is symmetric wrt sign and transposition, + * so move to first octant (gx>=0, gy>=0, gx>=gy) to + * avoid handling all possible edge directions. + */ + gx = fabs(gx); + gy = fabs(gy); + if(gx 1.0) a = 1.0; + if(a < 0.0) a = 0.0; // Clip grayscale values outside the range [0,1] + if(a == 0.0) return 1000000.0; // Not an object pixel, return "very far" ("don't know yet") + + dx = (double)xi; + dy = (double)yi; + di = sqrt(dx*dx + dy*dy); // Length of integer vector, like a traditional EDT + if(di==0) { // Use local gradient only at edges + // Estimate based on local gradient only + df = edgedf(gx, gy, a); + } else { + // Estimate gradient based on direction to edge (accurate for large di) + df = edgedf(dx, dy, a); + } + return di + df; // Same metric as edtaa2, except at edges (where di=0) +} + +// Shorthand macro: add ubiquitous parameters dist, gx, gy, img and w and call distaa3() +#define DISTAA(c,xc,yc,xi,yi) (distaa3(img, gx, gy, w, c, xc, yc, xi, yi)) + +void edtaa3(double *img, double *gx, double *gy, int w, int h, short *distx, short *disty, double *dist) +{ + int x, y, i, c; + int offset_u, offset_ur, offset_r, offset_rd, + offset_d, offset_dl, offset_l, offset_lu; + double olddist, newdist; + int cdistx, cdisty, newdistx, newdisty; + int changed; + double epsilon = 1e-3; + + /* Initialize index offsets for the current image width */ + offset_u = -w; + offset_ur = -w+1; + offset_r = 1; + offset_rd = w+1; + offset_d = w; + offset_dl = w-1; + offset_l = -1; + offset_lu = -w-1; + + /* Initialize the distance images */ + for(i=0; i 0) // If non-zero distance or not set yet + { + c = i + offset_u; // Index of candidate for testing + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx; + newdisty = cdisty+1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_ur; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx-1; + newdisty = cdisty+1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + changed = 1; + } + } + i++; + + /* Middle pixels have all neighbors */ + for(x=1; x 0) // If not already zero distance + { + c = i+offset_l; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx+1; + newdisty = cdisty; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_lu; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx+1; + newdisty = cdisty+1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_u; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx; + newdisty = cdisty+1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + changed = 1; + } + } + + /* Move index to second rightmost pixel of current row. */ + /* Rightmost pixel is skipped, it has no right neighbor. */ + i = y*w + w-2; + + /* scan left, propagate distance from right */ + for(x=w-2; x>=0; x--, i--) + { + olddist = dist[i]; + if(olddist <= 0) continue; // Already zero distance + + c = i+offset_r; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx-1; + newdisty = cdisty; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + changed = 1; + } + } + } + + /* Scan rows in reverse order, except last row */ + for(y=h-2; y>=0; y--) + { + /* move index to rightmost pixel of current row */ + i = y*w + w-1; + + /* Scan left, propagate distances from below & right */ + + /* Rightmost pixel is special, has no right neighbors */ + olddist = dist[i]; + if(olddist > 0) // If not already zero distance + { + c = i+offset_d; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx; + newdisty = cdisty-1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_dl; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx+1; + newdisty = cdisty-1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + changed = 1; + } + } + i--; + + /* Middle pixels have all neighbors */ + for(x=w-2; x>0; x--, i--) + { + olddist = dist[i]; + if(olddist <= 0) continue; // Already zero distance + + c = i+offset_r; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx-1; + newdisty = cdisty; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_rd; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx-1; + newdisty = cdisty-1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_d; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx; + newdisty = cdisty-1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_dl; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx+1; + newdisty = cdisty-1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + changed = 1; + } + } + /* Leftmost pixel is special, has no left neighbors */ + olddist = dist[i]; + if(olddist > 0) // If not already zero distance + { + c = i+offset_r; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx-1; + newdisty = cdisty; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_rd; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx-1; + newdisty = cdisty-1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + olddist=newdist; + changed = 1; + } + + c = i+offset_d; + cdistx = distx[c]; + cdisty = disty[c]; + newdistx = cdistx; + newdisty = cdisty-1; + newdist = DISTAA(c, cdistx, cdisty, newdistx, newdisty); + if(newdist < olddist-epsilon) + { + distx[i]=newdistx; + disty[i]=newdisty; + dist[i]=newdist; + changed = 1; + } + } + + /* Move index to second leftmost pixel of current row. */ + /* Leftmost pixel is skipped, it has no left neighbor. */ + i = y*w + 1; + for(x=1; x +# endif +#endif +#include +#include +#include +#include +#include "font-manager.h" + +// ------------------------------------------------------------ file_exists --- +static int +file_exists( const char * filename ) +{ + FILE * file = fopen( filename, "r" ); + if ( file ) + { + fclose(file); + return 1; + } + return 0; +} + + +// ------------------------------------------------------- font_manager_new --- +font_manager_t * +font_manager_new( size_t width, size_t height, size_t depth ) +{ + font_manager_t *self; + texture_atlas_t *atlas = texture_atlas_new( width, height, depth ); + self = (font_manager_t *) malloc( sizeof(font_manager_t) ); + if( !self ) + { + fprintf( stderr, + "line %d: No more memory for allocating data\n", __LINE__ ); + exit( EXIT_FAILURE ); + } + self->atlas = atlas; + self->fonts = vector_new( sizeof(texture_font_t *) ); + self->cache = strdup( " " ); + return self; +} + + +// ---------------------------------------------------- font_manager_delete --- +void +font_manager_delete( font_manager_t * self ) +{ + size_t i; + texture_font_t *font; + assert( self ); + + for( i=0; ifonts ); ++i) + { + font = *(texture_font_t **) vector_get( self->fonts, i ); + texture_font_delete( font ); + } + vector_delete( self->fonts ); + texture_atlas_delete( self->atlas ); + if( self->cache ) + { + free( self->cache ); + } + free( self ); +} + + + +// ----------------------------------------------- font_manager_delete_font --- +void +font_manager_delete_font( font_manager_t * self, + texture_font_t * font) +{ + size_t i; + texture_font_t *other; + + assert( self ); + assert( font ); + + for( i=0; ifonts->size;++i ) + { + other = (texture_font_t *) vector_get( self->fonts, i ); + if ( (strcmp(font->filename, other->filename) == 0) + && ( font->size == other->size) ) + { + vector_erase( self->fonts, i); + break; + } + } + texture_font_delete( font ); +} + + + +// ----------------------------------------- font_manager_get_from_filename --- +texture_font_t * +font_manager_get_from_filename( font_manager_t *self, + const char * filename, + const float size ) +{ + size_t i; + texture_font_t *font; + + assert( self ); + for( i=0; ifonts); ++i ) + { + font = * (texture_font_t **) vector_get( self->fonts, i ); + if( (strcmp(font->filename, filename) == 0) && ( font->size == size) ) + { + return font; + } + } + font = texture_font_new_from_file( self->atlas, size, filename ); + if( font ) + { + vector_push_back( self->fonts, &font ); + texture_font_load_glyphs( font, self->cache ); + return font; + } + fprintf( stderr, "Unable to load \"%s\" (size=%.1f)\n", filename, size ); + return 0; +} + + +// ----------------------------------------- font_manager_get_from_description --- +texture_font_t * +font_manager_get_from_description( font_manager_t *self, + const char * family, + const float size, + const int bold, + const int italic ) +{ + texture_font_t *font; + char *filename = 0; + + assert( self ); + + if( file_exists( family ) ) + { + filename = strdup( family ); + } + else + { +#if defined(_WIN32) || defined(_WIN64) + fprintf( stderr, "\"font_manager_get_from_description\" not implemented yet.\n" ); + return 0; +#endif + filename = font_manager_match_description( self, family, size, bold, italic ); + if( !filename ) + { + fprintf( stderr, "No \"%s (size=%.1f, bold=%d, italic=%d)\" font available.\n", + family, size, bold, italic ); + return 0; + } + } + font = font_manager_get_from_filename( self, filename, size ); + + free( filename ); + return font; +} + +// ------------------------------------------- font_manager_get_from_markup --- +texture_font_t * +font_manager_get_from_markup( font_manager_t *self, + const markup_t *markup ) +{ + assert( self ); + assert( markup ); + + return font_manager_get_from_description( self, markup->family, markup->size, + markup->bold, markup->italic ); +} + +// ----------------------------------------- font_manager_match_description --- +char * +font_manager_match_description( font_manager_t * self, + const char * family, + const float size, + const int bold, + const int italic ) +{ +// Use of fontconfig is disabled by default. +#if 1 + return 0; +#else +# if defined _WIN32 || defined _WIN64 + fprintf( stderr, "\"font_manager_match_description\" not implemented for windows.\n" ); + return 0; +# endif + char *filename = 0; + int weight = FC_WEIGHT_REGULAR; + int slant = FC_SLANT_ROMAN; + if ( bold ) + { + weight = FC_WEIGHT_BOLD; + } + if( italic ) + { + slant = FC_SLANT_ITALIC; + } + FcInit(); + FcPattern *pattern = FcPatternCreate(); + FcPatternAddDouble( pattern, FC_SIZE, size ); + FcPatternAddInteger( pattern, FC_WEIGHT, weight ); + FcPatternAddInteger( pattern, FC_SLANT, slant ); + FcPatternAddString( pattern, FC_FAMILY, (FcChar8*) family ); + FcConfigSubstitute( 0, pattern, FcMatchPattern ); + FcDefaultSubstitute( pattern ); + FcResult result; + FcPattern *match = FcFontMatch( 0, pattern, &result ); + FcPatternDestroy( pattern ); + + if ( !match ) + { + fprintf( stderr, "fontconfig error: could not match family '%s'", family ); + return 0; + } + else + { + FcValue value; + FcResult result = FcPatternGet( match, FC_FILE, 0, &value ); + if ( result ) + { + fprintf( stderr, "fontconfig error: could not match family '%s'", family ); + } + else + { + filename = strdup( (char *)(value.u.s) ); + } + } + FcPatternDestroy( match ); + return filename; +#endif +} diff --git a/src/freetype-gl/font-manager.h b/src/freetype-gl/font-manager.h new file mode 100644 index 00000000..c975e650 --- /dev/null +++ b/src/freetype-gl/font-manager.h @@ -0,0 +1,181 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __FONT_MANAGER_H__ +#define __FONT_MANAGER_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "vector.h" +#include "markup.h" +#include "texture-font.h" +#include "texture-atlas.h" + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * @file font-manager.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup font-manager Font manager + * + * Structure in charge of caching fonts. + * + * Example Usage: + * @code + * #include "font-manager.h" + * + * int main( int arrgc, char *argv[] ) + * { + * font_manager_t * manager = manager_new( 512, 512, 1 ); + * texture_font_t * font = font_manager_get( manager, "Mono", 12, 0, 0 ); + * + * return 0; + * } + * @endcode + * + * @{ + */ + + +/** + * Structure in charge of caching fonts. + */ +typedef struct font_manager_t { + /** + * Texture atlas to hold font glyphs. + */ + texture_atlas_t * atlas; + + /** + * Cached textures. + */ + vector_t * fonts; + + /** + * Default glyphs to be loaded when loading a new font. + */ + char * cache; + +} font_manager_t; + + + +/** + * Creates a new empty font manager. + * + * @param width width of the underlying atlas + * @param height height of the underlying atlas + * @param depth bit depth of the underlying atlas + * + * @return a new font manager. + * + */ + font_manager_t * + font_manager_new( size_t width, + size_t height, + size_t depth ); + + +/** + * Deletes a font manager. + * + * @param self a font manager. + */ + void + font_manager_delete( font_manager_t *self ); + + +/** + * Deletes a font from the font manager. + * + * Note that font glyphs are not removed from the atlas. + * + * @param self a font manager. + * @param font font to be deleted + * + */ + void + font_manager_delete_font( font_manager_t * self, + texture_font_t * font ); + + +/** + * Request for a font based on a filename. + * + * @param self a font manager. + * @param filename font filename + * @param size font size + * + * @return Requested font + */ + texture_font_t * + font_manager_get_from_filename( font_manager_t * self, + const char * filename, + const float size ); + + +/** + * Request for a font based on a description + * + * @param self a font manager + * @param family font family + * @param size font size + * @param bold whether font is bold + * @param italic whether font is italic + * + * @return Requested font + */ + texture_font_t * + font_manager_get_from_description( font_manager_t * self, + const char * family, + const float size, + const int bold, + const int italic ); + + +/** + * Request for a font based on a markup + * + * @param self a font manager + * @param markup Markup describing a font + * + * @return Requested font + */ + texture_font_t * + font_manager_get_from_markup( font_manager_t *self, + const markup_t *markup ); + + +/** + * Search for a font filename that match description. + * + * @param self a font manager + * @param family font family + * @param size font size + * @param bold whether font is bold + * @param italic whether font is italic + * + * @return Requested font filename + */ + char * + font_manager_match_description( font_manager_t * self, + const char * family, + const float size, + const int bold, + const int italic ); + +/** @} */ + +#ifdef __cplusplus +} +} +#endif // ifdef __cplusplus + +#endif /* __FONT_MANAGER_H__ */ diff --git a/src/freetype-gl/freetype-gl.h b/src/freetype-gl/freetype-gl.h new file mode 100644 index 00000000..f6fe1deb --- /dev/null +++ b/src/freetype-gl/freetype-gl.h @@ -0,0 +1,22 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __FREETYPE_GL_H__ +#define __FREETYPE_GL_H__ + +/* Mandatory */ +#include "opengl.h" +#include "vec234.h" +#include "vector.h" +#include "texture-atlas.h" +#include "texture-font.h" + +#ifdef __cplusplus +#ifndef NOT_USING_FT_GL_NAMESPACE +using namespace ftgl; +#endif /* NOT_USING_FT_GL_NAMESPACE */ +#endif /* __cplusplus */ + +#endif /* FREETYPE_GL_H */ diff --git a/src/freetype-gl/markup.h b/src/freetype-gl/markup.h new file mode 100644 index 00000000..bf630fda --- /dev/null +++ b/src/freetype-gl/markup.h @@ -0,0 +1,165 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __MARKUP_H__ +#define __MARKUP_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "texture-font.h" +#include "vec234.h" + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * @file markup.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup markup Markup + * + * Simple structure that describes text properties. + * + * Example Usage: + * @code + * #include "markup.h" + * + * ... + * + * vec4 black = {{0.0, 0.0, 0.0, 1.0}}; + * vec4 white = {{1.0, 1.0, 1.0, 1.0}}; + * vec4 none = {{1.0, 1.0, 1.0, 0.0}}; + * + * markup_t normal = { + * .family = "Droid Serif", + * .size = 24.0, + * .bold = 0, + * .italic = 0, + * .spacing = 1.0, + * .gamma = 1.0, + * .foreground_color = black, .background_color = none, + * .underline = 0, .underline_color = black, + * .overline = 0, .overline_color = black, + * .strikethrough = 0, .strikethrough_color = black, + * .font = 0, + * }; + * + * ... + * + * @endcode + * + * @{ + */ + + +/** + * Simple structure that describes text properties. + */ +typedef struct markup_t +{ + /** + * A font family name such as "normal", "sans", "serif" or "monospace". + */ + char * family; + + /** + * Font size. + */ + float size; + + /** + * Whether text is bold. + */ + int bold; + + /** + * Whether text is italic. + */ + int italic; + + /** + * Spacing between letters. + */ + float spacing; + + /** + * Gamma correction. + */ + float gamma; + + /** + * Text color. + */ + vec4 foreground_color; + + /** + * Background color. + */ + vec4 background_color; + + /** + * Whether outline is active. + */ + int outline; + + /** + * Outline color. + */ + vec4 outline_color; + + /** + * Whether underline is active. + */ + int underline; + + /** + * Underline color. + */ + vec4 underline_color; + + /** + * Whether overline is active. + */ + int overline; + + /** + * Overline color. + */ + vec4 overline_color; + + /** + * Whether strikethrough is active. + */ + int strikethrough; + + /** + * Strikethrough color. + */ + vec4 strikethrough_color; + + /** + * Pointer on the corresponding font (family/size/bold/italic) + */ + texture_font_t * font; + +} markup_t; + +/** + * Default markup + */ +extern markup_t default_markup; + + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* __MARKUP_H__ */ diff --git a/src/freetype-gl/mat4.c b/src/freetype-gl/mat4.c new file mode 100644 index 00000000..7a986fa5 --- /dev/null +++ b/src/freetype-gl/mat4.c @@ -0,0 +1,245 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include "mat4.h" + +mat4 * +mat4_new( void ) +{ + mat4 *self = (mat4 *) malloc( sizeof(mat4) ); + return self; + +} + +void +mat4_set_zero( mat4 *self ) +{ + if (!self) + return; + + memset( self, 0, sizeof( mat4 )); +} + +void +mat4_set_identity( mat4 *self ) +{ + if (!self) + return; + + memset( self, 0, sizeof( mat4 )); + self->m00 = 1.0; + self->m11 = 1.0; + self->m22 = 1.0; + self->m33 = 1.0; +} + +void +mat4_multiply( mat4 *self, mat4 *other ) +{ + mat4 m; + size_t i; + + if (!self || !other) + return; + + for( i=0; i<4; ++i ) + { + m.data[i*4+0] = + (self->data[i*4+0] * other->data[0*4+0]) + + (self->data[i*4+1] * other->data[1*4+0]) + + (self->data[i*4+2] * other->data[2*4+0]) + + (self->data[i*4+3] * other->data[3*4+0]) ; + + m.data[i*4+1] = + (self->data[i*4+0] * other->data[0*4+1]) + + (self->data[i*4+1] * other->data[1*4+1]) + + (self->data[i*4+2] * other->data[2*4+1]) + + (self->data[i*4+3] * other->data[3*4+1]) ; + + m.data[i*4+2] = + (self->data[i*4+0] * other->data[0*4+2]) + + (self->data[i*4+1] * other->data[1*4+2]) + + (self->data[i*4+2] * other->data[2*4+2]) + + (self->data[i*4+3] * other->data[3*4+2]) ; + + m.data[i*4+3] = + (self->data[i*4+0] * other->data[0*4+3]) + + (self->data[i*4+1] * other->data[1*4+3]) + + (self->data[i*4+2] * other->data[2*4+3]) + + (self->data[i*4+3] * other->data[3*4+3]) ; + } + memcpy( self, &m, sizeof( mat4 ) ); + +} + + +void +mat4_set_orthographic( mat4 *self, + float left, float right, + float bottom, float top, + float znear, float zfar ) +{ + if (!self) + return; + + if (left == right || bottom == top || znear == zfar) + return; + + mat4_set_zero( self ); + + self->m00 = +2.0f/(right-left); + self->m30 = -(right+left)/(right-left); + self->m11 = +2.0f/(top-bottom); + self->m31 = -(top+bottom)/(top-bottom); + self->m22 = -2.0f/(zfar-znear); + self->m32 = -(zfar+znear)/(zfar-znear); + self->m33 = 1.0f; +} + +void +mat4_set_perspective( mat4 *self, + float fovy, float aspect, + float znear, float zfar) +{ + float h, w; + + if (!self) + return; + + if (znear == zfar) + return; + + h = (float)tan(fovy / 360.0 * M_PI) * znear; + w = h * aspect; + + mat4_set_frustum( self, -w, w, -h, h, znear, zfar ); +} + +void +mat4_set_frustum( mat4 *self, + float left, float right, + float bottom, float top, + float znear, float zfar ) +{ + + if (!self) + return; + + if (left == right || bottom == top || znear == zfar) + return; + + mat4_set_zero( self ); + + self->m00 = (2.0f*znear)/(right-left); + self->m20 = (right+left)/(right-left); + + self->m11 = (2.0f*znear)/(top-bottom); + self->m21 = (top+bottom)/(top-bottom); + + self->m22 = -(zfar+znear)/(zfar-znear); + self->m32 = -(2.0f*zfar*znear)/(zfar-znear); + + self->m23 = -1.0f; +} + +void +mat4_set_rotation( mat4 *self, + float angle, + float x, float y, float z) +{ + float c, s, norm; + + if (!self) + return; + + c = (float)cos( M_PI*angle/180.0 ); + s = (float)sin( M_PI*angle/180.0 ); + norm = (float)sqrt(x*x+y*y+z*z); + + x /= norm; y /= norm; z /= norm; + + mat4_set_identity( self ); + + self->m00 = x*x*(1-c)+c; + self->m10 = y*x*(1-c)-z*s; + self->m20 = z*x*(1-c)+y*s; + + self->m01 = x*y*(1-c)+z*s; + self->m11 = y*y*(1-c)+c; + self->m21 = z*y*(1-c)-x*s; + + self->m02 = x*z*(1-c)-y*s; + self->m12 = y*z*(1-c)+x*s; + self->m22 = z*z*(1-c)+c; +} + +void +mat4_set_translation( mat4 *self, + float x, float y, float z) +{ + if (!self) + return; + + mat4_set_identity( self ); + self-> m30 = x; + self-> m31 = y; + self-> m32 = z; +} + +void +mat4_set_scaling( mat4 *self, + float x, float y, float z) +{ + if (!self) + return; + + mat4_set_identity( self ); + self-> m00 = x; + self-> m11 = y; + self-> m22 = z; +} + +void +mat4_rotate( mat4 *self, + float angle, + float x, float y, float z) +{ + mat4 m; + + if (!self) + return; + + mat4_set_rotation( &m, angle, x, y, z); + mat4_multiply( self, &m ); +} + +void +mat4_translate( mat4 *self, + float x, float y, float z) +{ + mat4 m; + + if (!self) + return; + + mat4_set_translation( &m, x, y, z); + mat4_multiply( self, &m ); +} + +void +mat4_scale( mat4 *self, + float x, float y, float z) +{ + mat4 m; + + if (!self) + return; + + mat4_set_scaling( &m, x, y, z); + mat4_multiply( self, &m ); +} diff --git a/src/freetype-gl/mat4.h b/src/freetype-gl/mat4.h new file mode 100644 index 00000000..83d6f305 --- /dev/null +++ b/src/freetype-gl/mat4.h @@ -0,0 +1,91 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __MAT4_H__ +#define __MAT4_H__ + +#ifdef __cplusplus +extern "C" { +namespace ftgl { +#endif + + +/** + * + */ +typedef union +{ + float data[16]; /**< All compoments at once */ + struct { + float m00, m01, m02, m03; + float m10, m11, m12, m13; + float m20, m21, m22, m23; + float m30, m31, m32, m33; + }; +} mat4; + + +mat4 * +mat4_new( void ); + +void +mat4_set_identity( mat4 *self ); + +void +mat4_set_zero( mat4 *self ); + +void +mat4_multiply( mat4 *self, mat4 *other ); + +void +mat4_set_orthographic( mat4 *self, + float left, float right, + float bottom, float top, + float znear, float zfar ); + +void +mat4_set_perspective( mat4 *self, + float fovy, float aspect, + float zNear, float zFar); + +void +mat4_set_frustum( mat4 *self, + float left, float right, + float bottom, float top, + float znear, float zfar ); + +void +mat4_set_rotation( mat4 *self, + float angle, + float x, float y, float z); + +void +mat4_set_translation( mat4 *self, + float x, float y, float z); + +void +mat4_set_scaling( mat4 *self, + float x, float y, float z); + +void +mat4_rotate( mat4 *self, + float angle, + float x, float y, float z); + +void +mat4_translate( mat4 *self, + float x, float y, float z); + +void +mat4_scale( mat4 *self, + float x, float y, float z); + + +#ifdef __cplusplus +} +} +#endif + +#endif /* __MAT4_H__ */ diff --git a/src/freetype-gl/opengl.h b/src/freetype-gl/opengl.h new file mode 100644 index 00000000..7ba7e185 --- /dev/null +++ b/src/freetype-gl/opengl.h @@ -0,0 +1,28 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __OPEN_GL_H__ +#define __OPEN_GL_H__ + +#if defined(__APPLE__) +# include "TargetConditionals.h" +# if TARGET_OS_SIMULATOR || TARGET_OS_IPHONE +# if defined(FREETYPE_GL_ES_VERSION_3_0) +# include +# else +# include +# endif +# else +# include +# endif +#elif defined(_WIN32) || defined(_WIN64) +# include +# include +#else +# include +# include +#endif + +#endif /* OPEN_GL_H */ diff --git a/src/freetype-gl/platform.c b/src/freetype-gl/platform.c new file mode 100644 index 00000000..5932a539 --- /dev/null +++ b/src/freetype-gl/platform.c @@ -0,0 +1,32 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include "platform.h" + +#if defined(_WIN32) || defined(_WIN64) + +#include + +// strndup() is not available on Windows +char *strndup( const char *s1, size_t n) +{ + char *copy= (char*)malloc( n+1 ); + memcpy( copy, s1, n ); + copy[n] = 0; + return copy; +}; +#endif + + +// strndup() was only added in OSX lion +#if defined(__APPLE__) +char *strndup( const char *s1, size_t n) +{ + char *copy = calloc( n+1, sizeof(char) ); + memcpy( copy, s1, n ); + return copy; +}; +#endif diff --git a/src/freetype-gl/platform.h b/src/freetype-gl/platform.h new file mode 100644 index 00000000..79091263 --- /dev/null +++ b/src/freetype-gl/platform.h @@ -0,0 +1,30 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __PLATFORM_H__ +#define __PLATFORM_H__ + +#include + +#ifdef __cplusplus +extern "C" { +namespace ftgl { +#endif + +#ifdef __APPLE__ + /* strndup() was only added in OSX lion */ + char * strndup( const char *s1, size_t n); +#elif defined(_WIN32) || defined(_WIN64) + /* does not exist on windows */ + char * strndup( const char *s1, size_t n); +# pragma warning (disable: 4244) // suspend warnings +#endif // _WIN32 || _WIN64 + +#ifdef __cplusplus +} +} +#endif // __cplusplus + +#endif /* __PLATFORM_H__ */ diff --git a/src/freetype-gl/shader.c b/src/freetype-gl/shader.c new file mode 100644 index 00000000..27d19f2a --- /dev/null +++ b/src/freetype-gl/shader.c @@ -0,0 +1,95 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include "opengl.h" +#include "shader.h" + + +// ------------------------------------------------------------ shader_read --- +char * +shader_read( const char *filename ) +{ + FILE * file; + char * buffer; + size_t size; + + file = fopen( filename, "rb" ); + if( !file ) + { + fprintf( stderr, "Unable to open file \"%s\".\n", filename ); + return 0; + } + fseek( file, 0, SEEK_END ); + size = ftell( file ); + fseek(file, 0, SEEK_SET ); + buffer = (char *) malloc( (size+1) * sizeof( char *) ); + fread( buffer, sizeof(char), size, file ); + buffer[size] = 0; + fclose( file ); + return buffer; +} + +// --------------------------------------------------------- shader_compile --- +GLuint +shader_compile( const char* source, + const GLenum type ) +{ + GLint compile_status; + GLuint handle = glCreateShader( type ); + glShaderSource( handle, 1, &source, 0 ); + glCompileShader( handle ); + glGetShaderiv( handle, GL_COMPILE_STATUS, &compile_status ); + if( compile_status == GL_FALSE ) + { + GLchar messages[256]; + glGetShaderInfoLog( handle, sizeof(messages), 0, &messages[0] ); + fprintf( stderr, "%s\n", messages ); + exit( EXIT_FAILURE ); + } + return handle; +} + + +// ------------------------------------------------------------ shader_load --- + +GLuint +shader_load( const char * vert_filename, + const char * frag_filename ) +{ + GLuint handle = glCreateProgram( ); + GLint link_status; + + if( vert_filename && strlen( vert_filename ) ) + { + char *vert_source = shader_read( vert_filename ); + GLuint vert_shader = shader_compile( vert_source, GL_VERTEX_SHADER); + glAttachShader( handle, vert_shader); + glDeleteShader( vert_shader ); + free( vert_source ); + } + if( frag_filename && strlen( frag_filename ) ) + { + char *frag_source = shader_read( frag_filename ); + GLuint frag_shader = shader_compile( frag_source, GL_FRAGMENT_SHADER); + glAttachShader( handle, frag_shader); + glDeleteShader( frag_shader ); + free( frag_source ); + } + + glLinkProgram( handle ); + + glGetProgramiv( handle, GL_LINK_STATUS, &link_status ); + if (link_status == GL_FALSE) + { + GLchar messages[256]; + glGetProgramInfoLog( handle, sizeof(messages), 0, &messages[0] ); + fprintf( stderr, "%s\n", messages ); + exit(1); + } + return handle; +} diff --git a/src/freetype-gl/shader.h b/src/freetype-gl/shader.h new file mode 100644 index 00000000..5519621f --- /dev/null +++ b/src/freetype-gl/shader.h @@ -0,0 +1,86 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __SHADER_H__ +#define __SHADER_H__ + +#include "opengl.h" + +#ifdef __cplusplus +extern "C" { +namespace ftgl { +#endif + +/** + * @file shader.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup shader Shader + * + * Simple functions for loading/building a shader from sources. + * + * Example Usage: + * @code + * #include "shader.h" + * + * int main( int arrgc, char *argv[] ) + * { + * GLuint shader = shader_load("shader.vert", "shader.frag"); + * + * return 0; + * } + * @endcode + * + * @{ + */ + +/** + * Read a fragment or vertex shader from a file + * + * @param filename file to read shader from + * @return a newly-allocated text buffer containing code. This buffer + * must be freed after usage. + * + */ + char * + shader_read( const char *filename ); + + +/** + * Compile a shader from a text buffer. + * + * @param source code of the shader + * @param type type of the shader + * + * @return a handle on the compiled program + * + */ + GLuint + shader_compile( const char* source, + const GLenum type ); + + +/** + * Load a vertex and fragment shader sources and build program + * + * @param vert_filename vertex shader filename + * @param frag_filename fragment shader filename + * + * @return a handle on the built program + * + */ + GLuint + shader_load( const char * vert_filename, + const char * frag_filename ); + + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* __SHADER_H__ */ diff --git a/src/freetype-gl/text-buffer.c b/src/freetype-gl/text-buffer.c new file mode 100644 index 00000000..78b329fb --- /dev/null +++ b/src/freetype-gl/text-buffer.c @@ -0,0 +1,540 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include +#include +#include +#include "opengl.h" +#include "text-buffer.h" +#include "utf8-utils.h" + +#define SET_GLYPH_VERTEX(value,x0,y0,z0,s0,t0,r,g,b,a,sh,gm) { \ + glyph_vertex_t *gv=&value; \ + gv->x=x0; gv->y=y0; gv->z=z0; \ + gv->u=s0; gv->v=t0; \ + gv->r=r; gv->g=g; gv->b=b; gv->a=a; \ + gv->shift=sh; gv->gamma=gm;} + +// ---------------------------------------------------------------------------- + +text_buffer_t * +text_buffer_new( ) +{ + text_buffer_t *self = (text_buffer_t *) malloc (sizeof(text_buffer_t)); + self->buffer = vertex_buffer_new( + "vertex:3f,tex_coord:2f,color:4f,ashift:1f,agamma:1f" ); + self->line_start = 0; + self->line_ascender = 0; + self->base_color.r = 0.0; + self->base_color.g = 0.0; + self->base_color.b = 0.0; + self->base_color.a = 1.0; + self->line_descender = 0; + self->lines = vector_new( sizeof(line_info_t) ); + self->bounds.left = 0.0; + self->bounds.top = 0.0; + self->bounds.width = 0.0; + self->bounds.height = 0.0; + return self; +} + +// ---------------------------------------------------------------------------- +void +text_buffer_delete( text_buffer_t * self ) +{ + vector_delete( self->lines ); + vertex_buffer_delete( self->buffer ); + free( self ); +} + +// ---------------------------------------------------------------------------- +void +text_buffer_clear( text_buffer_t * self ) +{ + assert( self ); + + vertex_buffer_clear( self->buffer ); + self->line_start = 0; + self->line_ascender = 0; + self->line_descender = 0; + vector_clear( self->lines ); + self->bounds.left = 0.0; + self->bounds.top = 0.0; + self->bounds.width = 0.0; + self->bounds.height = 0.0; +} + +// ---------------------------------------------------------------------------- +void +text_buffer_printf( text_buffer_t * self, vec2 *pen, ... ) +{ + markup_t *markup; + char *text; + va_list args; + + if( vertex_buffer_size( self->buffer ) == 0 ) + { + self->origin = *pen; + } + + va_start ( args, pen ); + do { + markup = va_arg( args, markup_t * ); + if( markup == NULL ) + { + return; + } + text = va_arg( args, char * ); + text_buffer_add_text( self, pen, markup, text, 0 ); + } while( markup != 0 ); + va_end ( args ); +} + +// ---------------------------------------------------------------------------- +void +text_buffer_move_last_line( text_buffer_t * self, float dy ) +{ + size_t i; + int j; + for( i=self->line_start; i < vector_size( self->buffer->items ); ++i ) + { + ivec4 *item = (ivec4 *) vector_get( self->buffer->items, i); + for( j=item->vstart; jvstart+item->vcount; ++j) + { + glyph_vertex_t * vertex = + (glyph_vertex_t *) vector_get( self->buffer->vertices, j ); + vertex->y -= dy; + } + } +} + + +// ---------------------------------------------------------------------------- +// text_buffer_finish_line (internal use only) +// +// Performs calculations needed at the end of each line of text +// and prepares for the next line if necessary +// +// advancePen: if true, advance the pen to the next line +// +static void +text_buffer_finish_line( text_buffer_t * self, vec2 * pen, bool advancePen ) +{ + float line_left = self->line_left; + float line_right = pen->x; + float line_width = line_right - line_left; + float line_top = pen->y + self->line_ascender; + float line_height = self->line_ascender - self->line_descender; + float line_bottom = line_top - line_height; + + line_info_t line_info; + line_info.line_start = self->line_start; + line_info.bounds.left = line_left; + line_info.bounds.top = line_top; + line_info.bounds.width = line_width; + line_info.bounds.height = line_height; + + vector_push_back( self->lines, &line_info); + + + if (line_left < self->bounds.left) + { + self->bounds.left = line_left; + } + if (line_top > self->bounds.top) + { + self->bounds.top = line_top; + } + + float self_right = self->bounds.left + self->bounds.width; + float self_bottom = self->bounds.top - self->bounds.height; + + if (line_right > self_right) + { + self->bounds.width = line_right - self->bounds.left; + } + if (line_bottom < self_bottom) + { + self->bounds.height = self->bounds.top - line_bottom; + } + + if ( advancePen ) + { + pen->x = self->origin.x; + pen->y += (int)(self->line_descender); + } + + self->line_descender = 0; + self->line_ascender = 0; + self->line_start = vector_size( self->buffer->items ); + self->line_left = pen->x; +} + +// ---------------------------------------------------------------------------- +void +text_buffer_add_text( text_buffer_t * self, + vec2 * pen, markup_t * markup, + const char * text, size_t length ) +{ + size_t i; + const char * prev_character = NULL; + + if( markup == NULL ) + { + return; + } + + if( !markup->font ) + { + fprintf( stderr, "Houston, we've got a problem !\n" ); + return; + } + + if( length == 0 ) + { + length = utf8_strlen(text); + } + if( vertex_buffer_size( self->buffer ) == 0 ) + { + self->origin = *pen; + self->line_left = pen->x; + self->bounds.left = pen->x; + self->bounds.top = pen->y; + } + else + { + if (pen->x < self->origin.x) + { + self->origin.x = pen->x; + } + if (pen->y != self->last_pen_y) + { + text_buffer_finish_line(self, pen, false); + } + } + + for( i = 0; utf8_strlen( text + i ) && length; i += utf8_surrogate_len( text + i ) ) + { + text_buffer_add_char( self, pen, markup, text + i, prev_character ); + prev_character = text + i; + length--; + } + + self->last_pen_y = pen->y; +} + +// ---------------------------------------------------------------------------- +void +text_buffer_add_char( text_buffer_t * self, + vec2 * pen, markup_t * markup, + const char * current, const char * previous ) +{ + size_t vcount = 0; + size_t icount = 0; + vertex_buffer_t * buffer = self->buffer; + texture_font_t * font = markup->font; + float gamma = markup->gamma; + + // Maximum number of vertices is 20 (= 5x2 triangles) per glyph: + // - 2 triangles for background + // - 2 triangles for overline + // - 2 triangles for underline + // - 2 triangles for strikethrough + // - 2 triangles for glyph + glyph_vertex_t vertices[4*5]; + GLuint indices[6*5]; + texture_glyph_t *glyph; + texture_glyph_t *black; + float kerning = 0.0f; + + if( markup->font->ascender > self->line_ascender ) + { + float y = pen->y; + pen->y -= (markup->font->ascender - self->line_ascender); + text_buffer_move_last_line( self, (float)(int)(y-pen->y) ); + self->line_ascender = markup->font->ascender; + } + if( markup->font->descender < self->line_descender ) + { + self->line_descender = markup->font->descender; + } + + if( *current == '\n' ) + { + text_buffer_finish_line(self, pen, true); + return; + } + + glyph = texture_font_get_glyph( font, current ); + black = texture_font_get_glyph( font, NULL ); + + if( glyph == NULL ) + { + return; + } + + if( previous && markup->font->kerning ) + { + kerning = texture_glyph_get_kerning( glyph, previous ); + } + pen->x += kerning; + + // Background + if( markup->background_color.alpha > 0 ) + { + float r = markup->background_color.r; + float g = markup->background_color.g; + float b = markup->background_color.b; + float a = markup->background_color.a; + float x0 = ( pen->x -kerning ); + float y0 = (float)(int)( pen->y + font->descender ); + float x1 = ( x0 + glyph->advance_x ); + float y1 = (float)(int)( y0 + font->height + font->linegap ); + float s0 = black->s0; + float t0 = black->t0; + float s1 = black->s1; + float t1 = black->t1; + + SET_GLYPH_VERTEX(vertices[vcount+0], + (float)(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+1], + (float)(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+2], + (float)(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+3], + (float)(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma ); + indices[icount + 0] = vcount+0; + indices[icount + 1] = vcount+1; + indices[icount + 2] = vcount+2; + indices[icount + 3] = vcount+0; + indices[icount + 4] = vcount+2; + indices[icount + 5] = vcount+3; + vcount += 4; + icount += 6; + } + + // Underline + if( markup->underline ) + { + float r = markup->underline_color.r; + float g = markup->underline_color.g; + float b = markup->underline_color.b; + float a = markup->underline_color.a; + float x0 = ( pen->x - kerning ); + float y0 = (float)(int)( pen->y + font->underline_position ); + float x1 = ( x0 + glyph->advance_x ); + float y1 = (float)(int)( y0 + font->underline_thickness ); + float s0 = black->s0; + float t0 = black->t0; + float s1 = black->s1; + float t1 = black->t1; + + SET_GLYPH_VERTEX(vertices[vcount+0], + (float)(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+1], + (float)(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+2], + (float)(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+3], + (float)(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma ); + indices[icount + 0] = vcount+0; + indices[icount + 1] = vcount+1; + indices[icount + 2] = vcount+2; + indices[icount + 3] = vcount+0; + indices[icount + 4] = vcount+2; + indices[icount + 5] = vcount+3; + vcount += 4; + icount += 6; + } + + // Overline + if( markup->overline ) + { + float r = markup->overline_color.r; + float g = markup->overline_color.g; + float b = markup->overline_color.b; + float a = markup->overline_color.a; + float x0 = ( pen->x -kerning ); + float y0 = (float)(int)( pen->y + (int)font->ascender ); + float x1 = ( x0 + glyph->advance_x ); + float y1 = (float)(int)( y0 + (int)font->underline_thickness ); + float s0 = black->s0; + float t0 = black->t0; + float s1 = black->s1; + float t1 = black->t1; + SET_GLYPH_VERTEX(vertices[vcount+0], + (float)(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+1], + (float)(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+2], + (float)(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+3], + (float)(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma ); + indices[icount + 0] = vcount+0; + indices[icount + 1] = vcount+1; + indices[icount + 2] = vcount+2; + indices[icount + 3] = vcount+0; + indices[icount + 4] = vcount+2; + indices[icount + 5] = vcount+3; + vcount += 4; + icount += 6; + } + + /* Strikethrough */ + if( markup->strikethrough ) + { + float r = markup->strikethrough_color.r; + float g = markup->strikethrough_color.g; + float b = markup->strikethrough_color.b; + float a = markup->strikethrough_color.a; + float x0 = ( pen->x -kerning ); + float y0 = (float)(int)( pen->y + (int)font->ascender*.33f); + float x1 = ( x0 + glyph->advance_x ); + float y1 = (float)(int)( y0 + (int)font->underline_thickness ); + float s0 = black->s0; + float t0 = black->t0; + float s1 = black->s1; + float t1 = black->t1; + SET_GLYPH_VERTEX(vertices[vcount+0], + (float)(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+1], + (float)(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+2], + (float)(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+3], + (float)(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma ); + indices[icount + 0] = vcount+0; + indices[icount + 1] = vcount+1; + indices[icount + 2] = vcount+2; + indices[icount + 3] = vcount+0; + indices[icount + 4] = vcount+2; + indices[icount + 5] = vcount+3; + vcount += 4; + icount += 6; + } + { + // Actual glyph + float r = markup->foreground_color.red; + float g = markup->foreground_color.green; + float b = markup->foreground_color.blue; + float a = markup->foreground_color.alpha; + float x0 = ( pen->x + glyph->offset_x ); + float y0 = (float)(int)( pen->y + glyph->offset_y ); + float x1 = ( x0 + glyph->width ); + float y1 = (float)(int)( y0 - glyph->height ); + float s0 = glyph->s0; + float t0 = glyph->t0; + float s1 = glyph->s1; + float t1 = glyph->t1; + + SET_GLYPH_VERTEX(vertices[vcount+0], + (float)(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+1], + (float)(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+2], + (float)(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma ); + SET_GLYPH_VERTEX(vertices[vcount+3], + (float)(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma ); + indices[icount + 0] = vcount+0; + indices[icount + 1] = vcount+1; + indices[icount + 2] = vcount+2; + indices[icount + 3] = vcount+0; + indices[icount + 4] = vcount+2; + indices[icount + 5] = vcount+3; + vcount += 4; + icount += 6; + + vertex_buffer_push_back( buffer, vertices, vcount, indices, icount ); + pen->x += glyph->advance_x * (1.0f + markup->spacing); + } +} + +// ---------------------------------------------------------------------------- +void +text_buffer_align( text_buffer_t * self, vec2 * pen, + enum Align alignment ) +{ + if (ALIGN_LEFT == alignment) + { + return; + } + + size_t total_items = vector_size( self->buffer->items ); + if ( self->line_start != total_items ) + { + text_buffer_finish_line( self, pen, false ); + } + + + size_t i, j; + int k; + float self_left, self_right, self_center; + float line_left, line_right, line_center; + float dx; + + self_left = self->bounds.left; + self_right = self->bounds.left + self->bounds.width; + self_center = (self_left + self_right) / 2; + + line_info_t* line_info; + size_t lines_count, line_end; + + lines_count = vector_size( self->lines ); + for ( i = 0; i < lines_count; ++i ) + { + line_info = (line_info_t*)vector_get( self->lines, i ); + + if ( i + 1 < lines_count ) + { + line_end = ((line_info_t*)vector_get( self->lines, i + 1 ))->line_start; + } + else + { + line_end = vector_size( self->buffer->items ); + } + + line_right = line_info->bounds.left + line_info->bounds.width; + + if ( ALIGN_RIGHT == alignment ) + { + dx = self_right - line_right; + } + else // ALIGN_CENTER + { + line_left = line_info->bounds.left; + line_center = (line_left + line_right) / 2; + dx = self_center - line_center; + } + + dx = roundf( dx ); + + for( j=line_info->line_start; j < line_end; ++j ) + { + ivec4 *item = (ivec4 *) vector_get( self->buffer->items, j); + for( k=item->vstart; kvstart+item->vcount; ++k) + { + glyph_vertex_t * vertex = + (glyph_vertex_t *)vector_get( self->buffer->vertices, k ); + vertex->x += dx; + } + } + + } +} + +vec4 +text_buffer_get_bounds( text_buffer_t * self, vec2 * pen ) +{ + size_t total_items = vector_size( self->buffer->items ); + if ( self->line_start != total_items ) + { + text_buffer_finish_line( self, pen, false ); + } + + return self->bounds; +} diff --git a/src/freetype-gl/text-buffer.h b/src/freetype-gl/text-buffer.h new file mode 100644 index 00000000..90701236 --- /dev/null +++ b/src/freetype-gl/text-buffer.h @@ -0,0 +1,305 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __TEXT_BUFFER_H__ +#define __TEXT_BUFFER_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "vertex-buffer.h" +#include "markup.h" + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * Use LCD filtering + */ +#define LCD_FILTERING_ON 3 + +/** + * Do not use LCD filtering + */ +#define LCD_FILTERING_OFF 1 + +/** + * @file text-buffer.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup text-buffer Text buffer + * + * + * Example Usage: + * @code + * + * int main( int arrgc, char *argv[] ) + * { + * + * return 0; + * } + * @endcode + * + * @{ + */ + +/** + * Text buffer structure + */ +typedef struct text_buffer_t { + /** + * Vertex buffer + */ + vertex_buffer_t *buffer; + + /** + * Base color for text + */ + vec4 base_color; + + + /** + * Pen origin + */ + vec2 origin; + + /** + * Last pen y location + */ + float last_pen_y; + + /** + * Total bounds + */ + vec4 bounds; + + /** + * Index (in the vertex buffer) of the current line start + */ + size_t line_start; + + /** + * Location of the start of the line + */ + float line_left; + + /** + * Vector of line information + */ + vector_t * lines; + + /** + * Current line ascender + */ + float line_ascender; + + /** + * Current line decender + */ + float line_descender; +} text_buffer_t; + + + +/** + * Glyph vertex structure + */ +typedef struct glyph_vertex_t { + /** + * Vertex x coordinates + */ + float x; + + /** + * Vertex y coordinates + */ + float y; + + /** + * Vertex z coordinates + */ + float z; + + /** + * Texture first coordinate + */ + float u; + + /** + * Texture second coordinate + */ + float v; + + /** + * Color red component + */ + float r; + + /** + * Color green component + */ + float g; + + /** + * Color blue component + */ + float b; + + /** + * Color alpha component + */ + float a; + + /** + * Shift along x + */ + float shift; + + /** + * Color gamma correction + */ + float gamma; + +} glyph_vertex_t; + + +/** + * Line structure + */ +typedef struct line_info_t { + /** + * Index (in the vertex buffer) where this line starts + */ + size_t line_start; + + /** + * bounds of this line + */ + vec4 bounds; + +} line_info_t; + +/** + * Align enumeration + */ +typedef enum Align +{ + /** + * Align text to the left hand side + */ + ALIGN_LEFT, + + /** + * Align text to the center + */ + ALIGN_CENTER, + + /** + * Align text to the right hand side + */ + ALIGN_RIGHT +} Align; + + +/** + * Creates a new empty text buffer. + * + * @return a new empty text buffer. + * + */ + text_buffer_t * + text_buffer_new( ); + +/** + * Deletes texture buffer and its associated vertex buffer. + * + * @param self texture buffer to delete + * + */ + void + text_buffer_delete( text_buffer_t * self ); + + + /** + * Print some text to the text buffer + * + * @param self a text buffer + * @param pen position of text start + * @param ... a series of markup_t *, char * ended by NULL + * + */ + void + text_buffer_printf( text_buffer_t * self, vec2 * pen, ... ); + + + /** + * Add some text to the text buffer + * + * @param self a text buffer + * @param pen position of text start + * @param markup Markup to be used to add text + * @param text Text to be added + * @param length Length of text to be added + */ + void + text_buffer_add_text( text_buffer_t * self, + vec2 * pen, markup_t * markup, + const char * text, size_t length ); + + /** + * Add a char to the text buffer + * + * @param self a text buffer + * @param pen position of text start + * @param markup markup to be used to add text + * @param current charactr to be added + * @param previous previous character (if any) + */ + void + text_buffer_add_char( text_buffer_t * self, + vec2 * pen, markup_t * markup, + const char * current, const char * previous ); + + /** + * Align all the lines of text already added to the buffer + * This alignment will be relative to the overall bounds of the + * text which can be queried by text_buffer_get_bounds + * + * @param self a text buffer + * @param pen pen used in last call (must be unmodified) + * @param alignment desired alignment of text + */ + void + text_buffer_align( text_buffer_t * self, vec2 * pen, + enum Align alignment ); + + /** + * Get the rectangle surrounding the text + * + * @param self a text buffer + * @param pen pen used in last call (must be unmodified) + */ + vec4 + text_buffer_get_bounds( text_buffer_t * self, vec2 * pen ); + +/** + * Clear text buffer + * + * @param self a text buffer + */ + void + text_buffer_clear( text_buffer_t * self ); + + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* #define __TEXT_BUFFER_H__ */ diff --git a/src/freetype-gl/texture-atlas.c b/src/freetype-gl/texture-atlas.c new file mode 100644 index 00000000..1d31e0f3 --- /dev/null +++ b/src/freetype-gl/texture-atlas.c @@ -0,0 +1,277 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include +#include +#include "texture-atlas.h" + + +// ------------------------------------------------------ texture_atlas_new --- +texture_atlas_t * +texture_atlas_new( const size_t width, + const size_t height, + const size_t depth ) +{ + texture_atlas_t *self = (texture_atlas_t *) malloc( sizeof(texture_atlas_t) ); + + // We want a one pixel border around the whole atlas to avoid any artefact when + // sampling texture + ivec3 node = {{1,1,width-2}}; + + assert( (depth == 1) || (depth == 3) || (depth == 4) ); + if( self == NULL) + { + fprintf( stderr, + "line %d: No more memory for allocating data\n", __LINE__ ); + exit( EXIT_FAILURE ); + } + self->nodes = vector_new( sizeof(ivec3) ); + self->used = 0; + self->width = width; + self->height = height; + self->depth = depth; + self->id = 0; + self->dirty = 1; + + vector_push_back( self->nodes, &node ); + self->data = (unsigned char *) + calloc( width*height*depth, sizeof(unsigned char) ); + + if( self->data == NULL) + { + fprintf( stderr, + "line %d: No more memory for allocating data\n", __LINE__ ); + exit( EXIT_FAILURE ); + } + + return self; +} + + +// --------------------------------------------------- texture_atlas_delete --- +void +texture_atlas_delete( texture_atlas_t *self ) +{ + assert( self ); + vector_delete( self->nodes ); + if( self->data ) + { + free( self->data ); + } + free( self ); +} + + +// ----------------------------------------------- texture_atlas_set_region --- +void +texture_atlas_set_region( texture_atlas_t * self, + const size_t x, + const size_t y, + const size_t width, + const size_t height, + const unsigned char * data, + const size_t stride ) +{ + size_t i; + size_t depth; + size_t charsize; + + assert( self ); + assert( x > 0); + assert( y > 0); + assert( x < (self->width-1)); + assert( (x + width) <= (self->width-1)); + assert( y < (self->height-1)); + assert( (y + height) <= (self->height-1)); + + //prevent copying data from undefined position + //and prevent memcpy's undefined behavior when count is zero + assert(height == 0 || (data != NULL && width > 0)); + + depth = self->depth; + charsize = sizeof(char); + for( i=0; idata+((y+i)*self->width + x ) * charsize * depth, + data + (i*stride) * charsize, width * charsize * depth ); + } + self->dirty = 1; +} + + +// ------------------------------------------------------ texture_atlas_fit --- +int +texture_atlas_fit( texture_atlas_t * self, + const size_t index, + const size_t width, + const size_t height ) +{ + ivec3 *node; + int x, y, width_left; + size_t i; + + assert( self ); + + node = (ivec3 *) (vector_get( self->nodes, index )); + x = node->x; + y = node->y; + width_left = width; + i = index; + + if ( (x + width) > (self->width-1) ) + { + return -1; + } + y = node->y; + while( width_left > 0 ) + { + node = (ivec3 *) (vector_get( self->nodes, i )); + if( node->y > y ) + { + y = node->y; + } + if( (y + height) > (self->height-1) ) + { + return -1; + } + width_left -= node->z; + ++i; + } + return y; +} + + +// ---------------------------------------------------- texture_atlas_merge --- +void +texture_atlas_merge( texture_atlas_t * self ) +{ + ivec3 *node, *next; + size_t i; + + assert( self ); + + for( i=0; i< self->nodes->size-1; ++i ) + { + node = (ivec3 *) (vector_get( self->nodes, i )); + next = (ivec3 *) (vector_get( self->nodes, i+1 )); + if( node->y == next->y ) + { + node->z += next->z; + vector_erase( self->nodes, i+1 ); + --i; + } + } +} + + +// ----------------------------------------------- texture_atlas_get_region --- +ivec4 +texture_atlas_get_region( texture_atlas_t * self, + const size_t width, + const size_t height ) +{ + int y, best_index; + size_t best_height, best_width; + ivec3 *node, *prev; + ivec4 region = {{0,0,width,height}}; + size_t i; + + assert( self ); + + best_height = UINT_MAX; + best_index = -1; + best_width = UINT_MAX; + for( i=0; inodes->size; ++i ) + { + y = texture_atlas_fit( self, i, width, height ); + if( y >= 0 ) + { + node = (ivec3 *) vector_get( self->nodes, i ); + if( ( (y + height) < best_height ) || + ( ((y + height) == best_height) && (node->z > 0 && (size_t)node->z < best_width)) ) + { + best_height = y + height; + best_index = i; + best_width = node->z; + region.x = node->x; + region.y = y; + } + } + } + + if( best_index == -1 ) + { + region.x = -1; + region.y = -1; + region.width = 0; + region.height = 0; + return region; + } + + node = (ivec3 *) malloc( sizeof(ivec3) ); + if( node == NULL) + { + fprintf( stderr, + "line %d: No more memory for allocating data\n", __LINE__ ); + exit( EXIT_FAILURE ); + } + node->x = region.x; + node->y = region.y + height; + node->z = width; + vector_insert( self->nodes, best_index, node ); + free( node ); + + for(i = best_index+1; i < self->nodes->size; ++i) + { + node = (ivec3 *) vector_get( self->nodes, i ); + prev = (ivec3 *) vector_get( self->nodes, i-1 ); + + if (node->x < (prev->x + prev->z) ) + { + int shrink = prev->x + prev->z - node->x; + node->x += shrink; + node->z -= shrink; + if (node->z <= 0) + { + vector_erase( self->nodes, i ); + --i; + } + else + { + break; + } + } + else + { + break; + } + } + texture_atlas_merge( self ); + self->used += width * height; + return region; +} + + +// ---------------------------------------------------- texture_atlas_clear --- +void +texture_atlas_clear( texture_atlas_t * self ) +{ + ivec3 node = {{1,1,1}}; + + assert( self ); + assert( self->data ); + + vector_clear( self->nodes ); + self->used = 0; + // We want a one pixel border around the whole atlas to avoid any artefact when + // sampling texture + node.z = self->width-2; + + vector_push_back( self->nodes, &node ); + memset( self->data, 0, self->width*self->height*self->depth ); +} diff --git a/src/freetype-gl/texture-atlas.h b/src/freetype-gl/texture-atlas.h new file mode 100644 index 00000000..2173ace7 --- /dev/null +++ b/src/freetype-gl/texture-atlas.h @@ -0,0 +1,199 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + * ============================================================================ + * + * + * This source is based on the article by Jukka Jylänki : + * "A Thousand Ways to Pack the Bin - A Practical Approach to + * Two-Dimensional Rectangle Bin Packing", February 27, 2010. + * + * More precisely, this is an implementation of the Skyline Bottom-Left + * algorithm based on C++ sources provided by Jukka Jylänki at: + * http://clb.demon.fi/files/RectangleBinPack/ + * + * ============================================================================ + */ +#ifndef __TEXTURE_ATLAS_H__ +#define __TEXTURE_ATLAS_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#include "vector.h" +#include "vec234.h" + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * @file texture-atlas.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup texture-atlas Texture atlas + * + * A texture atlas is used to pack several small regions into a single texture. + * + * The actual implementation is based on the article by Jukka Jylänki : "A + * Thousand Ways to Pack the Bin - A Practical Approach to Two-Dimensional + * Rectangle Bin Packing", February 27, 2010. + * More precisely, this is an implementation of the Skyline Bottom-Left + * algorithm based on C++ sources provided by Jukka Jylänki at: + * http://clb.demon.fi/files/RectangleBinPack/ + * + * + * Example Usage: + * @code + * #include "texture-atlas.h" + * + * ... + * + * / Creates a new atlas of 512x512 with a depth of 1 + * texture_atlas_t * atlas = texture_atlas_new( 512, 512, 1 ); + * + * // Allocates a region of 20x20 + * ivec4 region = texture_atlas_get_region( atlas, 20, 20 ); + * + * // Fill region with some data + * texture_atlas_set_region( atlas, region.x, region.y, region.width, region.height, data, stride ) + * + * ... + * + * @endcode + * + * @{ + */ + + +/** + * A texture atlas is used to pack several small regions into a single texture. + */ +typedef struct texture_atlas_t +{ + /** + * Allocated nodes + */ + vector_t * nodes; + + /** + * Width (in pixels) of the underlying texture + */ + size_t width; + + /** + * Height (in pixels) of the underlying texture + */ + size_t height; + + /** + * Depth (in bytes) of the underlying texture + */ + size_t depth; + + /** + * Allocated surface size + */ + size_t used; + + /** + * Texture identity (OpenGL) + */ + unsigned int id; + + /** + * Atlas data + */ + unsigned char * data; + + /** + * Custom field, "dirty" flag, set to true when atlas is updated. + */ + char dirty; + +} texture_atlas_t; + + + +/** + * Creates a new empty texture atlas. + * + * @param width width of the atlas + * @param height height of the atlas + * @param depth bit depth of the atlas + * @return a new empty texture atlas. + * + */ + texture_atlas_t * + texture_atlas_new( const size_t width, + const size_t height, + const size_t depth ); + + +/** + * Deletes a texture atlas. + * + * @param self a texture atlas structure + * + */ + void + texture_atlas_delete( texture_atlas_t * self ); + + +/** + * Allocate a new region in the atlas. + * + * @param self a texture atlas structure + * @param width width of the region to allocate + * @param height height of the region to allocate + * @return Coordinates of the allocated region + * + */ + ivec4 + texture_atlas_get_region( texture_atlas_t * self, + const size_t width, + const size_t height ); + + +/** + * Upload data to the specified atlas region. + * + * @param self a texture atlas structure + * @param x x coordinate the region + * @param y y coordinate the region + * @param width width of the region + * @param height height of the region + * @param data data to be uploaded into the specified region + * @param stride stride of the data + * + */ + void + texture_atlas_set_region( texture_atlas_t * self, + const size_t x, + const size_t y, + const size_t width, + const size_t height, + const unsigned char *data, + const size_t stride ); + +/** + * Remove all allocated regions from the atlas. + * + * @param self a texture atlas structure + */ + void + texture_atlas_clear( texture_atlas_t * self ); + + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* __TEXTURE_ATLAS_H__ */ diff --git a/src/freetype-gl/texture-font.c b/src/freetype-gl/texture-font.c new file mode 100644 index 00000000..ae0eeffe --- /dev/null +++ b/src/freetype-gl/texture-font.c @@ -0,0 +1,733 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include FT_FREETYPE_H +#include FT_STROKER_H +// #include FT_ADVANCES_H +#include FT_LCD_FILTER_H +#include +#include +#include +#include +#include +#include "distance-field.h" +#include "texture-font.h" +#include "platform.h" +#include "utf8-utils.h" + +#define HRES 64 +#define HRESf 64.f +#define DPI 72 + +#undef __FTERRORS_H__ +#define FT_ERRORDEF( e, v, s ) { e, s }, +#define FT_ERROR_START_LIST { +#define FT_ERROR_END_LIST { 0, 0 } }; +const struct { + int code; + const char* message; +} FT_Errors[] = +#include FT_ERRORS_H + +// ------------------------------------------------- texture_font_load_face --- +static int +texture_font_load_face(texture_font_t *self, float size, + FT_Library *library, FT_Face *face) +{ + FT_Error error; + FT_Matrix matrix = { + (int)((1.0/HRES) * 0x10000L), + (int)((0.0) * 0x10000L), + (int)((0.0) * 0x10000L), + (int)((1.0) * 0x10000L)}; + + assert(library); + assert(size); + + /* Initialize library */ + error = FT_Init_FreeType(library); + if(error) { + fprintf(stderr, "FT_Error (0x%02x) : %s\n", + FT_Errors[error].code, FT_Errors[error].message); + goto cleanup; + } + + /* Load face */ + switch (self->location) { + case TEXTURE_FONT_FILE: + error = FT_New_Face(*library, self->filename, 0, face); + break; + + case TEXTURE_FONT_MEMORY: + error = FT_New_Memory_Face(*library, + self->memory.base, self->memory.size, 0, face); + break; + } + + if(error) { + fprintf(stderr, "FT_Error (line %d, code 0x%02x) : %s\n", + __LINE__, FT_Errors[error].code, FT_Errors[error].message); + goto cleanup_library; + } + + /* Select charmap */ + error = FT_Select_Charmap(*face, FT_ENCODING_UNICODE); + if(error) { + fprintf(stderr, "FT_Error (line %d, code 0x%02x) : %s\n", + __LINE__, FT_Errors[error].code, FT_Errors[error].message); + goto cleanup_face; + } + + /* Set char size */ + error = FT_Set_Char_Size(*face, (int)(size * HRES), 0, DPI * HRES, DPI); + + if(error) { + fprintf(stderr, "FT_Error (line %d, code 0x%02x) : %s\n", + __LINE__, FT_Errors[error].code, FT_Errors[error].message); + goto cleanup_face; + } + + /* Set transform matrix */ + FT_Set_Transform(*face, &matrix, NULL); + + return 1; + +cleanup_face: + FT_Done_Face( *face ); +cleanup_library: + FT_Done_FreeType( *library ); +cleanup: + return 0; +} + +// ------------------------------------------------------ texture_glyph_new --- +texture_glyph_t * +texture_glyph_new(void) +{ + texture_glyph_t *self = (texture_glyph_t *) malloc( sizeof(texture_glyph_t) ); + if(self == NULL) { + fprintf( stderr, + "line %d: No more memory for allocating data\n", __LINE__); + return NULL; + } + + self->codepoint = -1; + self->width = 0; + self->height = 0; + self->rendermode = RENDER_NORMAL; + self->outline_thickness = 0.0; + self->offset_x = 0; + self->offset_y = 0; + self->advance_x = 0.0; + self->advance_y = 0.0; + self->s0 = 0.0; + self->t0 = 0.0; + self->s1 = 0.0; + self->t1 = 0.0; + self->kerning = vector_new( sizeof(kerning_t) ); + return self; +} + + +// --------------------------------------------------- texture_glyph_delete --- +void +texture_glyph_delete( texture_glyph_t *self ) +{ + assert( self ); + vector_delete( self->kerning ); + free( self ); +} + +// ---------------------------------------------- texture_glyph_get_kerning --- +float +texture_glyph_get_kerning( const texture_glyph_t * self, + const char * codepoint ) +{ + size_t i; + uint32_t ucodepoint = utf8_to_utf32( codepoint ); + + assert( self ); + for( i=0; ikerning); ++i ) + { + kerning_t * kerning = (kerning_t *) vector_get( self->kerning, i ); + if( kerning->codepoint == ucodepoint ) + { + return kerning->kerning; + } + } + return 0; +} + + +// ------------------------------------------ texture_font_generate_kerning --- +void +texture_font_generate_kerning( texture_font_t *self, + FT_Library *library, FT_Face *face ) +{ + size_t i, j; + FT_UInt glyph_index, prev_index; + texture_glyph_t *glyph, *prev_glyph; + FT_Vector kerning; + + assert( self ); + + /* For each glyph couple combination, check if kerning is necessary */ + /* Starts at index 1 since 0 is for the special backgroudn glyph */ + for( i=1; iglyphs->size; ++i ) + { + glyph = *(texture_glyph_t **) vector_get( self->glyphs, i ); + glyph_index = FT_Get_Char_Index( *face, glyph->codepoint ); + vector_clear( glyph->kerning ); + + for( j=1; jglyphs->size; ++j ) + { + prev_glyph = *(texture_glyph_t **) vector_get( self->glyphs, j ); + prev_index = FT_Get_Char_Index( *face, prev_glyph->codepoint ); + FT_Get_Kerning( *face, prev_index, glyph_index, FT_KERNING_UNFITTED, &kerning ); + // printf("%c(%d)-%c(%d): %ld\n", + // prev_glyph->codepoint, prev_glyph->codepoint, + // glyph_index, glyph_index, kerning.x); + if( kerning.x ) + { + kerning_t k = {prev_glyph->codepoint, kerning.x / (float)(HRESf*HRESf)}; + vector_push_back( glyph->kerning, &k ); + } + } + } +} + +// ------------------------------------------------------ texture_font_init --- +static int +texture_font_init(texture_font_t *self) +{ + FT_Library library; + FT_Face face; + FT_Size_Metrics metrics; + + assert(self->atlas); + assert(self->size > 0); + assert((self->location == TEXTURE_FONT_FILE && self->filename) + || (self->location == TEXTURE_FONT_MEMORY + && self->memory.base && self->memory.size)); + + self->glyphs = vector_new(sizeof(texture_glyph_t *)); + self->height = 0; + self->ascender = 0; + self->descender = 0; + self->rendermode = RENDER_NORMAL; + self->outline_thickness = 0.0; + self->hinting = 1; + self->kerning = 1; + self->filtering = 1; + + // FT_LCD_FILTER_LIGHT is (0x00, 0x55, 0x56, 0x55, 0x00) + // FT_LCD_FILTER_DEFAULT is (0x10, 0x40, 0x70, 0x40, 0x10) + self->lcd_weights[0] = 0x10; + self->lcd_weights[1] = 0x40; + self->lcd_weights[2] = 0x70; + self->lcd_weights[3] = 0x40; + self->lcd_weights[4] = 0x10; + + if (!texture_font_load_face(self, self->size * 100.f, &library, &face)) + return -1; + + self->underline_position = face->underline_position / (float)(HRESf*HRESf) * self->size; + self->underline_position = roundf( self->underline_position ); + if( self->underline_position > -2 ) + { + self->underline_position = -2.0; + } + + self->underline_thickness = face->underline_thickness / (float)(HRESf*HRESf) * self->size; + self->underline_thickness = roundf( self->underline_thickness ); + if( self->underline_thickness < 1 ) + { + self->underline_thickness = 1.0; + } + + metrics = face->size->metrics; + self->ascender = (metrics.ascender >> 6) / 100.0; + self->descender = (metrics.descender >> 6) / 100.0; + self->height = (metrics.height >> 6) / 100.0; + self->linegap = self->height - self->ascender + self->descender; + FT_Done_Face( face ); + FT_Done_FreeType( library ); + + /* NULL is a special glyph */ + texture_font_get_glyph( self, NULL ); + + return 0; +} + +// --------------------------------------------- texture_font_new_from_file --- +texture_font_t * +texture_font_new_from_file(texture_atlas_t *atlas, const float pt_size, + const char *filename) +{ + texture_font_t *self; + + assert(filename); + + self = calloc(1, sizeof(*self)); + if (!self) { + fprintf(stderr, + "line %d: No more memory for allocating data\n", __LINE__); + return NULL; + } + + self->atlas = atlas; + self->size = pt_size; + + self->location = TEXTURE_FONT_FILE; + self->filename = strdup(filename); + + if (texture_font_init(self)) { + texture_font_delete(self); + return NULL; + } + + return self; +} + +// ------------------------------------------- texture_font_new_from_memory --- +texture_font_t * +texture_font_new_from_memory(texture_atlas_t *atlas, float pt_size, + const void *memory_base, size_t memory_size) +{ + texture_font_t *self; + + assert(memory_base); + assert(memory_size); + + self = calloc(1, sizeof(*self)); + if (!self) { + fprintf(stderr, + "line %d: No more memory for allocating data\n", __LINE__); + return NULL; + } + + self->atlas = atlas; + self->size = pt_size; + + self->location = TEXTURE_FONT_MEMORY; + self->memory.base = memory_base; + self->memory.size = memory_size; + + if (texture_font_init(self)) { + texture_font_delete(self); + return NULL; + } + + return self; +} + +// ---------------------------------------------------- texture_font_delete --- +void +texture_font_delete( texture_font_t *self ) +{ + size_t i; + texture_glyph_t *glyph; + + assert( self ); + + if(self->location == TEXTURE_FONT_FILE && self->filename) + free( self->filename ); + + for( i=0; iglyphs ); ++i) + { + glyph = *(texture_glyph_t **) vector_get( self->glyphs, i ); + texture_glyph_delete( glyph); + } + + vector_delete( self->glyphs ); + free( self ); +} + +texture_glyph_t * +texture_font_find_glyph( texture_font_t * self, + const char * codepoint ) +{ + size_t i; + texture_glyph_t *glyph; + uint32_t ucodepoint = utf8_to_utf32( codepoint ); + + for( i = 0; i < self->glyphs->size; ++i ) + { + glyph = *(texture_glyph_t **) vector_get( self->glyphs, i ); + // If codepoint is -1, we don't care about outline type or thickness + if( (glyph->codepoint == ucodepoint) && + ((ucodepoint == -1) || + ((glyph->rendermode == self->rendermode) && + (glyph->outline_thickness == self->outline_thickness)) )) + { + return glyph; + } + } + + return NULL; +} + +// ------------------------------------------------ texture_font_load_glyph --- +int +texture_font_load_glyph( texture_font_t * self, + const char * codepoint ) +{ + size_t i, x, y; + + FT_Library library; + FT_Error error; + FT_Face face; + FT_Glyph ft_glyph; + FT_GlyphSlot slot; + FT_Bitmap ft_bitmap; + + FT_UInt glyph_index; + texture_glyph_t *glyph; + FT_Int32 flags = 0; + int ft_glyph_top = 0; + int ft_glyph_left = 0; + + ivec4 region; + size_t missed = 0; + + + if (!texture_font_load_face(self, self->size, &library, &face)) + return 0; + + /* Check if codepoint has been already loaded */ + if (texture_font_find_glyph(self, codepoint)) { + FT_Done_Face(face); + FT_Done_FreeType(library); + return 1; + } + + /* codepoint NULL is special : it is used for line drawing (overline, + * underline, strikethrough) and background. + */ + if( !codepoint ) + { + ivec4 region = texture_atlas_get_region( self->atlas, 5, 5 ); + texture_glyph_t * glyph = texture_glyph_new( ); + static unsigned char data[4*4*3] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; + if ( region.x < 0 ) + { + fprintf( stderr, "Texture atlas is full (line %d)\n", __LINE__ ); + FT_Done_Face( face ); + FT_Done_FreeType( library ); + return NULL; + } + texture_atlas_set_region( self->atlas, region.x, region.y, 4, 4, data, 0 ); + glyph->codepoint = -1; + glyph->s0 = (region.x+2)/(float)self->atlas->width; + glyph->t0 = (region.y+2)/(float)self->atlas->height; + glyph->s1 = (region.x+3)/(float)self->atlas->width; + glyph->t1 = (region.y+3)/(float)self->atlas->height; + vector_push_back( self->glyphs, &glyph ); + + FT_Done_Face(face); + FT_Done_FreeType(library); + return 1; + } + + flags = 0; + ft_glyph_top = 0; + ft_glyph_left = 0; + glyph_index = FT_Get_Char_Index( face, (FT_ULong)utf8_to_utf32( codepoint ) ); + // WARNING: We use texture-atlas depth to guess if user wants + // LCD subpixel rendering + + if( self->rendermode != RENDER_NORMAL && self->rendermode != RENDER_SIGNED_DISTANCE_FIELD ) + { + flags |= FT_LOAD_NO_BITMAP; + } + else + { + flags |= FT_LOAD_RENDER; + } + + if( !self->hinting ) + { + flags |= FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT; + } + else + { + flags |= FT_LOAD_FORCE_AUTOHINT; + } + + if( self->atlas->depth == 3 ) + { + FT_Library_SetLcdFilter( library, FT_LCD_FILTER_LIGHT ); + flags |= FT_LOAD_TARGET_LCD; + + if( self->filtering ) + { + FT_Library_SetLcdFilterWeights( library, self->lcd_weights ); + } + } + + error = FT_Load_Glyph( face, glyph_index, flags ); + if( error ) + { + fprintf( stderr, "FT_Error (line %d, code 0x%02x) : %s\n", + __LINE__, FT_Errors[error].code, FT_Errors[error].message ); + FT_Done_Face( face ); + FT_Done_FreeType( library ); + return 0; + } + + if( self->rendermode == RENDER_NORMAL || self->rendermode == RENDER_SIGNED_DISTANCE_FIELD ) + { + slot = face->glyph; + ft_bitmap = slot->bitmap; + ft_glyph_top = slot->bitmap_top; + ft_glyph_left = slot->bitmap_left; + } + else + { + FT_Stroker stroker; + FT_BitmapGlyph ft_bitmap_glyph; + + error = FT_Stroker_New( library, &stroker ); + + if( error ) + { + fprintf(stderr, "FT_Error (0x%02x) : %s\n", + FT_Errors[error].code, FT_Errors[error].message); + goto cleanup_stroker; + } + + FT_Stroker_Set(stroker, + (int)(self->outline_thickness * HRES), + FT_STROKER_LINECAP_ROUND, + FT_STROKER_LINEJOIN_ROUND, + 0); + + error = FT_Get_Glyph( face->glyph, &ft_glyph); + + if( error ) + { + fprintf(stderr, "FT_Error (0x%02x) : %s\n", + FT_Errors[error].code, FT_Errors[error].message); + goto cleanup_stroker; + } + + if( self->rendermode == RENDER_OUTLINE_EDGE ) + error = FT_Glyph_Stroke( &ft_glyph, stroker, 1 ); + else if ( self->rendermode == RENDER_OUTLINE_POSITIVE ) + error = FT_Glyph_StrokeBorder( &ft_glyph, stroker, 0, 1 ); + else if ( self->rendermode == RENDER_OUTLINE_NEGATIVE ) + error = FT_Glyph_StrokeBorder( &ft_glyph, stroker, 1, 1 ); + + if( error ) + { + fprintf(stderr, "FT_Error (0x%02x) : %s\n", + FT_Errors[error].code, FT_Errors[error].message); + goto cleanup_stroker; + } + + if( self->atlas->depth == 1 ) + error = FT_Glyph_To_Bitmap( &ft_glyph, FT_RENDER_MODE_NORMAL, 0, 1); + else + error = FT_Glyph_To_Bitmap( &ft_glyph, FT_RENDER_MODE_LCD, 0, 1); + + if( error ) + { + fprintf(stderr, "FT_Error (0x%02x) : %s\n", + FT_Errors[error].code, FT_Errors[error].message); + goto cleanup_stroker; + } + + ft_bitmap_glyph = (FT_BitmapGlyph) ft_glyph; + ft_bitmap = ft_bitmap_glyph->bitmap; + ft_glyph_top = ft_bitmap_glyph->top; + ft_glyph_left = ft_bitmap_glyph->left; + +cleanup_stroker: + FT_Stroker_Done( stroker ); + + if( error ) + { + FT_Done_Face( face ); + FT_Done_FreeType( library ); + return 0; + } + } + + struct { + int left; + int top; + int right; + int bottom; + } padding = { 0, 0, 1, 1 }; + + if( self->rendermode == RENDER_SIGNED_DISTANCE_FIELD ) + { + padding.top = 1; + padding.left = 1; + } + + size_t src_w = ft_bitmap.width/self->atlas->depth; + size_t src_h = ft_bitmap.rows; + + size_t tgt_w = src_w + padding.left + padding.right; + size_t tgt_h = src_h + padding.top + padding.bottom; + + region = texture_atlas_get_region( self->atlas, tgt_w, tgt_h ); + + if ( region.x < 0 ) + { + fprintf( stderr, "Texture atlas is full (line %d)\n", __LINE__ ); + FT_Done_Face( face ); + FT_Done_FreeType( library ); + return 0; + } + + x = region.x; + y = region.y; + + unsigned char *buffer = calloc( tgt_w * tgt_h * self->atlas->depth, sizeof(unsigned char) ); + + unsigned char *dst_ptr = buffer + (padding.top * tgt_w + padding.left) * self->atlas->depth; + unsigned char *src_ptr = ft_bitmap.buffer; + for( i = 0; i < src_h; i++ ) + { + //difference between width and pitch: https://www.freetype.org/freetype2/docs/reference/ft2-basic_types.html#FT_Bitmap + memcpy( dst_ptr, src_ptr, ft_bitmap.width); + dst_ptr += tgt_w * self->atlas->depth; + src_ptr += ft_bitmap.pitch; + } + + if( self->rendermode == RENDER_SIGNED_DISTANCE_FIELD ) + { + unsigned char *sdf = make_distance_mapb( buffer, tgt_w, tgt_h ); + free( buffer ); + buffer = sdf; + } + + texture_atlas_set_region( self->atlas, x, y, tgt_w, tgt_h, buffer, tgt_w * self->atlas->depth); + + free( buffer ); + + glyph = texture_glyph_new( ); + glyph->codepoint = utf8_to_utf32( codepoint ); + glyph->width = tgt_w; + glyph->height = tgt_h; + glyph->rendermode = self->rendermode; + glyph->outline_thickness = self->outline_thickness; + glyph->offset_x = ft_glyph_left; + glyph->offset_y = ft_glyph_top; + glyph->s0 = x/(float)self->atlas->width; + glyph->t0 = y/(float)self->atlas->height; + glyph->s1 = (x + glyph->width)/(float)self->atlas->width; + glyph->t1 = (y + glyph->height)/(float)self->atlas->height; + + // Discard hinting to get advance + FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER | FT_LOAD_NO_HINTING); + slot = face->glyph; + glyph->advance_x = slot->advance.x / HRESf; + glyph->advance_y = slot->advance.y / HRESf; + + vector_push_back( self->glyphs, &glyph ); + + if( self->rendermode != RENDER_NORMAL && self->rendermode != RENDER_SIGNED_DISTANCE_FIELD ) + FT_Done_Glyph( ft_glyph ); + + texture_font_generate_kerning( self, &library, &face ); + + FT_Done_Face( face ); + FT_Done_FreeType( library ); + + return 1; +} + +// ----------------------------------------------- texture_font_load_glyphs --- +size_t +texture_font_load_glyphs( texture_font_t * self, + const char * codepoints ) +{ + size_t i; + + /* Load each glyph */ + for( i = 0; i < utf8_strlen(codepoints); i += utf8_surrogate_len(codepoints + i) ) { + if( !texture_font_load_glyph( self, codepoints + i ) ) + return utf8_strlen( codepoints + i ); + + } + + return 0; +} + + +// ------------------------------------------------- texture_font_get_glyph --- +texture_glyph_t * +texture_font_get_glyph( texture_font_t * self, + const char * codepoint ) +{ + texture_glyph_t *glyph; + + assert( self ); + assert( self->filename ); + assert( self->atlas ); + + /* Check if codepoint has been already loaded */ + if( (glyph = texture_font_find_glyph( self, codepoint )) ) + return glyph; + + /* Glyph has not been already loaded */ + if( texture_font_load_glyph( self, codepoint ) ) + return texture_font_find_glyph( self, codepoint ); + + return NULL; +} + +// ------------------------------------------------- texture_font_enlarge_atlas --- +void +texture_font_enlarge_atlas( texture_font_t * self, size_t width_new, + size_t height_new) +{ + assert(self); + assert(self->atlas); + //ensure size increased + assert(width_new >= self->atlas->width); + assert(height_new >= self->atlas->height); + assert(width_new + height_new > self->atlas->width + self->atlas->height); + texture_atlas_t* ta = self->atlas; + size_t width_old = ta->width; + size_t height_old = ta->height; + //allocate new buffer + unsigned char* data_old = ta->data; + ta->data = calloc(1,width_new*height_new * sizeof(char)*ta->depth); + //update atlas size + ta->width = width_new; + ta->height = height_new; + //add node reflecting the gained space on the right + if(width_new>width_old){ + ivec3 node; + node.x = width_old - 1; + node.y = 1; + node.z = width_new - width_old; + vector_push_back(ta->nodes, &node); + } + //copy over data from the old buffer, skipping first row and column because of the margin + size_t pixel_size = sizeof(char) * ta->depth; + size_t old_row_size = width_old * pixel_size; + texture_atlas_set_region(ta, 1, 1, width_old - 2, height_old - 2, data_old + old_row_size + pixel_size, old_row_size); + free(data_old); + //change uv coordinates of existing glyphs to reflect size change + float mulw = (float)width_old / width_new; + float mulh = (float)height_old / height_new; + size_t i; + for (i = 0; i < vector_size(self->glyphs); i++) { + texture_glyph_t* g = *(texture_glyph_t**)vector_get(self->glyphs, i); + g->s0 *= mulw; + g->s1 *= mulw; + g->t0 *= mulh; + g->t1 *= mulh; + } +} diff --git a/src/freetype-gl/texture-font.h b/src/freetype-gl/texture-font.h new file mode 100644 index 00000000..7eebd914 --- /dev/null +++ b/src/freetype-gl/texture-font.h @@ -0,0 +1,472 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __TEXTURE_FONT_H__ +#define __TEXTURE_FONT_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#include "vector.h" +#include "texture-atlas.h" + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * @file texture-font.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup texture-font Texture font + * + * Texture font. + * + * Example Usage: + * @code + * #include "texture-font.h" + * + * int main( int arrgc, char *argv[] ) + * { + * return 0; + * } + * @endcode + * + * @{ + */ + + +/** + * A list of possible ways to render a glyph. + */ +typedef enum rendermode_t +{ + RENDER_NORMAL, + RENDER_OUTLINE_EDGE, + RENDER_OUTLINE_POSITIVE, + RENDER_OUTLINE_NEGATIVE, + RENDER_SIGNED_DISTANCE_FIELD +} rendermode_t; + + +/** + * A structure that hold a kerning value relatively to a Unicode + * codepoint. + * + * This structure cannot be used alone since the (necessary) right + * Unicode codepoint is implicitely held by the owner of this structure. + */ +typedef struct kerning_t +{ + /** + * Left Unicode codepoint in the kern pair in UTF-32 LE encoding. + */ + uint32_t codepoint; + + /** + * Kerning value (in fractional pixels). + */ + float kerning; + +} kerning_t; + + + + +/* + * Glyph metrics: + * -------------- + * + * xmin xmax + * | | + * |<-------- width -------->| + * | | + * | +-------------------------+----------------- ymax + * | | ggggggggg ggggg | ^ ^ + * | | g:::::::::ggg::::g | | | + * | | g:::::::::::::::::g | | | + * | | g::::::ggggg::::::gg | | | + * | | g:::::g g:::::g | | | + * offset_x -|-------->| g:::::g g:::::g | offset_y | + * | | g:::::g g:::::g | | | + * | | g::::::g g:::::g | | | + * | | g:::::::ggggg:::::g | | | + * | | g::::::::::::::::g | | height + * | | gg::::::::::::::g | | | + * baseline ---*---------|---- gggggggg::::::g-----*-------- | + * / | | g:::::g | | + * origin | | gggggg g:::::g | | + * | | g:::::gg gg:::::g | | + * | | g::::::ggg:::::::g | | + * | | gg:::::::::::::g | | + * | | ggg::::::ggg | | + * | | gggggg | v + * | +-------------------------+----------------- ymin + * | | + * |------------- advance_x ---------->| + */ + +/** + * A structure that describe a glyph. + */ +typedef struct texture_glyph_t +{ + /** + * Unicode codepoint this glyph represents in UTF-32 LE encoding. + */ + uint32_t codepoint; + + /** + * Glyph's width in pixels. + */ + size_t width; + + /** + * Glyph's height in pixels. + */ + size_t height; + + /** + * Glyph's left bearing expressed in integer pixels. + */ + int offset_x; + + /** + * Glyphs's top bearing expressed in integer pixels. + * + * Remember that this is the distance from the baseline to the top-most + * glyph scanline, upwards y coordinates being positive. + */ + int offset_y; + + /** + * For horizontal text layouts, this is the horizontal distance (in + * fractional pixels) used to increment the pen position when the glyph is + * drawn as part of a string of text. + */ + float advance_x; + + /** + * For vertical text layouts, this is the vertical distance (in fractional + * pixels) used to increment the pen position when the glyph is drawn as + * part of a string of text. + */ + float advance_y; + + /** + * First normalized texture coordinate (x) of top-left corner + */ + float s0; + + /** + * Second normalized texture coordinate (y) of top-left corner + */ + float t0; + + /** + * First normalized texture coordinate (x) of bottom-right corner + */ + float s1; + + /** + * Second normalized texture coordinate (y) of bottom-right corner + */ + float t1; + + /** + * A vector of kerning pairs relative to this glyph. + */ + vector_t * kerning; + + /** + * Mode this glyph was rendered + */ + rendermode_t rendermode; + + /** + * Glyph outline thickness + */ + float outline_thickness; + +} texture_glyph_t; + + + +/** + * Texture font structure. + */ +typedef struct texture_font_t +{ + /** + * Vector of glyphs contained in this font. + */ + vector_t * glyphs; + + /** + * Atlas structure to store glyphs data. + */ + texture_atlas_t * atlas; + + /** + * font location + */ + enum { + TEXTURE_FONT_FILE = 0, + TEXTURE_FONT_MEMORY, + } location; + + union { + /** + * Font filename, for when location == TEXTURE_FONT_FILE + */ + char *filename; + + /** + * Font memory address, for when location == TEXTURE_FONT_MEMORY + */ + struct { + const void *base; + size_t size; + } memory; + }; + + /** + * Font size + */ + float size; + + /** + * Whether to use autohint when rendering font + */ + int hinting; + + /** + * Mode the font is rendering its next glyph + */ + rendermode_t rendermode; + + /** + * Outline thickness + */ + float outline_thickness; + + /** + * Whether to use our own lcd filter. + */ + int filtering; + + /** + * LCD filter weights + */ + unsigned char lcd_weights[5]; + + /** + * Whether to use kerning if available + */ + int kerning; + + + /** + * This field is simply used to compute a default line spacing (i.e., the + * baseline-to-baseline distance) when writing text with this font. Note + * that it usually is larger than the sum of the ascender and descender + * taken as absolute values. There is also no guarantee that no glyphs + * extend above or below subsequent baselines when using this distance. + */ + float height; + + /** + * This field is the distance that must be placed between two lines of + * text. The baseline-to-baseline distance should be computed as: + * ascender - descender + linegap + */ + float linegap; + + /** + * The ascender is the vertical distance from the horizontal baseline to + * the highest 'character' coordinate in a font face. Unfortunately, font + * formats define the ascender differently. For some, it represents the + * ascent of all capital latin characters (without accents), for others it + * is the ascent of the highest accented character, and finally, other + * formats define it as being equal to bbox.yMax. + */ + float ascender; + + /** + * The descender is the vertical distance from the horizontal baseline to + * the lowest 'character' coordinate in a font face. Unfortunately, font + * formats define the descender differently. For some, it represents the + * descent of all capital latin characters (without accents), for others it + * is the ascent of the lowest accented character, and finally, other + * formats define it as being equal to bbox.yMin. This field is negative + * for values below the baseline. + */ + float descender; + + /** + * The position of the underline line for this face. It is the center of + * the underlining stem. Only relevant for scalable formats. + */ + float underline_position; + + /** + * The thickness of the underline for this face. Only relevant for scalable + * formats. + */ + float underline_thickness; + +} texture_font_t; + + + +/** + * This function creates a new texture font from given filename and size. The + * texture atlas is used to store glyph on demand. Note the depth of the atlas + * will determine if the font is rendered as alpha channel only (depth = 1) or + * RGB (depth = 3) that correspond to subpixel rendering (if available on your + * freetype implementation). + * + * @param atlas A texture atlas + * @param pt_size Size of font to be created (in points) + * @param filename A font filename + * + * @return A new empty font (no glyph inside yet) + * + */ + texture_font_t * + texture_font_new_from_file( texture_atlas_t * atlas, + const float pt_size, + const char * filename ); + + +/** + * This function creates a new texture font from a memory location and size. + * The texture atlas is used to store glyph on demand. Note the depth of the + * atlas will determine if the font is rendered as alpha channel only + * (depth = 1) or RGB (depth = 3) that correspond to subpixel rendering (if + * available on your freetype implementation). + * + * @param atlas A texture atlas + * @param pt_size Size of font to be created (in points) + * @param memory_base Start of the font file in memory + * @param memory_size Size of the font file memory region, in bytes + * + * @return A new empty font (no glyph inside yet) + * + */ + texture_font_t * + texture_font_new_from_memory( texture_atlas_t *atlas, + float pt_size, + const void *memory_base, + size_t memory_size ); + +/** + * Delete a texture font. Note that this does not delete the glyph from the + * texture atlas. + * + * @param self a valid texture font + */ + void + texture_font_delete( texture_font_t * self ); + + +/** + * Request a new glyph from the font. If it has not been created yet, it will + * be. + * + * @param self A valid texture font + * @param codepoint Character codepoint to be loaded in UTF-8 encoding. + * + * @return A pointer on the new glyph or 0 if the texture atlas is not big + * enough + * + */ + texture_glyph_t * + texture_font_get_glyph( texture_font_t * self, + const char * codepoint ); + +/** + * Request an already loaded glyph from the font. + * + * @param self A valid texture font + * @param codepoint Character codepoint to be found in UTF-8 encoding. + * + * @return A pointer on the glyph or 0 if the glyph is not loaded + */ + texture_glyph_t * + texture_font_find_glyph( texture_font_t * self, + const char * codepoint ); + +/** + * Request the loading of a given glyph. + * + * @param self A valid texture font + * @param codepoints Character codepoint to be loaded in UTF-8 encoding. + * + * @return One if the glyph could be loaded, zero if not. + */ + int + texture_font_load_glyph( texture_font_t * self, + const char * codepoint ); + +/** + * Request the loading of several glyphs at once. + * + * @param self A valid texture font + * @param codepoints Character codepoints to be loaded in UTF-8 encoding. May + * contain duplicates. + * + * @return Number of missed glyph if the texture is not big enough to hold + * every glyphs. + */ + size_t + texture_font_load_glyphs( texture_font_t * self, + const char * codepoints ); + /* + *Increases the size of a fonts texture atlas + *Invalidates all pointers to font->atlas->data + *Changes the UV Coordinates of existing glyphs in the font + * + *@param self A valid texture font + *@param width_new Width of the texture atlas after resizing (must be bigger or equal to current width) + *@param height_new Height of the texture atlas after resizing (must be bigger or equal to current height) + */ + void + texture_font_enlarge_atlas( texture_font_t * self, size_t width_new, + size_t height_new); +/** + * Get the kerning between two horizontal glyphs. + * + * @param self A valid texture glyph + * @param codepoint Character codepoint of the peceding character in UTF-8 encoding. + * + * @return x kerning value + */ +float +texture_glyph_get_kerning( const texture_glyph_t * self, + const char * codepoint ); + + +/** + * Creates a new empty glyph + * + * @return a new empty glyph (not valid) + */ +texture_glyph_t * +texture_glyph_new( void ); + +/** @} */ + + +#ifdef __cplusplus +} +} +#endif + +#endif /* __TEXTURE_FONT_H__ */ diff --git a/src/freetype-gl/utf8-utils.c b/src/freetype-gl/utf8-utils.c new file mode 100644 index 00000000..cc34f566 --- /dev/null +++ b/src/freetype-gl/utf8-utils.c @@ -0,0 +1,85 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include "utf8-utils.h" + +// ----------------------------------------------------- utf8_surrogate_len --- +size_t +utf8_surrogate_len( const char* character ) +{ + size_t result = 0; + char test_char; + + if (!character) + return 0; + + test_char = character[0]; + + if ((test_char & 0x80) == 0) + return 1; + + while (test_char & 0x80) + { + test_char <<= 1; + result++; + } + + return result; +} + +// ------------------------------------------------------------ utf8_strlen --- +size_t +utf8_strlen( const char* string ) +{ + const char* ptr = string; + size_t result = 0; + + while (*ptr) + { + ptr += utf8_surrogate_len(ptr); + result++; + } + + return result; +} + +uint32_t +utf8_to_utf32( const char * character ) +{ + uint32_t result = -1; + + if( !character ) + { + return result; + } + + if( ( character[0] & 0x80 ) == 0x0 ) + { + result = character[0]; + } + + if( ( character[0] & 0xC0 ) == 0xC0 ) + { + result = ( ( character[0] & 0x3F ) << 6 ) | ( character[1] & 0x3F ); + } + + if( ( character[0] & 0xE0 ) == 0xE0 ) + { + result = ( ( character[0] & 0x1F ) << ( 6 + 6 ) ) | ( ( character[1] & 0x3F ) << 6 ) | ( character[2] & 0x3F ); + } + + if( ( character[0] & 0xF0 ) == 0xF0 ) + { + result = ( ( character[0] & 0x0F ) << ( 6 + 6 + 6 ) ) | ( ( character[1] & 0x3F ) << ( 6 + 6 ) ) | ( ( character[2] & 0x3F ) << 6 ) | ( character[3] & 0x3F ); + } + + if( ( character[0] & 0xF8 ) == 0xF8 ) + { + result = ( ( character[0] & 0x07 ) << ( 6 + 6 + 6 + 6 ) ) | ( ( character[1] & 0x3F ) << ( 6 + 6 + 6 ) ) | ( ( character[2] & 0x3F ) << ( 6 + 6 ) ) | ( ( character[3] & 0x3F ) << 6 ) | ( character[4] & 0x3F ); + } + + return result; +} diff --git a/src/freetype-gl/utf8-utils.h b/src/freetype-gl/utf8-utils.h new file mode 100644 index 00000000..a6262011 --- /dev/null +++ b/src/freetype-gl/utf8-utils.h @@ -0,0 +1,68 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __UTF8_UTILS_H__ +#define __UTF8_UTILS_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { + +namespace ftgl { +#endif + +/** + * @file utf8-utils.h + * @author Marcel Metz + * + * defgroup utf8-utils UTF-8 Utilities + * + * @{ + */ + + /** + * Returns the size in bytes of a given UTF-8 encoded character surrogate + * + * @param character An UTF-8 encoded character + * + * @return The length of the surrogate in bytes. + */ + size_t + utf8_surrogate_len( const char* character ); + + /** + * Return the length of the given UTF-8 encoded and + * NULL terminated string. + * + * @param string An UTF-8 encoded string + * + * @return The length of the string in characters. + */ + size_t + utf8_strlen( const char* string ); + + /** + * Converts a given UTF-8 encoded character to its UTF-32 LE equivalent + * + * @param character An UTF-8 encoded character + * + * @return The equivalent of the given character in UTF-32 LE + * encoding. + */ + uint32_t + utf8_to_utf32( const char * character ); + +/** + * @} + */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* #define __UTF8_UTILS_H__ */ diff --git a/src/freetype-gl/vec234.h b/src/freetype-gl/vec234.h new file mode 100644 index 00000000..d248222c --- /dev/null +++ b/src/freetype-gl/vec234.h @@ -0,0 +1,211 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __VEC234_H__ +#define __VEC234_H__ + +#ifdef __cplusplus +extern "C" { +namespace ftgl { +#endif + + +/** + * Tuple of 4 ints. + * + * Each field can be addressed using several aliases: + * - First component: x, r, red or vstart + * - Second component: y, g, green or vcount + * - Third component: z, b, blue, width or istart + * - Fourth component: w, a, alpha, height or icount + * + */ +typedef union +{ + int data[4]; /**< All compoments at once */ + struct { + int x; /**< Alias for first component */ + int y; /**< Alias for second component */ + int z; /**< Alias for third component */ + int w; /**< Alias for fourht component */ + }; + struct { + int x_; /**< Alias for first component */ + int y_; /**< Alias for second component */ + int width; /**< Alias for third component */ + int height; /**< Alias for fourth component */ + }; + struct { + int r; /**< Alias for first component */ + int g; /**< Alias for second component */ + int b; /**< Alias for third component */ + int a; /**< Alias for fourth component */ + }; + struct { + int red; /**< Alias for first component */ + int green; /**< Alias for second component */ + int blue; /**< Alias for third component */ + int alpha; /**< Alias for fourth component */ + }; + struct { + int vstart; /**< Alias for first component */ + int vcount; /**< Alias for second component */ + int istart; /**< Alias for third component */ + int icount; /**< Alias for fourth component */ + }; +} ivec4; + + +/** + * Tuple of 3 ints. + * + * Each field can be addressed using several aliases: + * - First component: x, r or red + * - Second component: y, g or green + * - Third component: z, b or blue + * + */ +typedef union +{ + int data[3]; /**< All compoments at once */ + struct { + int x; /**< Alias for first component */ + int y; /**< Alias for second component */ + int z; /**< Alias for third component */ + }; + struct { + int r; /**< Alias for first component */ + int g; /**< Alias for second component */ + int b; /**< Alias for third component */ + }; + struct { + int red; /**< Alias for first component */ + int green; /**< Alias for second component */ + int blue; /**< Alias for third component */ + }; +} ivec3; + + +/** + * Tuple of 2 ints. + * + * Each field can be addressed using several aliases: + * - First component: x, s or start + * - Second component: y, t or end + * + */ +typedef union +{ + int data[2]; /**< All compoments at once */ + struct { + int x; /**< Alias for first component */ + int y; /**< Alias for second component */ + }; + struct { + int s; /**< Alias for first component */ + int t; /**< Alias for second component */ + }; + struct { + int start; /**< Alias for first component */ + int end; /**< Alias for second component */ + }; +} ivec2; + + +/** + * Tuple of 4 floats. + * + * Each field can be addressed using several aliases: + * - First component: x, left, r or red + * - Second component: y, top, g or green + * - Third component: z, width, b or blue + * - Fourth component: w, height, a or alpha + */ +typedef union +{ + float data[4]; /**< All compoments at once */ + struct { + float x; /**< Alias for first component */ + float y; /**< Alias for second component */ + float z; /**< Alias for third component */ + float w; /**< Alias for fourth component */ + }; + struct { + float left; /**< Alias for first component */ + float top; /**< Alias for second component */ + float width; /**< Alias for third component */ + float height; /**< Alias for fourth component */ + }; + struct { + float r; /**< Alias for first component */ + float g; /**< Alias for second component */ + float b; /**< Alias for third component */ + float a; /**< Alias for fourth component */ + }; + struct { + float red; /**< Alias for first component */ + float green; /**< Alias for second component */ + float blue; /**< Alias for third component */ + float alpha; /**< Alias for fourth component */ + }; +} vec4; + + +/** + * Tuple of 3 floats + * + * Each field can be addressed using several aliases: + * - First component: x, r or red + * - Second component: y, g or green + * - Third component: z, b or blue + */ +typedef union +{ + float data[3]; /**< All compoments at once */ + struct { + float x; /**< Alias for first component */ + float y; /**< Alias fo second component */ + float z; /**< Alias fo third component */ + }; + struct { + float r; /**< Alias for first component */ + float g; /**< Alias fo second component */ + float b; /**< Alias fo third component */ + }; + struct { + float red; /**< Alias for first component */ + float green; /**< Alias fo second component */ + float blue; /**< Alias fo third component */ + }; +} vec3; + + +/** + * Tuple of 2 floats + * + * Each field can be addressed using several aliases: + * - First component: x or s + * - Second component: y or t + */ +typedef union +{ + float data[2]; /**< All components at once */ + struct { + float x; /**< Alias for first component */ + float y; /**< Alias for second component */ + }; + struct { + float s; /**< Alias for first component */ + float t; /**< Alias for second component */ + }; +} vec2; + + +#ifdef __cplusplus +} +} +#endif + +#endif /* __VEC234_H__ */ diff --git a/src/freetype-gl/vector.c b/src/freetype-gl/vector.c new file mode 100644 index 00000000..fd7de188 --- /dev/null +++ b/src/freetype-gl/vector.c @@ -0,0 +1,335 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include +#include "vector.h" + + + +// ------------------------------------------------------------- vector_new --- +vector_t * +vector_new( size_t item_size ) +{ + vector_t *self = (vector_t *) malloc( sizeof(vector_t) ); + assert( item_size ); + + if( !self ) + { + fprintf( stderr, + "line %d: No more memory for allocating data\n", __LINE__ ); + exit( EXIT_FAILURE ); + } + self->item_size = item_size; + self->size = 0; + self->capacity = 1; + self->items = malloc( self->item_size * self->capacity ); + return self; +} + + + +// ---------------------------------------------------------- vector_delete --- +void +vector_delete( vector_t *self ) +{ + assert( self ); + + free( self->items ); + free( self ); +} + + + +// ------------------------------------------------------------- vector_get --- +const void * +vector_get( const vector_t *self, + size_t index ) +{ + assert( self ); + assert( self->size ); + assert( index < self->size ); + + return (char*)(self->items) + index * self->item_size; +} + + + +// ----------------------------------------------------------- vector_front --- +const void * +vector_front( const vector_t *self ) +{ + assert( self ); + assert( self->size ); + + return vector_get( self, 0 ); +} + + +// ------------------------------------------------------------ vector_back --- +const void * +vector_back( const vector_t *self ) +{ + assert( self ); + assert( self->size ); + + return vector_get( self, self->size-1 ); +} + + +// -------------------------------------------------------- vector_contains --- +int +vector_contains( const vector_t *self, + const void *item, + int (*cmp)(const void *, const void *) ) +{ + size_t i; + assert( self ); + + for( i=0; isize; ++i ) + { + if( (*cmp)(item, vector_get(self,i) ) == 0 ) + { + return 1; + } + } + return 0; +} + + +// ----------------------------------------------------------- vector_empty --- +int +vector_empty( const vector_t *self ) +{ + assert( self ); + + return self->size == 0; +} + + +// ------------------------------------------------------------ vector_size --- +size_t +vector_size( const vector_t *self ) +{ + assert( self ); + + return self->size; +} + + +// --------------------------------------------------------- vector_reserve --- +void +vector_reserve( vector_t *self, + const size_t size ) +{ + assert( self ); + + if( self->capacity < size) + { + self->items = realloc( self->items, size * self->item_size ); + self->capacity = size; + } +} + + +// -------------------------------------------------------- vector_capacity --- +size_t +vector_capacity( const vector_t *self ) +{ + assert( self ); + + return self->capacity; +} + + +// ---------------------------------------------------------- vector_shrink --- +void +vector_shrink( vector_t *self ) +{ + assert( self ); + + if( self->capacity > self->size ) + { + self->items = realloc( self->items, self->size * self->item_size ); + } + self->capacity = self->size; +} + + +// ----------------------------------------------------------- vector_clear --- +void +vector_clear( vector_t *self ) +{ + assert( self ); + + self->size = 0; +} + + +// ------------------------------------------------------------- vector_set --- +void +vector_set( vector_t *self, + const size_t index, + const void *item ) +{ + assert( self ); + assert( self->size ); + assert( index < self->size ); + + memcpy( (char *)(self->items) + index * self->item_size, + item, self->item_size ); +} + + +// ---------------------------------------------------------- vector_insert --- +void +vector_insert( vector_t *self, + const size_t index, + const void *item ) +{ + assert( self ); + assert( index <= self->size); + + if( self->capacity <= self->size ) + { + vector_reserve(self, 2 * self->capacity ); + } + if( index < self->size ) + { + memmove( (char *)(self->items) + (index + 1) * self->item_size, + (char *)(self->items) + (index + 0) * self->item_size, + (self->size - index) * self->item_size); + } + self->size++; + vector_set( self, index, item ); +} + + +// ----------------------------------------------------- vector_erase_range --- +void +vector_erase_range( vector_t *self, + const size_t first, + const size_t last ) +{ + assert( self ); + assert( first < self->size ); + assert( last < self->size+1 ); + assert( first < last ); + + memmove( (char *)(self->items) + first * self->item_size, + (char *)(self->items) + last * self->item_size, + (self->size - last) * self->item_size); + self->size -= (last-first); +} + + +// ----------------------------------------------------------- vector_erase --- +void +vector_erase( vector_t *self, + const size_t index ) +{ + assert( self ); + assert( index < self->size ); + + vector_erase_range( self, index, index+1 ); +} + + +// ------------------------------------------------------- vector_push_back --- +void +vector_push_back( vector_t *self, + const void *item ) +{ + vector_insert( self, self->size, item ); +} + + +// -------------------------------------------------------- vector_pop_back --- +void +vector_pop_back( vector_t *self ) +{ + assert( self ); + assert( self->size ); + + self->size--; +} + + +// ---------------------------------------------------------- vector_resize --- +void +vector_resize( vector_t *self, + const size_t size ) +{ + assert( self ); + + if( size > self->capacity) + { + vector_reserve( self, size ); + self->size = self->capacity; + } + else + { + self->size = size; + } +} + + +// -------------------------------------------------- vector_push_back_data --- +void +vector_push_back_data( vector_t *self, + const void * data, + const size_t count ) +{ + assert( self ); + assert( data ); + assert( count ); + + if( self->capacity < (self->size+count) ) + { + vector_reserve(self, self->size+count); + } + memmove( (char *)(self->items) + self->size * self->item_size, data, + count*self->item_size ); + self->size += count; +} + + +// ----------------------------------------------------- vector_insert_data --- +void +vector_insert_data( vector_t *self, + const size_t index, + const void * data, + const size_t count ) +{ + assert( self ); + assert( index < self->size ); + assert( data ); + assert( count ); + + if( self->capacity < (self->size+count) ) + { + vector_reserve(self, self->size+count); + } + memmove( (char *)(self->items) + (index + count ) * self->item_size, + (char *)(self->items) + (index ) * self->item_size, + count*self->item_size ); + memmove( (char *)(self->items) + index * self->item_size, data, + count*self->item_size ); + self->size += count; +} + + +// ------------------------------------------------------------ vector_sort --- +void +vector_sort( vector_t *self, + int (*cmp)(const void *, const void *) ) +{ + assert( self ); + assert( self->size ); + + qsort(self->items, self->size, self->item_size, cmp); +} diff --git a/src/freetype-gl/vector.h b/src/freetype-gl/vector.h new file mode 100644 index 00000000..22dba811 --- /dev/null +++ b/src/freetype-gl/vector.h @@ -0,0 +1,330 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __VECTOR_H__ +#define __VECTOR_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * @file vector.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup vector Vector + * + * The vector structure and accompanying functions loosely mimic the STL C++ + * vector class. It is used by @ref texture-atlas (for storing nodes), @ref + * texture-font (for storing glyphs) and @ref font-manager (for storing fonts). + * More information at http://www.cppreference.com/wiki/container/vector/start + * + * Example Usage: + * @code + * #include "vector.h" + * + * int main( int arrgc, char *argv[] ) + * { + * int i,j = 1; + * vector_t * vector = vector_new( sizeof(int) ); + * vector_push_back( &i ); + * + * j = * (int *) vector_get( vector, 0 ); + * vector_delete( vector); + * + * return 0; + * } + * @endcode + * + * @{ + */ + +/** + * Generic vector structure. + * + * @memberof vector + */ +typedef struct vector_t + { + /** Pointer to dynamically allocated items. */ + void * items; + + /** Number of items that can be held in currently allocated storage. */ + size_t capacity; + + /** Number of items. */ + size_t size; + + /** Size (in bytes) of a single item. */ + size_t item_size; +} vector_t; + + +/** + * Creates a new empty vector. + * + * @param item_size item size in bytes + * @return a new empty vector + * + */ + vector_t * + vector_new( size_t item_size ); + + +/** + * Deletes a vector. + * + * @param self a vector structure + * + */ + void + vector_delete( vector_t *self ); + + +/** + * Returns a pointer to the item located at specified index. + * + * @param self a vector structure + * @param index the index of the item to be returned + * @return pointer on the specified item + */ + const void * + vector_get( const vector_t *self, + size_t index ); + + +/** + * Returns a pointer to the first item. + * + * @param self a vector structure + * @return pointer on the first item + */ + const void * + vector_front( const vector_t *self ); + + +/** + * Returns a pointer to the last item + * + * @param self a vector structure + * @return pointer on the last item + */ + const void * + vector_back( const vector_t *self ); + + +/** + * Check if an item is contained within the vector. + * + * @param self a vector structure + * @param item item to be searched in the vector + * @param cmp a pointer a comparison function + * @return 1 if item is contained within the vector, 0 otherwise + */ + int + vector_contains( const vector_t *self, + const void *item, + int (*cmp)(const void *, const void *) ); + + +/** + * Checks whether the vector is empty. + * + * @param self a vector structure + * @return 1 if the vector is empty, 0 otherwise + */ + int + vector_empty( const vector_t *self ); + + +/** + * Returns the number of items + * + * @param self a vector structure + * @return number of items + */ + size_t + vector_size( const vector_t *self ); + + +/** + * Reserve storage such that it can hold at last size items. + * + * @param self a vector structure + * @param size the new storage capacity + */ + void + vector_reserve( vector_t *self, + const size_t size ); + + +/** + * Returns current storage capacity + * + * @param self a vector structure + * @return storage capacity + */ + size_t + vector_capacity( const vector_t *self ); + + +/** + * Decrease capacity to fit actual size. + * + * @param self a vector structure + */ + void + vector_shrink( vector_t *self ); + + +/** + * Removes all items. + * + * @param self a vector structure + */ + void + vector_clear( vector_t *self ); + + +/** + * Replace an item. + * + * @param self a vector structure + * @param index the index of the item to be replaced + * @param item the new item + */ + void + vector_set( vector_t *self, + const size_t index, + const void *item ); + + +/** + * Erase an item. + * + * @param self a vector structure + * @param index the index of the item to be erased + */ + void + vector_erase( vector_t *self, + const size_t index ); + + +/** + * Erase a range of items. + * + * @param self a vector structure + * @param first the index of the first item to be erased + * @param last the index of the last item to be erased + */ + void + vector_erase_range( vector_t *self, + const size_t first, + const size_t last ); + + +/** + * Appends given item to the end of the vector. + * + * @param self a vector structure + * @param item the item to be inserted + */ + void + vector_push_back( vector_t *self, + const void *item ); + + +/** + * Removes the last item of the vector. + * + * @param self a vector structure + */ + void + vector_pop_back( vector_t *self ); + + +/** + * Resizes the vector to contain size items + * + * If the current size is less than size, additional items are appended and + * initialized with value. If the current size is greater than size, the + * vector is reduced to its first size elements. + * + * @param self a vector structure + * @param size the new size + */ + void + vector_resize( vector_t *self, + const size_t size ); + + +/** + * Insert a single item at specified index. + * + * @param self a vector structure + * @param index location before which to insert item + * @param item the item to be inserted + */ + void + vector_insert( vector_t *self, + const size_t index, + const void *item ); + + +/** + * Insert raw data at specified index. + * + * @param self a vector structure + * @param index location before which to insert item + * @param data a pointer to the items to be inserted + * @param count the number of items to be inserted + */ + void + vector_insert_data( vector_t *self, + const size_t index, + const void * data, + const size_t count ); + + +/** + * Append raw data to the end of the vector. + * + * @param self a vector structure + * @param data a pointer to the items to be inserted + * @param count the number of items to be inserted + */ + void + vector_push_back_data( vector_t *self, + const void * data, + const size_t count ); + + +/** + * Sort vector items according to cmp function. + * + * @param self a vector structure + * @param cmp a pointer a comparison function + */ + void + vector_sort( vector_t *self, + int (*cmp)(const void *, const void *) ); + + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* __VECTOR_H__ */ diff --git a/src/freetype-gl/vertex-attribute.c b/src/freetype-gl/vertex-attribute.c new file mode 100644 index 00000000..e0efb9c9 --- /dev/null +++ b/src/freetype-gl/vertex-attribute.c @@ -0,0 +1,140 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include +#include "vec234.h" +#include "platform.h" +#include "vertex-attribute.h" + + + +// ---------------------------------------------------------------------------- +vertex_attribute_t * +vertex_attribute_new( GLchar * name, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + GLvoid *pointer ) +{ + vertex_attribute_t *attribute = + (vertex_attribute_t *) malloc (sizeof(vertex_attribute_t)); + + assert( size > 0 ); + + attribute->name = (GLchar *) strdup( name ); + attribute->index = -1; + attribute->size = size; + attribute->type = type; + attribute->normalized = normalized; + attribute->stride = stride; + attribute->pointer = pointer; + return attribute; +} + + + +// ---------------------------------------------------------------------------- +void +vertex_attribute_delete( vertex_attribute_t * self ) +{ + assert( self ); + + free( self->name ); + free( self ); +} + + + +// ---------------------------------------------------------------------------- +vertex_attribute_t * +vertex_attribute_parse( char *format ) +{ + GLenum type = 0; + int size; + int normalized = 0; + char ctype; + char *name; + vertex_attribute_t *attr; + char *p = strchr(format, ':'); + if( p != NULL) + { + name = strndup(format, p-format); + if( *(++p) == '\0' ) + { + fprintf( stderr, "No size specified for '%s' attribute\n", name ); + free( name ); + return 0; + } + size = *p - '0'; + + if( *(++p) == '\0' ) + { + fprintf( stderr, "No format specified for '%s' attribute\n", name ); + free( name ); + return 0; + } + ctype = *p; + + if( *(++p) != '\0' ) + { + if( *p == 'n' ) + { + normalized = 1; + } + } + + } + else + { + fprintf(stderr, "Vertex attribute format not understood ('%s')\n", format ); + return 0; + } + + switch( ctype ) + { + case 'b': type = GL_BYTE; break; + case 'B': type = GL_UNSIGNED_BYTE; break; + case 's': type = GL_SHORT; break; + case 'S': type = GL_UNSIGNED_SHORT; break; + case 'i': type = GL_INT; break; + case 'I': type = GL_UNSIGNED_INT; break; + case 'f': type = GL_FLOAT; break; + default: type = 0; break; + } + + + attr = vertex_attribute_new( name, size, type, normalized, 0, 0 ); + free( name ); + return attr; +} + + + +// ---------------------------------------------------------------------------- +void +vertex_attribute_enable( vertex_attribute_t *attr ) +{ + if( attr->index == -1 ) + { + GLint program; + glGetIntegerv( GL_CURRENT_PROGRAM, &program ); + if( program == 0) + { + return; + } + attr->index = glGetAttribLocation( program, attr->name ); + if( attr->index == -1 ) + { + return; + } + } + glEnableVertexAttribArray( attr->index ); + glVertexAttribPointer( attr->index, attr->size, attr->type, + attr->normalized, attr->stride, attr->pointer ); +} diff --git a/src/freetype-gl/vertex-attribute.h b/src/freetype-gl/vertex-attribute.h new file mode 100644 index 00000000..a32a6bf8 --- /dev/null +++ b/src/freetype-gl/vertex-attribute.h @@ -0,0 +1,296 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __VERTEX_ATTRIBUTE_H__ +#define __VERTEX_ATTRIBUTE_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "opengl.h" +#include "vector.h" + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * @file vertex-attribute.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * + * @defgroup vertex-attribut Vertex attribute + * + * Besides the required vertex position, vertices can have several other + * numeric attributes. Each is specified in the format string with a letter, + * the number of components and the data type. + * + * Each of the attributes is described in the table below with the set of valid + * format strings written as a regular expression (for example, "v[234][if]" + * means "v2f", "v3i", "v4f", etc. are all valid formats). + * + * Some attributes have a "recommended" format string, which is the most + * efficient form for the video driver as it requires less conversion. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
AttributeFormatsRecommended
Vertex position"v[234][sifd]""v[234]f"
Color "c[34][bBsSiIfd]" "c[34]B"
Edge flag "e1[bB]"
Fog coordinate "f[1234][bBsSiIfd]"
Normal "n3[bsifd]" "n3f"
Secondary color "s[34][bBsSiIfd]" "s[34]B"
Texture coordinate "t[234][sifd]" "t[234]f"
Generic attribute "[0-15]g(n)?[1234][bBsSiIfd]"
+ * + * The possible data types that can be specified in the format string are described below. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Format Type GL Type
"b" Signed byte GL_BYTE
"B" Unsigned byte GL_UNSIGNED_BYTE
"s" Signed short GL_SHORT
"S" Unsigned short GL_UNSIGNED_SHORT
"i" Signed int GL_INT
"I" Unsigned int GL_UNSIGNED_INT
"f" Float GL_FLOAT
"d" Double GL_DOUBLE T
+ * + * The following attributes are normalised to the range [0, 1]. The value is + * used as-is if the data type is floating-point. If the data type is byte, + * short or int, the value is divided by the maximum value representable by + * that type. For example, unsigned bytes are divided by 255 to get the + * normalised value. + * + * - Color + * - Secondary color + * - Generic attributes with the "n" format given. + * + * Up to 16 generic attributes can be specified per vertex, and can be used by + * shader programs for any purpose (they are ignored in the fixed-function + * pipeline). For the other attributes, consult the OpenGL programming guide + * for details on their effects. + * + * When using the draw and related functions, attribute data is specified + * alongside the vertex position data. The following example reproduces the two + * points from the previous page, except that the first point is blue and the + * second green: + * + * It is an error to provide more than one set of data for any attribute, or to + * mismatch the size of the initial data with the number of vertices specified + * in the first argument. + * + * @{ + */ + + +/** + * Maximum number of attributes per vertex + * + * @private + */ +#define MAX_VERTEX_ATTRIBUTE 16 + + +/** + * Generic vertex attribute. + */ +typedef struct vertex_attribute_t +{ + /** + * atribute name + */ + GLchar * name; + + /** + * index of the generic vertex attribute to be modified. + */ + GLuint index; + + /** + * Number of components per generic vertex attribute. + * + * Must be 1, 2, 3, or 4. The initial value is 4. + */ + GLint size; + + /** + * data type of each component in the array. + * + * Symbolic constants GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, + * GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT, GL_FLOAT, or GL_DOUBLE are + * accepted. The initial value is GL_FLOAT. + */ + GLenum type; + + /** + * whether fixed-point data values should be normalized (GL_TRUE) or + * converted directly as fixed-point values (GL_FALSE) when they are + * accessed. + */ + GLboolean normalized; + + /** + * byte offset between consecutive generic vertex attributes. + * + * If stride is 0, the generic vertex attributes are understood to be + * tightly packed in the array. The initial value is 0. + */ + GLsizei stride; + + /** + * pointer to the first component of the first attribute element in the + * array. + */ + GLvoid * pointer; + + /** + * pointer to the function that enable this attribute. + */ + void ( * enable )(void *); + +} vertex_attribute_t; + + + +/** + * Create an attribute from the given parameters. + * + * @param size number of component + * @param type data type + * @param normalized Whether fixed-point data values should be normalized + (GL_TRUE) or converted directly as fixed-point values + (GL_FALSE) when they are accessed. + * @param stride byte offset between consecutive attributes. + * @param pointer pointer to the first component of the first attribute + * element in the array. + * @return a new initialized vertex attribute. + * + * @private + */ +vertex_attribute_t * +vertex_attribute_new( GLchar * name, + GLint size, + GLenum type, + GLboolean normalized, + GLsizei stride, + GLvoid *pointer ); + + + +/** + * Delete a vertex attribute. + * + * @param self a vertex attribute + * + */ +void +vertex_attribute_delete( vertex_attribute_t * self ); + + +/** + * Create an attribute from the given description. + * + * @param format Format string specifies the format of a vertex attribute. + * @return an initialized vertex attribute + * + * @private + */ + vertex_attribute_t * + vertex_attribute_parse( char *format ); + +/** + * Enable a vertex attribute. + * + * @param attr a vertex attribute + * + * @private + */ + void + vertex_attribute_enable( vertex_attribute_t *attr ); + + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* __VERTEX_ATTRIBUTE_H__ */ diff --git a/src/freetype-gl/vertex-buffer.c b/src/freetype-gl/vertex-buffer.c new file mode 100644 index 00000000..0be4edc7 --- /dev/null +++ b/src/freetype-gl/vertex-buffer.c @@ -0,0 +1,650 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#include +#include +#include +#include +#include "vec234.h" +#include "platform.h" +#include "vertex-buffer.h" + +/** + * Buffer status + */ +#define CLEAN (0) +#define DIRTY (1) +#define FROZEN (2) + + +// ---------------------------------------------------------------------------- +vertex_buffer_t * +vertex_buffer_new( const char *format ) +{ + size_t i, index = 0, stride = 0; + const char *start = 0, *end = 0; + GLchar *pointer = 0; + + vertex_buffer_t *self = (vertex_buffer_t *) malloc (sizeof(vertex_buffer_t)); + if( !self ) + { + return NULL; + } + + self->format = strdup( format ); + + for( i=0; iattributes[i] = 0; + } + + start = format; + do + { + char *desc = 0; + vertex_attribute_t *attribute; + GLuint attribute_size = 0; + end = (char *) (strchr(start+1, ',')); + + if (end == NULL) + { + desc = strdup( start ); + } + else + { + desc = strndup( start, end-start ); + } + attribute = vertex_attribute_parse( desc ); + start = end+1; + free(desc); + attribute->pointer = pointer; + + switch( attribute->type ) + { + case GL_BOOL: attribute_size = sizeof(GLboolean); break; + case GL_BYTE: attribute_size = sizeof(GLbyte); break; + case GL_UNSIGNED_BYTE: attribute_size = sizeof(GLubyte); break; + case GL_SHORT: attribute_size = sizeof(GLshort); break; + case GL_UNSIGNED_SHORT: attribute_size = sizeof(GLushort); break; + case GL_INT: attribute_size = sizeof(GLint); break; + case GL_UNSIGNED_INT: attribute_size = sizeof(GLuint); break; + case GL_FLOAT: attribute_size = sizeof(GLfloat); break; + default: attribute_size = 0; + } + stride += attribute->size*attribute_size; + pointer += attribute->size*attribute_size; + self->attributes[index] = attribute; + index++; + } while ( end && (index < MAX_VERTEX_ATTRIBUTE) ); + + for( i=0; iattributes[i]->stride = stride; + } + +#ifdef FREETYPE_GL_USE_VAO + self->VAO_id = 0; +#endif + + self->vertices = vector_new( stride ); + self->vertices_id = 0; + self->GPU_vsize = 0; + + self->indices = vector_new( sizeof(GLuint) ); + self->indices_id = 0; + self->GPU_isize = 0; + + self->items = vector_new( sizeof(ivec4) ); + self->state = DIRTY; + self->mode = GL_TRIANGLES; + return self; +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_delete( vertex_buffer_t *self ) +{ + size_t i; + + assert( self ); + + for( i=0; iattributes[i] ) + { + vertex_attribute_delete( self->attributes[i] ); + } + } + +#ifdef FREETYPE_GL_USE_VAO + if( self->VAO_id ) + { + glDeleteVertexArrays( 1, &self->VAO_id ); + } + self->VAO_id = 0; +#endif + + vector_delete( self->vertices ); + self->vertices = 0; + if( self->vertices_id ) + { + glDeleteBuffers( 1, &self->vertices_id ); + } + self->vertices_id = 0; + + vector_delete( self->indices ); + self->indices = 0; + if( self->indices_id ) + { + glDeleteBuffers( 1, &self->indices_id ); + } + self->indices_id = 0; + + vector_delete( self->items ); + + if( self->format ) + { + free( self->format ); + } + self->format = 0; + self->state = 0; + free( self ); +} + + +// ---------------------------------------------------------------------------- +const char * +vertex_buffer_format( const vertex_buffer_t *self ) +{ + assert( self ); + + return self->format; +} + + +// ---------------------------------------------------------------------------- +size_t +vertex_buffer_size( const vertex_buffer_t *self ) +{ + assert( self ); + + return vector_size( self->items ); +} + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_print( vertex_buffer_t * self ) +{ + int i = 0; + static char *gltypes[9] = { + "GL_BOOL", + "GL_BYTE", + "GL_UNSIGNED_BYTE", + "GL_SHORT", + "GL_UNSIGNED_SHORT", + "GL_INT", + "GL_UNSIGNED_INT", + "GL_FLOAT", + "GL_VOID" + }; + + assert(self); + + fprintf( stderr, "%ld vertices, %ld indices\n", + vector_size( self->vertices ), vector_size( self->indices ) ); + while( self->attributes[i] ) + { + int j = 8; + switch( self->attributes[i]->type ) + { + case GL_BOOL: j=0; break; + case GL_BYTE: j=1; break; + case GL_UNSIGNED_BYTE: j=2; break; + case GL_SHORT: j=3; break; + case GL_UNSIGNED_SHORT: j=4; break; + case GL_INT: j=5; break; + case GL_UNSIGNED_INT: j=6; break; + case GL_FLOAT: j=7; break; + default: j=8; break; + } + fprintf(stderr, "%s : %dx%s (+%p)\n", + self->attributes[i]->name, + self->attributes[i]->size, + gltypes[j], + self->attributes[i]->pointer); + + i += 1; + } +} + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_upload ( vertex_buffer_t *self ) +{ + size_t vsize, isize; + + if( self->state == FROZEN ) + { + return; + } + + if( !self->vertices_id ) + { + glGenBuffers( 1, &self->vertices_id ); + } + if( !self->indices_id ) + { + glGenBuffers( 1, &self->indices_id ); + } + + vsize = self->vertices->size*self->vertices->item_size; + isize = self->indices->size*self->indices->item_size; + + + // Always upload vertices first such that indices do not point to non + // existing data (if we get interrupted in between for example). + + // Upload vertices + glBindBuffer( GL_ARRAY_BUFFER, self->vertices_id ); + if( vsize != self->GPU_vsize ) + { + glBufferData( GL_ARRAY_BUFFER, + vsize, self->vertices->items, GL_DYNAMIC_DRAW ); + self->GPU_vsize = vsize; + } + else + { + glBufferSubData( GL_ARRAY_BUFFER, + 0, vsize, self->vertices->items ); + } + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + + // Upload indices + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, self->indices_id ); + if( isize != self->GPU_isize ) + { + glBufferData( GL_ELEMENT_ARRAY_BUFFER, + isize, self->indices->items, GL_DYNAMIC_DRAW ); + self->GPU_isize = isize; + } + else + { + glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, + 0, isize, self->indices->items ); + } + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_clear( vertex_buffer_t *self ) +{ + assert( self ); + + self->state = FROZEN; + vector_clear( self->indices ); + vector_clear( self->vertices ); + vector_clear( self->items ); + self->state = DIRTY; +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_render_setup ( vertex_buffer_t *self, GLenum mode ) +{ + size_t i; + +#ifdef FREETYPE_GL_USE_VAO + // Unbind so no existing VAO-state is overwritten, + // (e.g. the GL_ELEMENT_ARRAY_BUFFER-binding). + glBindVertexArray( 0 ); +#endif + + if( self->state != CLEAN ) + { + vertex_buffer_upload( self ); + self->state = CLEAN; + } + +#ifdef FREETYPE_GL_USE_VAO + if( self->VAO_id == 0 ) + { + // Generate and set up VAO + + glGenVertexArrays( 1, &self->VAO_id ); + glBindVertexArray( self->VAO_id ); + + glBindBuffer( GL_ARRAY_BUFFER, self->vertices_id ); + + for( i=0; iattributes[i]; + if( attribute == 0 ) + { + continue; + } + else + { + vertex_attribute_enable( attribute ); + } + } + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + + if( self->indices->size ) + { + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, self->indices_id ); + } + } + + // Bind VAO for drawing + glBindVertexArray( self->VAO_id ); +#else + + glBindBuffer( GL_ARRAY_BUFFER, self->vertices_id ); + + for( i=0; iattributes[i]; + if ( attribute == 0 ) + { + continue; + } + else + { + vertex_attribute_enable( attribute ); + } + } + + if( self->indices->size ) + { + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, self->indices_id ); + } +#endif + + self->mode = mode; +} + +// ---------------------------------------------------------------------------- +void +vertex_buffer_render_finish ( vertex_buffer_t *self ) +{ +#ifdef FREETYPE_GL_USE_VAO + glBindVertexArray( 0 ); +#else + int i; + + for( i=0; iattributes[i]; + if( attribute == 0 ) + { + continue; + } + else + { + glDisableVertexAttribArray( attribute->index ); + } + } + + glBindBuffer( GL_ARRAY_BUFFER, 0 ); + glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); +#endif +} + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_render_item ( vertex_buffer_t *self, + size_t index ) +{ + ivec4 * item = (ivec4 *) vector_get( self->items, index ); + assert( self ); + assert( index < vector_size( self->items ) ); + + + if( self->indices->size ) + { + size_t start = item->istart; + size_t count = item->icount; + glDrawElements( self->mode, count, GL_UNSIGNED_INT, (void *)(start*sizeof(GLuint)) ); + } + else if( self->vertices->size ) + { + size_t start = item->vstart; + size_t count = item->vcount; + glDrawArrays( self->mode, start*self->vertices->item_size, count); + } +} + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_render ( vertex_buffer_t *self, GLenum mode ) +{ + size_t vcount = self->vertices->size; + size_t icount = self->indices->size; + + vertex_buffer_render_setup( self, mode ); + if( icount ) + { + glDrawElements( mode, icount, GL_UNSIGNED_INT, 0 ); + } + else + { + glDrawArrays( mode, 0, vcount ); + } + vertex_buffer_render_finish( self ); +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_push_back_indices ( vertex_buffer_t * self, + const GLuint * indices, + const size_t icount ) +{ + assert( self ); + + self->state |= DIRTY; + vector_push_back_data( self->indices, indices, icount ); +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_push_back_vertices ( vertex_buffer_t * self, + const void * vertices, + const size_t vcount ) +{ + assert( self ); + + self->state |= DIRTY; + vector_push_back_data( self->vertices, vertices, vcount ); +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_insert_indices ( vertex_buffer_t *self, + const size_t index, + const GLuint *indices, + const size_t count ) +{ + assert( self ); + assert( self->indices ); + assert( index < self->indices->size+1 ); + + self->state |= DIRTY; + vector_insert_data( self->indices, index, indices, count ); +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_insert_vertices( vertex_buffer_t *self, + const size_t index, + const void *vertices, + const size_t vcount ) +{ + size_t i; + assert( self ); + assert( self->vertices ); + assert( index < self->vertices->size+1 ); + + self->state |= DIRTY; + + for( i=0; iindices->size; ++i ) + { + if( *(GLuint *)(vector_get( self->indices, i )) > index ) + { + *(GLuint *)(vector_get( self->indices, i )) += index; + } + } + + vector_insert_data( self->vertices, index, vertices, vcount ); +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_erase_indices( vertex_buffer_t *self, + const size_t first, + const size_t last ) +{ + assert( self ); + assert( self->indices ); + assert( first < self->indices->size ); + assert( (last) <= self->indices->size ); + + self->state |= DIRTY; + vector_erase_range( self->indices, first, last ); +} + + + +// ---------------------------------------------------------------------------- +void +vertex_buffer_erase_vertices( vertex_buffer_t *self, + const size_t first, + const size_t last ) +{ + size_t i; + assert( self ); + assert( self->vertices ); + assert( first < self->vertices->size ); + assert( last <= self->vertices->size ); + assert( last > first ); + + self->state |= DIRTY; + for( i=0; iindices->size; ++i ) + { + if( *(GLuint *)(vector_get( self->indices, i )) > first ) + { + *(GLuint *)(vector_get( self->indices, i )) -= (last-first); + } + } + vector_erase_range( self->vertices, first, last ); +} + + + +// ---------------------------------------------------------------------------- +size_t +vertex_buffer_push_back( vertex_buffer_t * self, + const void * vertices, const size_t vcount, + const GLuint * indices, const size_t icount ) +{ + return vertex_buffer_insert( self, vector_size( self->items ), + vertices, vcount, indices, icount ); +} + +// ---------------------------------------------------------------------------- +size_t +vertex_buffer_insert( vertex_buffer_t * self, const size_t index, + const void * vertices, const size_t vcount, + const GLuint * indices, const size_t icount ) +{ + size_t vstart, istart, i; + ivec4 item; + assert( self ); + assert( vertices ); + assert( indices ); + + self->state = FROZEN; + + // Push back vertices + vstart = vector_size( self->vertices ); + vertex_buffer_push_back_vertices( self, vertices, vcount ); + + // Push back indices + istart = vector_size( self->indices ); + vertex_buffer_push_back_indices( self, indices, icount ); + + // Update indices within the vertex buffer + for( i=0; iindices, istart+i )) += vstart; + } + + // Insert item + item.x = vstart; + item.y = vcount; + item.z = istart; + item.w = icount; + vector_insert( self->items, index, &item ); + + self->state = DIRTY; + return index; +} + +// ---------------------------------------------------------------------------- +void +vertex_buffer_erase( vertex_buffer_t * self, + const size_t index ) +{ + ivec4 * item; + int vstart; + size_t vcount, istart, icount, i; + + assert( self ); + assert( index < vector_size( self->items ) ); + + item = (ivec4 *) vector_get( self->items, index ); + vstart = item->vstart; + vcount = item->vcount; + istart = item->istart; + icount = item->icount; + + // Update items + for( i=0; iitems); ++i ) + { + ivec4 * item = (ivec4 *) vector_get( self->items, i ); + if( item->vstart > vstart) + { + item->vstart -= vcount; + item->istart -= icount; + } + } + + self->state = FROZEN; + vertex_buffer_erase_indices( self, istart, istart+icount ); + vertex_buffer_erase_vertices( self, vstart, vstart+vcount ); + vector_erase( self->items, index ); + self->state = DIRTY; +} diff --git a/src/freetype-gl/vertex-buffer.h b/src/freetype-gl/vertex-buffer.h new file mode 100644 index 00000000..85a88cc6 --- /dev/null +++ b/src/freetype-gl/vertex-buffer.h @@ -0,0 +1,327 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +#ifndef __VERTEX_BUFFER_H__ +#define __VERTEX_BUFFER_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "opengl.h" +#include "vector.h" +#include "vertex-attribute.h" + +#ifdef __cplusplus +namespace ftgl { +#endif + +/** + * @file vertex-buffer.h + * @author Nicolas Rougier (Nicolas.Rougier@inria.fr) + * @date April, 2012 + * + * @defgroup vertex-buffer Vertex buffer + * + * @{ + */ + + +/** + * Generic vertex buffer. + */ +typedef struct vertex_buffer_t +{ + /** Format of the vertex buffer. */ + char * format; + + /** Vector of vertices. */ + vector_t * vertices; + +#ifdef FREETYPE_GL_USE_VAO + /** GL identity of the Vertex Array Object */ + GLuint VAO_id; +#endif + + /** GL identity of the vertices buffer. */ + GLuint vertices_id; + + /** Vector of indices. */ + vector_t * indices; + + /** GL identity of the indices buffer. */ + GLuint indices_id; + + /** Current size of the vertices buffer in GPU */ + size_t GPU_vsize; + + /** Current size of the indices buffer in GPU*/ + size_t GPU_isize; + + /** GL primitives to render. */ + GLenum mode; + + /** Whether the vertex buffer needs to be uploaded to GPU memory. */ + char state; + + /** Individual items */ + vector_t * items; + + /** Array of attributes. */ + vertex_attribute_t *attributes[MAX_VERTEX_ATTRIBUTE]; +} vertex_buffer_t; + + +/** + * Creates an empty vertex buffer. + * + * @param format a string describing vertex format. + * @return an empty vertex buffer. + */ + vertex_buffer_t * + vertex_buffer_new( const char *format ); + + +/** + * Deletes vertex buffer and releases GPU memory. + * + * @param self a vertex buffer + */ + void + vertex_buffer_delete( vertex_buffer_t * self ); + + +/** + * Returns the number of items in the vertex buffer + * + * @param self a vertex buffer + * @return number of items + */ + size_t + vertex_buffer_size( const vertex_buffer_t *self ); + + +/** + * Returns vertex format + * + * @param self a vertex buffer + * @return vertex format + */ + const char * + vertex_buffer_format( const vertex_buffer_t *self ); + + +/** + * Print information about a vertex buffer + * + * @param self a vertex buffer + */ + void + vertex_buffer_print( vertex_buffer_t * self ); + + +/** + * Prepare vertex buffer for render. + * + * @param self a vertex buffer + * @param mode render mode + */ + void + vertex_buffer_render_setup ( vertex_buffer_t *self, + GLenum mode ); + + +/** + * Finish rendering by setting back modified states + * + * @param self a vertex buffer + */ + void + vertex_buffer_render_finish ( vertex_buffer_t *self ); + + +/** + * Render vertex buffer. + * + * @param self a vertex buffer + * @param mode render mode + */ + void + vertex_buffer_render ( vertex_buffer_t *self, + GLenum mode ); + + +/** + * Render a specified item from the vertex buffer. + * + * @param self a vertex buffer + * @param index index of the item to be rendered + */ + void + vertex_buffer_render_item ( vertex_buffer_t *self, + size_t index ); + + +/** + * Upload buffer to GPU memory. + * + * @param self a vertex buffer + */ + void + vertex_buffer_upload( vertex_buffer_t *self ); + + +/** + * Clear all items. + * + * @param self a vertex buffer + */ + void + vertex_buffer_clear( vertex_buffer_t *self ); + + +/** + * Appends indices at the end of the buffer. + * + * @param self a vertex buffer + * @param indices indices to be appended + * @param icount number of indices to be appended + * + * @private + */ + void + vertex_buffer_push_back_indices ( vertex_buffer_t *self, + const GLuint * indices, + const size_t icount ); + + +/** + * Appends vertices at the end of the buffer. + * + * @note Internal use + * + * @param self a vertex buffer + * @param vertices vertices to be appended + * @param vcount number of vertices to be appended + * + * @private + */ + void + vertex_buffer_push_back_vertices ( vertex_buffer_t *self, + const void * vertices, + const size_t vcount ); + + +/** + * Insert indices in the buffer. + * + * @param self a vertex buffer + * @param index location before which to insert indices + * @param indices indices to be appended + * @param icount number of indices to be appended + * + * @private + */ + void + vertex_buffer_insert_indices ( vertex_buffer_t *self, + const size_t index, + const GLuint *indices, + const size_t icount ); + + +/** + * Insert vertices in the buffer. + * + * @param self a vertex buffer + * @param index location before which to insert vertices + * @param vertices vertices to be appended + * @param vcount number of vertices to be appended + * + * @private + */ + void + vertex_buffer_insert_vertices ( vertex_buffer_t *self, + const size_t index, + const void *vertices, + const size_t vcount ); + +/** + * Erase indices in the buffer. + * + * @param self a vertex buffer + * @param first the index of the first index to be erased + * @param last the index of the last index to be erased + * + * @private + */ + void + vertex_buffer_erase_indices ( vertex_buffer_t *self, + const size_t first, + const size_t last ); + +/** + * Erase vertices in the buffer. + * + * @param self a vertex buffer + * @param first the index of the first vertex to be erased + * @param last the index of the last vertex to be erased + * + * @private + */ + void + vertex_buffer_erase_vertices ( vertex_buffer_t *self, + const size_t first, + const size_t last ); + + +/** + * Append a new item to the collection. + * + * @param self a vertex buffer + * @param vcount number of vertices + * @param vertices raw vertices data + * @param icount number of indices + * @param indices raw indices data + */ + size_t + vertex_buffer_push_back( vertex_buffer_t * self, + const void * vertices, const size_t vcount, + const GLuint * indices, const size_t icount ); + + +/** + * Insert a new item into the vertex buffer. + * + * @param self a vertex buffer + * @param index location before which to insert item + * @param vertices raw vertices data + * @param vcount number of vertices + * @param indices raw indices data + * @param icount number of indices + */ + size_t + vertex_buffer_insert( vertex_buffer_t * self, + const size_t index, + const void * vertices, const size_t vcount, + const GLuint * indices, const size_t icount ); + +/** + * Erase an item from the vertex buffer. + * + * @param self a vertex buffer + * @param index index of the item to be deleted + */ + void + vertex_buffer_erase( vertex_buffer_t * self, + const size_t index ); + +/** @} */ + +#ifdef __cplusplus +} +} +#endif + +#endif /* __VERTEX_BUFFER_H__ */ diff --git a/src/ftrender.cpp b/src/ftrender.cpp new file mode 100644 index 00000000..09741b2d --- /dev/null +++ b/src/ftrender.cpp @@ -0,0 +1,172 @@ +/* + * ftrender.cpp + * + * Created on: May 20, 2017 + * Author: nullifiedcat + */ + +#include "ftrender.hpp" + +extern "C" { +#include +#include +#include +#include +} + +#include "drawing.h" +#include "helpers.h" +#include "logging.h" + +using namespace ftgl; + +typedef struct { + float x, y, z; + float s, t; + rgba_t rgba; +} vertex_t; + +vertex_buffer_t* buffer; +texture_atlas_t* atlas; +vec2 pen; +GLuint shader; +mat4 model, view, projection; + +void FTGL_PreInit() { + pen.x = pen.y = 0; + atlas = texture_atlas_new(1024, 1024, 1); + buffer = vertex_buffer_new("vertex:3f,tex_coord:2f,color:4f"); + mat4_set_identity(&projection); + mat4_set_identity(&view); + mat4_set_identity(&model); + mat4_set_orthographic(&projection, 0, draw::width, 0, draw::height, -1, 1); + fonts::ftgl_ESP = ftgl::texture_font_new_from_file(atlas, 14, "cathook/fonts/opensans-bold.ttf"); + logging::Info("Pre-Init done %d %d", draw::width, draw::height); +} + +void FTGL_Init() { + logging::Info("Init glew.."); + glewInit(); + logging::Info("Done..."); + glGenTextures(1, &atlas->id); + logging::Info("Loading shaders..."); + shader = shader_load("cathook/shaders/v3f-t2f-c4f.vert", "cathook/shaders/v3f-t2f-c4f.frag"); + logging::Info("Done init"); +} + +void add_text(vertex_buffer_t * buffer, texture_font_t * font, + const std::string& text, vec2 pen, const rgba_t& fg_color_1, const rgba_t& fg_color_2, int *size_x = nullptr, int *size_y = nullptr) +{ + vec2 v_size { pen.x, 0 }; + size_t i; + for( i = 0; i < text.length(); ++i ) + { + texture_glyph_t *glyph = texture_font_get_glyph( font, &text.at(i) ); + float kerning = 0.0f; + if( i > 0) + { + kerning = texture_glyph_get_kerning( glyph, &text.at(i - 1) ); + } + pen.x += kerning; + + /* Actual glyph */ + float x0 = ( pen.x + glyph->offset_x ); + float y0 = (int)( pen.y + glyph->offset_y ); + float x1 = ( x0 + glyph->width ); + float y1 = (int)( y0 - glyph->height ); + float s0 = glyph->s0; + float t0 = glyph->t0; + float s1 = glyph->s1; + float t1 = glyph->t1; + GLuint index = buffer->vertices->size; + GLuint indices[] = {index, index+1, index+2, + index, index+2, index+3}; + vertex_t vertices[] = { + { (int)x0,y0,0, s0,t0, fg_color_1 }, + { (int)x0,y1,0, s0,t1, fg_color_2 }, + { (int)x1,y1,0, s1,t1, fg_color_2 }, + { (int)x1,y0,0, s1,t0, fg_color_1 } }; + vertex_buffer_push_back_indices( buffer, indices, 6 ); + vertex_buffer_push_back_vertices( buffer, vertices, 4 ); + pen.x += glyph->advance_x; + if (glyph->height > v_size.y) v_size.y = glyph->height; + } + v_size.x = pen.x - v_size.x; + if (size_x) *size_x = v_size.x; + if (size_y) *size_y = v_size.y; +} + +void FTGL_Draw(const std::string& text, int x, int y, ftgl::texture_font_t* font, const rgba_t& clr, int *size_x, int *size_y) { + rgba_t black = { 0.0, 0.0, 0.0, 1.0 }; + black.a = clr.a; + font->rendermode = RENDER_OUTLINE_POSITIVE; + font->outline_thickness = 1.0f; + add_text(buffer, font, text, vec2{ x, draw::height - y - font->height }, black, black); + font->rendermode = RENDER_NORMAL; + font->outline_thickness = 0.0f; + add_text(buffer, font, text, vec2{ x, draw::height - y - font->height }, clr, clr, size_x, size_y); +} + +void FTGL_NewFrame() { + vertex_buffer_clear(buffer); +} + +void FTGL_ChangeFont(texture_font_t** font, const char* newfont) { + texture_atlas_clear(atlas); + texture_font_t* replacement = texture_font_new_from_file(atlas, 14, strfmt("cathook/fonts/%s.ttf", newfont)); + if (replacement) { + texture_font_delete(*font); + *font = replacement; + } +} + +void FTGL_Render() { + static GLint loc_texture, loc_model, loc_view, loc_projection; + static bool loc_init { false }; + + if (buffer->indices->size == 0) { + return; + } + + glUseProgram(shader); + if (!loc_init) { + loc_texture = glGetUniformLocation(shader, "texture"); + loc_model = glGetUniformLocation(shader, "model"); + loc_view = glGetUniformLocation(shader, "view"); + loc_projection = glGetUniformLocation(shader, "projection"); + loc_init = true; + } + glBindTexture(GL_TEXTURE_2D, atlas->id); + if (atlas->dirty) { + logging::Info("[DEBUG] Atlas updated."); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, atlas->width, atlas->height, 0, GL_RED, GL_UNSIGNED_BYTE, atlas->data); + atlas->dirty = false; + } + glUniform1i(loc_texture, 0); + glUniformMatrix4fv(loc_model, 1, 0, model.data); + glUniformMatrix4fv(loc_view, 1, 0, view.data); + glUniformMatrix4fv(loc_projection, 1, 0, projection.data); + vertex_buffer_render(buffer, GL_TRIANGLES); +} + +void FTGL_StringLength(const std::string& text, ftgl::texture_font_t* font, int *size_x, int *size_y) { + vec2 pen { 0, 0 }; + for (size_t i = 0; i < text.length(); ++i) { + texture_glyph_t *glyph = texture_font_get_glyph(font, &text.at(i)); + float kerning = 0.0f; + if (i) { + kerning = texture_glyph_get_kerning(glyph, &text.at(i - 1)); + } + pen.x += kerning; + + /* Actual glyph */ + if (pen.y < glyph->height) pen.y = glyph->height; + pen.x += glyph->advance_x; + } + if (size_x) *size_x = pen.x; + if (size_y) *size_y = pen.y; +} diff --git a/src/ftrender.hpp b/src/ftrender.hpp new file mode 100644 index 00000000..92b42007 --- /dev/null +++ b/src/ftrender.hpp @@ -0,0 +1,27 @@ +/* + * ftrender.hpp + * + * Created on: May 20, 2017 + * Author: nullifiedcat + */ + +#ifndef FTRENDER_HPP_ +#define FTRENDER_HPP_ + +#include "common.h" + +extern "C" { +#include +} + +extern ftgl::texture_atlas_t* atlas; + +void FTGL_PreInit(); +void FTGL_Init(); +void FTGL_Draw(const std::string& text, int x, int y, ftgl::texture_font_t* font, const rgba_t& color = colors::white, int *size_x = nullptr, int *size_y = nullptr); +void FTGL_NewFrame(); +void FTGL_Render(); +void FTGL_StringLength(const std::string& text, ftgl::texture_font_t* font, int *size_x = nullptr, int *size_y = nullptr); +void FTGL_ChangeFont(ftgl::texture_font_t** font, const char* newfont); + +#endif /* FTRENDER_HPP_ */ diff --git a/src/gameinfo.hpp b/src/gameinfo.hpp index 74a5f51d..9d8f8864 100644 --- a/src/gameinfo.hpp +++ b/src/gameinfo.hpp @@ -29,6 +29,7 @@ constexpr bool IsTF2() { return !c_strcmp(TO_STRING(BUILD_GAME), "tf2"); } constexpr bool IsTF2C() { return !c_strcmp(TO_STRING(BUILD_GAME), "tf2c"); } constexpr bool IsHL2DM() { return !c_strcmp(TO_STRING(BUILD_GAME), "hl2dm"); } constexpr bool IsCSS() { return !c_strcmp(TO_STRING(BUILD_GAME), "css"); } +constexpr bool IsDynamic() { return !c_strcmp(TO_STRING(BUILD_GAME), "dynamic"); } constexpr bool IsTF() { return IsTF2() || IsTF2C(); } @@ -40,6 +41,7 @@ inline bool IsTF2() { return g_AppID == 440; } inline bool IsTF2C() { return g_AppID == 243750; } inline bool IsHL2DM() { return g_AppID == 320; } inline bool IsCSS() { return g_AppID == 240; } +constexpr bool IsDynamic() { return false; } inline bool IsTF() { return IsTF2() || IsTF2C(); } @@ -47,10 +49,4 @@ inline bool IsTF() { return IsTF2() || IsTF2C(); } #endif -#ifndef FORCE_SINGLE_GAME -#define CURRENT_APPID g_AppID -#else -#define CURRENT_APPID (SINGLE_APPID) -#endif - #endif /* GAMEINFO_HPP_ */ diff --git a/src/globals.cpp b/src/globals.cpp index b3a538dc..f4ad12e3 100644 --- a/src/globals.cpp +++ b/src/globals.cpp @@ -9,18 +9,23 @@ #include "sdk.h" #include "copypasted/CSignature.h" -EstimateAbsVelocity_t* EstimateAbsVelocity = 0; int g_AppID = 0; void ThirdpersonCallback(IConVar* var, const char* pOldValue, float flOldValue) { if (force_thirdperson.convar_parent && !force_thirdperson) { - if (g_pLocalPlayer && g_pLocalPlayer->entity) + if (g_pLocalPlayer && CE_GOOD(g_pLocalPlayer->entity)) CE_INT(g_pLocalPlayer->entity, netvar.nForceTauntCam) = 0; } } +ConVar* sv_client_min_interp_ratio; +ConVar* cl_interp_ratio; +ConVar* cl_interp; +ConVar* cl_interpolate; + unsigned long tickcount = 0; +char* force_name_newlined = new char[32] { 0 }; bool need_name_change = true; int last_cmd_number = 0; CatVar force_name(CV_STRING, "name", "", "Force name"); @@ -33,18 +38,36 @@ CatVar force_thirdperson(CV_SWITCH, "thirdperson", "0", "Thirdperson", "Enable t CatVar console_logging(CV_SWITCH, "log", "1", "Debug Log", "Disable this if you don't need cathook messages in your console"); //CatVar fast_outline(CV_SWITCH, "fastoutline", "0", "Low quality outline", "Might increase performance when there is a lot of ESP text to draw"); CatVar roll_speedhack(CV_KEY, "rollspeedhack", "0", "Roll Speedhack", "Roll speedhack key"); +char* disconnect_reason_newlined = new char[256] { 0 }; +CatVar disconnect_reason(CV_STRING, "disconnect_reason", "", "Disconnect reason", "A custom disconnect reason"); +CatVar event_log(CV_SWITCH, "events", "1", "Advanced Events"); void GlobalSettings::Init() { + sv_client_min_interp_ratio = g_ICvar->FindVar("sv_client_min_interp_ratio"); + cl_interp_ratio = g_ICvar->FindVar("cl_interp_ratio"); + cl_interp = g_ICvar->FindVar("cl_interp"); + cl_interpolate = g_ICvar->FindVar("cl_interpolate"); + bSendPackets = new bool; *bSendPackets = true; - EstimateAbsVelocity = (EstimateAbsVelocity_t*)gSignatures.GetClientSignature("55 89 E5 56 53 83 EC 30 8B 5D 08 8B 75 0C E8 4D 2E 01 00 39 D8 74 69 0F B6 05 24 3F 00 02 81 C3 B8 02 00 00 C6 05 24 3F 00 02 01 88 45 F0 A1 20 3F 00 02 89 45 F4 A1 28 3F 00 02 89 45 EC 8D 45 EC A3 28 3F 00 02 A1 14 C8 F6 01 8B 40 0C 89 74 24 04 89 1C 24 89 44 24 08 E8 A2 41 00 00 0F B6 45 F0 A2 24 3F 00 02 8B 45 F4 A3 20 3F 00 02 8B 45 EC A3 28 3F 00 02 83 C4 30 5B 5E 5D C3"); force_thirdperson.OnRegister([](CatVar* var) { var->convar_parent->InstallChangeCallback(ThirdpersonCallback); }); + force_name.InstallChangeCallback([](IConVar* var, const char* old, float oldfl) { + std::string nl(force_name.GetString()); + ReplaceString(nl, "\\n", "\n"); + strncpy(force_name_newlined, nl.c_str(), 31); + (void)oldfl; + }); + disconnect_reason.InstallChangeCallback([](IConVar* var, const char* old, float oldfl) { + std::string nl(disconnect_reason.GetString()); + ReplaceString(nl, "\\n", "\n"); + strncpy(disconnect_reason_newlined, nl.c_str(), 255); + (void)oldfl; + }); bInvalid = true; } CUserCmd* g_pUserCmd = nullptr; -const char* g_pszTFPath = 0; GlobalSettings g_Settings; diff --git a/src/globals.h b/src/globals.h index fa343bdb..1615a516 100644 --- a/src/globals.h +++ b/src/globals.h @@ -12,12 +12,15 @@ class Vector; class ConVar; class CatVar; -typedef void(EstimateAbsVelocity_t)(IClientEntity*, Vector&); -extern EstimateAbsVelocity_t* EstimateAbsVelocity; - extern int g_AppID; extern unsigned long tickcount; +extern ConVar* sv_client_min_interp_ratio; +extern ConVar* cl_interp_ratio; +extern ConVar* cl_interp; +extern ConVar* cl_interpolate; + +extern CatVar event_log; extern CatVar cathook; // Master switch extern CatVar ignore_taunting; extern bool* bSendPackets; @@ -27,9 +30,13 @@ extern CatVar console_logging; extern CatVar fast_outline; extern CatVar roll_speedhack; extern CatVar force_name; +extern char* force_name_newlined; extern bool need_name_change; extern int last_cmd_number; +extern char* disconnect_reason_newlined; +extern CatVar disconnect_reason; + class GlobalSettings { public: void Init(); @@ -39,7 +46,6 @@ public: class CUserCmd; extern CUserCmd* g_pUserCmd; -extern const char* g_pszTFPath; extern GlobalSettings g_Settings; diff --git a/src/glowobjects.cpp b/src/glowobjects.cpp deleted file mode 100644 index 78e2c561..00000000 --- a/src/glowobjects.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - * glowobjects.cpp - * - * Created on: Jan 16, 2017 - * Author: nullifiedcat - */ - -#include "glowobjects.h" -#include "common.h" - -static CatEnum glow_color_scheme_enum({"ESP", "HEALTH"}); -static CatVar glow_color_scheme(glow_color_scheme_enum, "glow_old_color_scheme", "1", "Colors", "Doesn't need a description"); -// Doesn't work - has to be registered manually. -static CatVar glow_ammo_boxes(CV_SWITCH, "glow_old_ammo_boxes", "0", "Ammo", "Render glow on ammoboxes"); -static CatVar glow_health_packs(CV_SWITCH, "glow_old_health_packs", "0", "Health", "Render glow on medkits"); -static CatVar glow_teammates(CV_SWITCH, "glow_old_teammates", "0", "Teammates", "Render glow on teammates"); -static CatVar glow_teammate_buildings(CV_SWITCH, "glow_old_teammate_buildings", "0", "Teammate buildings", "Render glow on teammates buildings"); -static CatVar glow_buildings(CV_SWITCH, "glow_old_buildings", "1", "Buildings", "Render glow on buildings"); -static CatVar glow_stickies(CV_SWITCH, "glow_old_stickies", "0", "Stickies", "Render glow on stickybombs"); -static CatVar glow_players(CV_SWITCH, "glow_old_players", "1", "Players", "Render glow on player models"); - -static CatVar glow_enabled(CV_SWITCH, "glow_old_enabled", "0", "Enable", "Make sure to enable glow_outline_effect_enable in tf2 settings"); -static CatVar glow_alpha(CV_FLOAT, "glow_old_alpha", "1", "Alpha", "Glow Transparency", 0.0f, 1.0f); - -void GlowFrameStageNotify(int stage) { - static ConVar* glow_outline_effect = g_ICvar->FindVar("glow_outline_effect_enable"); - if (glow_outline_effect->GetBool()) { - PROF_SECTION(FSN_outline); - if (glow_enabled) { - for (int i = 0; i < g_GlowObjectManager->m_GlowObjectDefinitions.Size(); i++) { - GlowObjectDefinition_t& glowobject = g_GlowObjectManager->m_GlowObjectDefinitions[i]; - if (glowobject.m_nNextFreeSlot != ENTRY_IN_USE) - continue; - int color = GetEntityGlowColor(glowobject.m_hEntity.m_Index & 0xFFF); - if (color == 0) { - glowobject.m_flGlowAlpha = 0.0f; - } else { - glowobject.m_flGlowAlpha = (float)glow_alpha; - } - unsigned char _b = (color >> 16) & 0xFF; - unsigned char _g = (color >> 8) & 0xFF; - unsigned char _r = (color) & 0xFF; - glowobject.m_vGlowColor.x = (float)_r / 255.0f; - glowobject.m_vGlowColor.y = (float)_g / 255.0f; - glowobject.m_vGlowColor.z = (float)_b / 255.0f; - } - } - // Remove glow from dead entities - for (int i = 0; i < g_GlowObjectManager->m_GlowObjectDefinitions.Count(); i++) { - if (g_GlowObjectManager->m_GlowObjectDefinitions[i].m_nNextFreeSlot != ENTRY_IN_USE) continue; - IClientEntity* ent = (IClientEntity*)g_IEntityList->GetClientEntityFromHandle(g_GlowObjectManager->m_GlowObjectDefinitions[i].m_hEntity); - if (ent && ent->IsDormant()) { - g_GlowObjectManager->DisableGlow(i); - } else if (ent && ent->GetClientClass()->m_ClassID == RCC_PLAYER) { - if (NET_BYTE(ent, netvar.iLifeState) != LIFE_ALIVE) { - g_GlowObjectManager->DisableGlow(i); - } - } - } - if (glow_enabled) { - for (int i = 1; i < g_IEntityList->GetHighestEntityIndex(); i++) { - IClientEntity* entity = g_IEntityList->GetClientEntity(i); - if (!entity || i == g_IEngine->GetLocalPlayer() || entity->IsDormant()) - continue; - if (!CanEntityEvenGlow(i)) continue; - int clazz = entity->GetClientClass()->m_ClassID; - int current_handle = g_GlowObjectManager->GlowHandle(entity); - bool shouldglow = ShouldEntityGlow(i); - if (current_handle != -1) { - if (!shouldglow) { - g_GlowObjectManager->DisableGlow(current_handle); - } - } else { - if (shouldglow) { - g_GlowObjectManager->EnableGlow(entity, colors::white); - } - } - } - } - } -} - -int CGlowObjectManager::EnableGlow(IClientEntity* entity, int color) { - int idx = GlowHandle(entity); - if (idx != -1) { - logging::Info("[WARNING] Glow handle exists!!!"); - return idx; - } - if (m_nFirstFreeSlot == END_OF_FREE_LIST) { - idx = m_GlowObjectDefinitions.AddToTail(); - } else { - idx = m_nFirstFreeSlot; - m_nFirstFreeSlot = m_GlowObjectDefinitions[idx].m_nNextFreeSlot; - } - g_CathookManagedGlowObjects.insert(idx); - GlowObjectDefinition_t& def = m_GlowObjectDefinitions[idx]; - def.m_bRenderWhenOccluded = true; - def.m_bRenderWhenUnoccluded = true; - def.m_flGlowAlpha = 1.0f; - def.m_hEntity = CBaseHandle(); - def.m_hEntity.Set(entity); - unsigned char _b = (color >> 16) & 0xFF; - unsigned char _g = (color >> 8) & 0xFF; - unsigned char _r = (color) & 0xFF; - def.m_vGlowColor = Vector((float)_r / 255.0f, (float)_g / 255.0f, (float)_b / 255.0f); - def.m_nNextFreeSlot = ENTRY_IN_USE; - def.m_nSplitScreenSlot = -1; - return idx; -} - -void CGlowObjectManager::DisableGlow(int idx) { - const auto& it = g_CathookManagedGlowObjects.find(idx); - if (it == g_CathookManagedGlowObjects.end()) { - return; - } - g_CathookManagedGlowObjects.erase(it); - m_GlowObjectDefinitions[idx].m_nNextFreeSlot = m_nFirstFreeSlot; - m_GlowObjectDefinitions[idx].m_hEntity = NULL; - m_nFirstFreeSlot = idx; -} - -int CGlowObjectManager::GlowHandle(IClientEntity* entity) const { - for (int i = 0; i < m_GlowObjectDefinitions.Count(); i++) { - if (m_GlowObjectDefinitions[i].m_nNextFreeSlot == ENTRY_IN_USE && (m_GlowObjectDefinitions[i].m_hEntity.m_Index & 0xFFF) == entity->entindex()) return i; - } - return -1; -} - -int GetEntityGlowColor(int idx) { - if (idx < 0 || idx > g_IEntityList->GetHighestEntityIndex()) return colors::white; - CachedEntity* ent = ENTITY(idx); - if (CE_BAD(ent)) return colors::white; - switch (ent->m_Type) { - case ENTITY_BUILDING: - if (!ent->m_bEnemy && !(glow_teammates || glow_teammate_buildings)) { - return 0; - } - if ((int)glow_color_scheme == 1) { - return colors::Health(ent->m_iHealth, ent->m_iMaxHealth); - } - break; - case ENTITY_PLAYER: - if (!glow_players) return 0; - if (!ent->m_bEnemy && !glow_teammates) return 0; - if ((int)glow_color_scheme == 1) { - return colors::Health(ent->m_iHealth, ent->m_iMaxHealth); - } - break; - } - return colors::EntityF(ent); -} - -bool CanEntityEvenGlow(int idx) { - IClientEntity* entity = g_IEntityList->GetClientEntity(idx); - if (!entity) return false; - int classid = entity->GetClientClass()->m_ClassID; - return (classid == CL_CLASS(CTFAmmoPack) || classid == CL_CLASS(CTFPlayer) || classid == CL_CLASS(CTFGrenadePipebombProjectile) || classid == CL_CLASS(CObjectDispenser) || classid == CL_CLASS(CObjectSentrygun) || classid == CL_CLASS(CObjectTeleporter) || classid == CL_CLASS(CBaseAnimating)); -} - -bool ShouldEntityGlow(int idx) { - CachedEntity* ent = ENTITY(idx); - if (CE_BAD(ent)) return false; - switch (ent->m_Type) { - case ENTITY_BUILDING: - if (!glow_buildings) return false; - if (!ent->m_bEnemy && !(glow_teammate_buildings || glow_teammates)) return false; - return true; - case ENTITY_PLAYER: - if (!glow_players) return false; - if (!glow_teammates && !ent->m_bEnemy) return false; - if (CE_BYTE(ent, netvar.iLifeState) != LIFE_ALIVE) return false; - return true; - break; - case ENTITY_PROJECTILE: - if (!ent->m_bEnemy) return false; - if (glow_stickies && ent->m_iClassID == CL_CLASS(CTFGrenadePipebombProjectile)) { - return true; - } - break; - case ENTITY_GENERIC: - switch (ent->m_ItemType) { - case ITEM_HEALTH_LARGE: - case ITEM_HEALTH_MEDIUM: - case ITEM_HEALTH_SMALL: - return glow_health_packs; - case ITEM_AMMO_LARGE: - case ITEM_AMMO_MEDIUM: - case ITEM_AMMO_SMALL: - return glow_ammo_boxes; - } - break; - } - return false; -} - -std::set g_CathookManagedGlowObjects {}; - -CGlowObjectManager* g_GlowObjectManager = 0; diff --git a/src/glowobjects.h b/src/glowobjects.h deleted file mode 100644 index 5ef0e320..00000000 --- a/src/glowobjects.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * glowobjects.h - * - * Created on: Jan 16, 2017 - * Author: nullifiedcat - */ - -#ifndef GLOWOBJECTS_H_ -#define GLOWOBJECTS_H_ - -#define END_OF_FREE_LIST -1 -#define ENTRY_IN_USE -2 - -#include "common.h" - -//template class CUtlVector; - -extern std::set g_CathookManagedGlowObjects; - -struct GlowObjectDefinition_t { - CBaseHandle m_hEntity; - Vector m_vGlowColor; - float m_flGlowAlpha; - bool m_bRenderWhenOccluded; - bool m_bRenderWhenUnoccluded; - int m_nSplitScreenSlot; - int m_nNextFreeSlot; -}; - -class CGlowObjectManager { -public: - int EnableGlow(IClientEntity* entity, int color); - void DisableGlow(int idx); - int GlowHandle(IClientEntity* entity) const; - CUtlVector m_GlowObjectDefinitions; - int m_nFirstFreeSlot; -}; - -extern CGlowObjectManager* g_GlowObjectManager; - -bool CanEntityEvenGlow(int idx); -int GetEntityGlowColor(int idx); -bool ShouldEntityGlow(int idx); -void GlowFrameStageNotify(int stage); - -#endif /* GLOWOBJECTS_H_ */ diff --git a/src/gui/CBaseButton.cpp b/src/gui/CBaseButton.cpp deleted file mode 100644 index 06b88abe..00000000 --- a/src/gui/CBaseButton.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - * CBaseButton.cpp - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#include "CBaseButton.h" - -#include "../common.h" -#include "../sdk.h" - -CBaseButton::CBaseButton(std::string name, IWidget* parent, std::string text, ButtonCallbackFn_t callback) : CTextLabel(name, parent, text) { - SetPadding(BUTTON_PADDING_W, BUTTON_PADDING_H); - SetText(text); - if (callback) SetCallback(callback); -} - -void CBaseButton::SetCallback(ButtonCallbackFn_t callback) { - m_pCallback = callback; -} - -void CBaseButton::Draw(int x, int y) { - int textcolor = GUIColor(); - auto size = GetSize(); - if (IsPressed()) { - draw::DrawRect(x, y, size.first, size.second, GUIColor()); - textcolor = colors::white; - } - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - draw::String(fonts::MENU, x + Props()->GetInt("padding_x"), y + Props()->GetInt("padding_y"), textcolor, 1, GetText()); -} - -void CBaseButton::OnMousePress() { - CBaseWidget::OnMousePress(); - if (m_pCallback) { - m_pCallback(this); - } -} diff --git a/src/gui/CBaseButton.h b/src/gui/CBaseButton.h deleted file mode 100644 index 90322e04..00000000 --- a/src/gui/CBaseButton.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * CBaseButton.h - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#ifndef CBASEBUTTON_H_ -#define CBASEBUTTON_H_ - -#include "../beforecheaders.h" -#include -#include "../aftercheaders.h" - -#include "CTextLabel.h" - -#define BUTTON_PADDING_W 3 -#define BUTTON_PADDING_H 2 - -class CBaseButton; - -typedef std::function ButtonCallbackFn_t; - -class CBaseButton : public CTextLabel { -public: - CBaseButton(std::string name = "unnamed", IWidget* parent = nullptr, std::string text = "", ButtonCallbackFn_t callback = nullptr); - - virtual void Draw(int x, int y); - virtual void OnMousePress() override; - - void SetCallback(ButtonCallbackFn_t callback); - - ButtonCallbackFn_t m_pCallback; -}; - -#endif /* CBASEBUTTON_H_ */ diff --git a/src/gui/CBaseContainer.cpp b/src/gui/CBaseContainer.cpp deleted file mode 100644 index 70e5b81d..00000000 --- a/src/gui/CBaseContainer.cpp +++ /dev/null @@ -1,203 +0,0 @@ -/* - * CBaseContainer.cpp - * - * Created on: Jan 31, 2017 - * Author: nullifiedcat - */ - -#include "CBaseContainer.h" - -#include "../common.h" -#include "../sdk.h" - -class IMemAlloc; -IMemAlloc* g_pMemAlloc = 0; - -CBaseContainer::CBaseContainer(std::string name, IWidget* parent) : CBaseWidget(name, parent) { - m_pFocusedChild = 0; - m_pHoveredChild = 0; - m_pPressedChild = 0; -} - -void CBaseContainer::HandleCustomEvent(KeyValues* event) { - for (auto& child : m_children) { - child->HandleCustomEvent(event); - } -} - -void CBaseContainer::AddChild(IWidget* child) { - m_children.push_back(child); - child->SetParent(this); - //auto maxs = GetMaxSize(); - //child->SetMaxSize(maxs.first, maxs.second); -} - -IWidget* CBaseContainer::ChildByIndex(int idx) { - if (idx < 0 || idx >= ChildCount()) return nullptr; - return m_children.at(idx); -} - -IWidget* CBaseContainer::ChildByName(std::string name) { - for (auto child : m_children) { - if (!child->GetName().compare(name)) { - return child; - } - } - return nullptr; -} - -IWidget* CBaseContainer::ChildByPoint(int x, int y) { - for (int i = ChildCount() - 1; i >= 0; i--) { - auto child = ChildByIndex(i); - if (!child->IsVisible()) continue; - auto co = child->GetOffset(); - auto cs = child->GetSize(); - if (x >= co.first && x <= co.first + cs.first && - y >= co.second && y <= co.second + cs.second) { - return child; - } - } - return nullptr; -} - -int CBaseContainer::ChildCount() { - return m_children.size(); -} - -void CBaseContainer::Draw(int x, int y) { - for (auto child : m_children) { - if (child->IsVisible()) { - auto off = child->GetOffset(); - if (AlwaysVisible() || g_pGUI->Visible() || child->AlwaysVisible()) - child->Draw(x + off.first, y + off.second); - } - } -} - -void CBaseContainer::DrawBounds(int x, int y) { - for (auto child : m_children) { - if (child->IsVisible()) { - auto off = child->GetOffset(); - child->DrawBounds(x + off.first, y + off.second); - } - } - CBaseWidget::DrawBounds(x, y); -} - -void CBaseContainer::FocusOn(IWidget* child) { - if (GetFocusedChild() != child) { - if (GetFocusedChild()) GetFocusedChild()->OnFocusLose(); - if (child) child->OnFocusGain(); - m_pFocusedChild = child; - } -} - -IWidget* CBaseContainer::GetFocusedChild() { - return m_pFocusedChild; -} - -IWidget* CBaseContainer::GetHoveredChild() { - return m_pHoveredChild; -} - -IWidget* CBaseContainer::GetPressedChild() { - return m_pPressedChild; -} - -bool CBaseContainer::ConsumesKey(ButtonCode_t key) { - if (GetFocusedChild()) return GetFocusedChild()->ConsumesKey(key); - return false; -} - -CBaseContainer::~CBaseContainer() { - for (auto child : m_children) { - delete child; - } -} - -void CBaseContainer::Hide() { - CBaseWidget::Hide(); - if (GetHoveredChild()) GetHoveredChild()->OnMouseLeave(); - if (GetFocusedChild()) GetFocusedChild()->OnFocusLose(); - if (GetPressedChild()) GetPressedChild()->OnMouseRelease(); -} - -void CBaseContainer::HoverOn(IWidget* child) { - if (GetHoveredChild()) GetHoveredChild()->OnMouseLeave(); - if (child) child->OnMouseEnter(); - m_pHoveredChild = child; -} - -void CBaseContainer::MoveChildren() { - return; -} - -void CBaseContainer::OnFocusLose() { - FocusOn(0); - CBaseWidget::OnFocusLose(); -} - -void CBaseContainer::OnKeyPress(ButtonCode_t key, bool repeat) { - if (GetFocusedChild()) GetFocusedChild()->OnKeyPress(key, repeat); -} - -void CBaseContainer::OnKeyRelease(ButtonCode_t key) { - if (GetFocusedChild()) GetFocusedChild()->OnKeyRelease(key); -} - -void CBaseContainer::OnMouseLeave() { - HoverOn(0); - CBaseWidget::OnMouseLeave(); -} - -void CBaseContainer::OnMousePress() { - CBaseWidget::OnMousePress(); - auto abs = AbsolutePosition(); - PressOn(ChildByPoint(g_pGUI->m_iMouseX - abs.first, g_pGUI->m_iMouseY - abs.second)); -} - -void CBaseContainer::OnMouseRelease() { - CBaseWidget::OnMouseRelease(); - if (GetPressedChild()) GetPressedChild()->OnMouseRelease(); -} - -void CBaseContainer::PressOn(IWidget* child) { - m_pPressedChild = child; - if (child) { - child->OnMousePress(); - if (child->DoesStealFocus()) - FocusOn(child); - } else FocusOn(0); -} - -void CBaseContainer::SortByZIndex() { - std::sort(m_children.begin(), m_children.end(), [](IWidget* a, IWidget* b) -> bool { - return a->GetZIndex() < b->GetZIndex(); - }); -} - -void CBaseContainer::UpdateHovers() { - auto abs = AbsolutePosition(); - auto hovered = ChildByPoint(g_pGUI->m_iMouseX - abs.first, g_pGUI->m_iMouseY - abs.second); - if (hovered != GetHoveredChild()) { - HoverOn(hovered); - } -} - -void CBaseContainer::Update() { - SortByZIndex(); - MoveChildren(); - UpdateHovers(); - for (auto child : m_children) { - if (AlwaysVisible() || g_pGUI->Visible() || child->AlwaysVisible()) - child->Update(); - } - CBaseWidget::Update(); -} - - - - - - - diff --git a/src/gui/CBaseContainer.h b/src/gui/CBaseContainer.h deleted file mode 100644 index c2150bb7..00000000 --- a/src/gui/CBaseContainer.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * CBaseContainer.h - * - * Created on: Jan 30, 2017 - * Author: nullifiedcat - */ - -#ifndef CBASECONTAINER_H_ -#define CBASECONTAINER_H_ - -#include "CBaseWidget.h" - -class CBaseContainer : public CBaseWidget, public virtual IWidget { -public: - CBaseContainer(std::string name = "unnamed", IWidget* parent = nullptr); - virtual ~CBaseContainer(); - - void AddChild(IWidget* child); - int ChildCount(); - virtual IWidget* ChildByIndex(int idx); - virtual IWidget* ChildByName(std::string name); - virtual IWidget* ChildByPoint(int x, int y); - - virtual bool ConsumesKey(ButtonCode_t key); - virtual void Draw(int x, int y); - virtual void DrawBounds(int x, int y); - virtual void Hide(); - virtual void OnFocusLose(); - virtual void OnKeyPress(ButtonCode_t key, bool repeat); - virtual void OnKeyRelease(ButtonCode_t key); - virtual void OnMouseLeave(); - virtual void OnMousePress(); - virtual void OnMouseRelease(); - virtual void Update(); - virtual void HandleCustomEvent(KeyValues* event); - - virtual void SortByZIndex(); - void UpdateHovers(); - - virtual void MoveChildren(); - - IWidget* GetHoveredChild(); - IWidget* GetFocusedChild(); - IWidget* GetPressedChild(); - void HoverOn(IWidget* child); - void FocusOn(IWidget* child); - void PressOn(IWidget* child); - - IWidget* m_pHoveredChild; - IWidget* m_pFocusedChild; - IWidget* m_pPressedChild; - - std::vector m_children; -}; - -#endif /* CBASECONTAINER_H_ */ diff --git a/src/gui/CBaseWidget.cpp b/src/gui/CBaseWidget.cpp deleted file mode 100644 index 652052ba..00000000 --- a/src/gui/CBaseWidget.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * CBaseWidget.cpp - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#include "CBaseWidget.h" -#include "../common.h" - -void CBaseWidget::DrawBounds(int x, int y) { - if (m_KeyValues->IsEmpty("bounds_color")) { - m_KeyValues->SetInt("bounds_color", colors::Create(rand() % 255, rand() % 255, rand() % 255, 255)); - } - auto size = GetSize(); - draw::DrawRect(x, y, size.first, size.second, colors::Transparent(m_KeyValues->GetInt("bounds_color"), 0.25f)); - draw::OutlineRect(x, y, size.first, size.second, m_KeyValues->GetInt("bounds_color")); -} - -bool CBaseWidget::IsHovered() { - return g_pGUI->Visible() && m_KeyValues->GetBool("hover"); -} - -bool CBaseWidget::IsFocused() { - return g_pGUI->Visible() && m_KeyValues->GetBool("focus"); -} - -bool CBaseWidget::IsPressed() { - return g_pGUI->Visible() && m_KeyValues->GetBool("press"); -} - -CBaseWidget::CBaseWidget(std::string name, IWidget* parent) : m_KeyValues(new KeyValues(std::string(name + "_kv").c_str())) { - m_pParent = parent; - Props()->SetString("name", name.c_str()); - SetPositionMode(INLINE); - Show(); - SetMaxSize(-1, -1); -} - -void CBaseWidget::Update() { - if (IsHovered() && IsVisible() && Props()->FindKey("tooltip")) { - g_pGUI->ShowTooltip(Props()->GetString("tooltip")); - } -} - -std::pair CBaseWidget::AbsolutePosition() { - auto result = GetOffset(); - auto parent = GetParent(); - while (parent) { - auto poffset = parent->GetOffset(); - result.first += poffset.first; - result.second += poffset.second; - parent = parent->GetParent(); - } - return result; -} diff --git a/src/gui/CBaseWidget.h b/src/gui/CBaseWidget.h deleted file mode 100644 index 2a9b256f..00000000 --- a/src/gui/CBaseWidget.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * CBaseWidget.h - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#ifndef CBASEWIDGET_H_ -#define CBASEWIDGET_H_ - -#include "IWidget.h" -#include "../beforecheaders.h" -#include -#include -#include -#include -#include "../aftercheaders.h" - -#include "../logging.h" - -#include - -class CBaseWidget : public virtual IWidget { -public: - inline ~CBaseWidget() {} - CBaseWidget(std::string name = "unnamed", IWidget* parent = nullptr); - - virtual void Update(); - inline virtual void Draw(int x, int y) {}; - virtual void DrawBounds(int x, int y); - - inline virtual KeyValues* Props() { - return m_KeyValues; - } - - inline virtual void OnMouseEnter() { m_KeyValues->SetBool("hover", true); } - inline virtual void OnMouseLeave() { m_KeyValues->SetBool("hover", false); } - inline virtual void OnMousePress() { m_KeyValues->SetBool("press", true); } - inline virtual void OnMouseRelease() { m_KeyValues->SetBool("press", false); } - inline virtual void OnKeyPress(ButtonCode_t key, bool repeat) {}; - inline virtual void OnKeyRelease(ButtonCode_t key) {}; - inline virtual void OnFocusGain() { m_KeyValues->SetBool("focus", true); } - inline virtual void OnFocusLose() { m_KeyValues->SetBool("focus", false); } - - inline virtual void HandleCustomEvent(KeyValues* event) {}; - - inline virtual bool ConsumesKey(ButtonCode_t key) { return false; } - - inline virtual bool AlwaysVisible() { return m_KeyValues->GetBool("always_visible"); } - - inline virtual void Show() { m_KeyValues->SetBool("visible", true); } - inline virtual void Hide() { m_KeyValues->SetBool("visible", false); } - inline virtual bool IsVisible() { - if (GetParent()) return GetParent()->IsVisible() && m_KeyValues->GetBool("visible"); - return m_KeyValues->GetBool("visible"); - } - - virtual bool IsHovered(); - virtual bool IsFocused(); - virtual bool IsPressed(); - - inline virtual bool DoesStealFocus() { return true; } - - inline virtual void SetOffset(int x, int y) { - if (x >= 0) m_KeyValues->SetInt("offset_x", x); - if (y >= 0) m_KeyValues->SetInt("offset_y", y); - } - inline virtual void SetMaxSize(int x, int y) { - if (x >= 0) m_KeyValues->SetInt("max_x", x); - if (y >= 0) m_KeyValues->SetInt("max_y", y); - } - inline virtual std::pair GetOffset() { - return std::make_pair(m_KeyValues->GetInt("offset_x"), m_KeyValues->GetInt("offset_y")); - } - inline virtual std::pair GetSize() { - return std::make_pair(m_KeyValues->GetInt("size_x"), m_KeyValues->GetInt("size_y")); - } - inline virtual std::pair GetMaxSize() { - return std::make_pair(m_KeyValues->GetInt("max_x"), m_KeyValues->GetInt("max_y")); - } - inline virtual int GetZIndex() { return m_KeyValues->GetInt("zindex"); } - inline virtual void SetZIndex(int idx) { m_KeyValues->SetInt("zindex", idx); } - - inline virtual std::string GetTooltip() { return std::string(m_KeyValues->GetString("tooltip")); } - - inline virtual PositionMode GetPositionMode() { return (PositionMode)m_KeyValues->GetInt("positionmode"); } - inline virtual void SetPositionMode(PositionMode mode) { m_KeyValues->SetInt("positionmode", mode); }; - - inline virtual IWidget* GetParent() { return m_pParent; } - inline virtual void SetParent(IWidget* parent) { m_pParent = parent; } - inline virtual std::string GetName() { return std::string(m_KeyValues->GetString("name")); } - - std::pair AbsolutePosition(); - inline void SetSize(int x, int y) { - if (x >= 0) m_KeyValues->SetInt("size_x", x); - if (y >= 0) m_KeyValues->SetInt("size_y", y); - } - - KeyValues::AutoDelete m_KeyValues; - IWidget* m_pParent; - -}; - - -#endif /* CBASEWIDGET_H_ */ diff --git a/src/gui/CBaseWindow.cpp b/src/gui/CBaseWindow.cpp deleted file mode 100644 index 428bcfae..00000000 --- a/src/gui/CBaseWindow.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * CBaseWindow.cpp - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#include "CBaseWindow.h" - -#include "../common.h" -#include "GUI.h" - -void CBaseWindow::MoveChildren() { - int mx = 0, my = 2; - for (auto c : m_children) { - if (!c->IsVisible()) continue; - auto off = c->GetOffset(); - auto size = c->GetSize(); - if (c->GetPositionMode() != ABSOLUTE && c->GetPositionMode() != FLOATING) - c->SetOffset(2, my); - else { - size.first += off.first; - size.second += off.second; - } - if (c->GetPositionMode() != FLOATING && c->GetPositionMode() != ABSOLUTE) - if (size.first > mx) mx = size.first; - if (c->GetPositionMode() != FLOATING) - my += (size.second + 2); - } - if (GetParent()) { - SetSize(mx + 4, my + 2); - } -} - -void CBaseWindow::OnFocusGain() { - SetZIndex(GetZIndex() + 1); - CBaseContainer::OnFocusGain(); -} - -void CBaseWindow::OnFocusLose() { - SetZIndex(GetZIndex() - 1); - CBaseContainer::OnFocusLose(); -} - -void CBaseWindow::Draw(int x, int y) { - auto abs = AbsolutePosition(); - auto size = GetSize(); - draw::DrawRect(abs.first, abs.second, size.first, size.second, colors::Transparent(colors::black, 0.9)); - draw::OutlineRect(abs.first, abs.second, size.first, size.second, GUIColor()); - CBaseContainer::Draw(x, y); -} diff --git a/src/gui/CBaseWindow.h b/src/gui/CBaseWindow.h deleted file mode 100644 index 0740fa41..00000000 --- a/src/gui/CBaseWindow.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * CBaseWindow.h - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#ifndef CBASEWINDOW_H_ -#define CBASEWINDOW_H_ - -#include "CBaseContainer.h" - -class CBaseWindow : public CBaseContainer { -public: - inline CBaseWindow(std::string name = "unnamed", IWidget* parent = nullptr) : CBaseContainer(name, parent) {} - inline virtual ~CBaseWindow() {}; - - virtual void OnFocusGain() override; - virtual void OnFocusLose() override; - virtual void Draw(int x, int y) override; - virtual void MoveChildren() override; -}; - - - -#endif /* CBASEWINDOW_H_ */ diff --git a/src/gui/CCTitleBar.cpp b/src/gui/CCTitleBar.cpp deleted file mode 100644 index 02410ae2..00000000 --- a/src/gui/CCTitleBar.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - * TitleBar.cpp - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#include "CCTitleBar.h" - -#include "GUI.h" - -#include "../common.h" -#include "../sdk.h" - -CTitleBar::CTitleBar(IWidget* parent, std::string title) : CBaseWidget("titlebar", parent) { - m_strTitle = title; - m_iDraggingStage = 0; - m_nLastX = 0; - m_nLastY = 0; - SetPositionMode(ABSOLUTE); -} - -void CTitleBar::Draw(int x, int y) { - auto size = GetSize(); - draw::DrawRect(x, y, size.first, size.second, GUIColor()); - int l, h; - draw::GetStringLength(fonts::MENU, (char*)m_strTitle.c_str(), l, h); - draw::String(fonts::MENU, x + (size.first - l) / 2, y + TITLEBAR_PADDING_H, colors::white, 1, m_strTitle.c_str()); -} - -void CTitleBar::Update() { - auto psize = GetParent()->GetSize(); - int l, h; - draw::GetStringLength(fonts::MENU, (char*)m_strTitle.c_str(), l, h); - SetSize(psize.first, 2 * TITLEBAR_PADDING_H + h); - if (!IsPressed()) { - m_iDraggingStage = 0; - return; - } - if (m_iDraggingStage == 0) { - m_iDraggingStage = 1; - } else { - int dx = g_pGUI->m_iMouseX - m_nLastX; - int dy = g_pGUI->m_iMouseY - m_nLastY; - auto offset = GetParent()->GetOffset(); - GetParent()->SetOffset(offset.first + dx, offset.second + dy); - } - m_nLastX = g_pGUI->m_iMouseX; - m_nLastY = g_pGUI->m_iMouseY; -} - - diff --git a/src/gui/CCTitleBar.h b/src/gui/CCTitleBar.h deleted file mode 100644 index 54f21248..00000000 --- a/src/gui/CCTitleBar.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * TitleBar.h - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#ifndef CCTITLEBAR_H_ -#define CCTITLEBAR_H_ - -#include "CBaseWidget.h" - -#define TITLEBAR_PADDING_W 2 -#define TITLEBAR_PADDING_H 1 - -class CTitleBar : public CBaseWidget { -public: - CTitleBar(IWidget* parent, std::string title); - - virtual void Draw(int x, int y); - virtual void Update(); - - std::string m_strTitle; - int m_iDraggingStage; - int m_nLastX; - int m_nLastY; -}; - -#endif /* CCTITLEBAR_H_ */ diff --git a/src/gui/CCVarContainer.cpp b/src/gui/CCVarContainer.cpp deleted file mode 100644 index 2d50a51d..00000000 --- a/src/gui/CCVarContainer.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* - * CCVarContainer.cpp - * - * Created on: Feb 1, 2017 - * Author: nullifiedcat - */ - - -#include "CCVarContainer.h" - -#include "CSlider.h" -#include "CTextInput.h" -#include "CTextLabel.h" -#include "CKeyInput.h" -#include "CCheckbox.h" -#include "CDropdown.h" - -#include "../common.h" -#include "../sdk.h" - -CCVarContainer::CCVarContainer(IWidget* parent, CatVar* var) : CBaseContainer("cvc_" + var->name, parent) { - m_pVar = var; - m_pInput = 0; - m_pLabel = new CTextLabel(GetName() + "_desc", this, var->desc_short); - m_pControl = 0; - if (var->desc_short.length()) { - Props()->SetString("tooltip", var->desc_long.c_str()); - } - bool needsinput = false; - switch (var->type) { - case CatVar_t::CV_SWITCH: {// Label, Checkbox - CCheckbox* cb = new CCheckbox(GetName() + "_control", this, var->GetBool()); - cb->SetCallback([this](CCheckbox*, bool value) { - m_pVar->SetValue(value); - }); - m_pControl = cb; - } break; - case CatVar_t::CV_ENUM: { // Most difficult thing, dropdown menu - if (!var->enum_type) { - logging::Info("VAR %s HAS NO ENUM TYPE!! ERROR!!", var->name.c_str()); - break; - } - CDropdown* dd = new CDropdown(GetName() + "_control", this); - for (int i = var->enum_type->Minimum(); i <= var->enum_type->Maximum(); i++) { - dd->AddValue(var->enum_type->Name(i)); - } - dd->SetCallback([this](CDropdown*, int value) { - m_pVar->SetValue(value); - }); - dd->Props()->SetInt("offset", var->enum_type->Minimum()); - m_pControl = dd; - } break; - case CatVar_t::CV_FLOAT: { - if (var->restricted) { - CSlider* sl = new CSlider(GetName() + "_control", this); - sl->Setup(var->min, var->max); - sl->SetValue(var->GetFloat()); - m_pControl = sl; - sl->SetCallback([this](CSlider*, float oldv, float newv) { - m_pVar->SetValue(newv); - }); - } - needsinput = true; - } break; - case CatVar_t::CV_INT: { - if (var->restricted) { - CSlider* sl = new CSlider(GetName() + "_control", this); - sl->Setup(var->min, var->max); - sl->SetStep(1.0f); - sl->SetValue(var->GetInt()); - sl->SetCallback([this](CSlider*, float oldv, float newv) { - m_pVar->SetValue(newv); - }); - m_pControl = sl; - } - needsinput = true; - } break; - case CatVar_t::CV_KEY: { - CKeyInput* ki = new CKeyInput(GetName() + "_control", this); - ki->SetCallback([this](CKeyInput*, ButtonCode_t key) { - m_pVar->SetValue(key); - }); - ki->SetSize(60, 18); - m_pControl = ki; - } break; - case CatVar_t::CV_STRING: { - needsinput = true; - } break; - } - - if (needsinput) { - m_pInput = new CTextInput(GetName() + "_input", this); - m_pInput->SetValue(std::string(var->GetString())); - m_pInput->SetCallback([this](CTextInput*, std::string old, std::string newv) { - if (m_pVar->type == CV_STRING) { - m_pVar->SetValue(newv); - } else { - try { - char* s = strfmt("%.2f", std::stof(newv)); - std::string str(s); - delete [] s; - m_pVar->SetValue(str); - } catch (...) { - - } - } - }); - } - - if (m_pLabel) { - AddChild(m_pLabel); - } - if (m_pControl) { - AddChild(m_pControl); - } - if (m_pInput) { - m_pInput->SetMaxWidth(10); - AddChild(m_pInput); - } -} - -void CCVarContainer::MoveChildren() { - int sy = 0; - for (auto child : m_children) { - auto s = child->GetSize(); - if (sy < s.second) sy = s.second; - } - auto max = GetMaxSize(); - SetSize(max.first, sy + 4); - auto labels = m_pLabel->GetSize(); - m_pLabel->SetOffset(2, (sy - labels.second) / 2 + 2); - int x = max.first - 2; - if (m_pInput) { - auto inputs = m_pInput->GetSize(); - x -= inputs.first + 2; - m_pInput->SetOffset(x + 2, (sy - inputs.second) / 2 + 2); - } - if (m_pControl) { - auto controls = m_pControl->GetSize(); - m_pControl->SetMaxSize(x - 4 - labels.first, sy - 4); - x -= controls.first + 2; - m_pControl->SetOffset(x + 2, (sy - controls.second) / 2 + 2); - } -} - -void CCVarContainer::Update() { - static int updticks = 0; - updticks++; - if (m_pVar && !(updticks % 30)) { - updticks = 1; - if (m_pInput) { - if (!m_pInput->IsFocused()) m_pInput->SetValue(m_pVar->GetString()); - } - if (m_pControl && !m_pControl->IsFocused()) { - switch (m_pVar->type) { - case CatVar_t::CV_ENUM: { - dynamic_cast(m_pControl)->SetValue(m_pVar->GetInt()); - } break; - case CatVar_t::CV_FLOAT: - case CatVar_t::CV_INT: { - dynamic_cast(m_pControl)->SetValue(m_pVar->GetFloat()); - } break; - case CatVar_t::CV_KEY: { - dynamic_cast(m_pControl)->SetValue(m_pVar->GetInt()); - } break; - case CatVar_t::CV_SWITCH: { - dynamic_cast(m_pControl)->SetValue(m_pVar->GetBool()); - } break; - } - } - } - CBaseContainer::Update(); -} diff --git a/src/gui/CCVarContainer.h b/src/gui/CCVarContainer.h deleted file mode 100644 index 61e47f89..00000000 --- a/src/gui/CCVarContainer.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * CCVarContainer.h - * - * Created on: Jan 28, 2017 - * Author: nullifiedcat - */ - -#ifndef CCVARCONTAINER_H_ -#define CCVARCONTAINER_H_ - -#include "CBaseContainer.h" - -class CatVar; -class CTextInput; -class CTextLabel; - -class CCVarContainer : public CBaseContainer { -public: - CCVarContainer(IWidget* parent, CatVar* var); - - virtual void MoveChildren() override; - virtual void Update() override; - - CTextInput* m_pInput; - IWidget* m_pControl; - CTextLabel* m_pLabel; - - CatVar* m_pVar; -}; - -#endif /* CCVARCONTAINER_H_ */ diff --git a/src/gui/CCheckbox.cpp b/src/gui/CCheckbox.cpp deleted file mode 100644 index b169112f..00000000 --- a/src/gui/CCheckbox.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - * CCheckbox.cpp - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#include "CCheckbox.h" - -#include "../common.h" -#include "../sdk.h" - -CCheckbox::CCheckbox(std::string name, IWidget* parent, bool checked) : CBaseWidget(name, parent) { - SetWidth(16); - SetValue(checked); -} - -void CCheckbox::SetWidth(int width) { - Props()->SetInt("width", width); - SetSize(width, width); -} - -void CCheckbox::Draw(int x, int y) { - auto size = GetSize(); - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - if (Value()) { - draw::DrawRect(x + 3, y + 3, size.first - 6, size.second - 6, GUIColor()); - } -} - -void CCheckbox::OnMousePress() { - SetValue(!Value()); - if (m_pCallback) { - m_pCallback(this, Value()); - } -} - -void CCheckbox::SetCallback(CheckboxCallbackFn_t callback) { - m_pCallback = callback; -} diff --git a/src/gui/CCheckbox.h b/src/gui/CCheckbox.h deleted file mode 100644 index 1aee6a96..00000000 --- a/src/gui/CCheckbox.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * CCheckbox.h - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#ifndef CCHECKBOX_H_ -#define CCHECKBOX_H_ - -#include "CBaseWidget.h" - -class CCheckbox; - -typedef std::function CheckboxCallbackFn_t; - -class CCheckbox : public CBaseWidget { -public: - CCheckbox(std::string name = "unnamed", IWidget* parent = nullptr, bool checked = false); - - void SetWidth(int width); - inline bool Value() { return Props()->GetBool("checked"); } - inline void SetValue(bool value) { Props()->SetBool("checked", value); } - void SetCallback(CheckboxCallbackFn_t callback); - - virtual void OnMousePress(); - virtual void Draw(int x, int y); - - CheckboxCallbackFn_t m_pCallback; - -}; - - - -#endif /* CCHECKBOX_H_ */ diff --git a/src/gui/CDropdown.cpp b/src/gui/CDropdown.cpp deleted file mode 100644 index ca82193b..00000000 --- a/src/gui/CDropdown.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* - * CDropdown.cpp - * - * Created on: Jan 31, 2017 - * Author: nullifiedcat - */ - -#include "CDropdown.h" -#include "CDropdownList.h" -#include "RootWindow.h" - -#include "../common.h" -#include "../sdk.h" - -CDropdown::CDropdown(std::string name, IWidget* parent) : CBaseButton(name, parent) { - list = new CDropdownList(name + "_list", this); - g_pGUI->GetRootWindow()->AddChild(list); - SetSize(80, 18); - list->SetSize(80, 0); - CBaseButton::SetCallback([this](CBaseButton*) -> void { - ShowList(); - }); -} - -CDropdown::~CDropdown() { - delete list; -} - -void CDropdown::SetCallback(DropdownCallbackFn_t callback) { - m_pDropdownCallback = callback; -} - -void CDropdown::AddValue(std::string string) { - list->AddEntry(string); - m_values.push_back(string); -} - -std::string CDropdown::ValueName(int idx) { - if (idx < 0 || idx >= m_values.size()) return "unknown"; - return m_values.at(idx); -} - -void CDropdown::Draw(int x, int y) { - auto size = GetSize(); - auto ssize = draw::GetStringLength(fonts::MENU, ValueName(Value() - Props()->GetInt("offset"))); - draw::DrawRect(x, y, size.first, size.second, colors::Transparent(colors::black)); - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - draw::String(fonts::MENU, x + (size.first - ssize.first) / 2, y + (size.second - ssize.second) / 2, GUIColor(), 1, ValueName(Value() - Props()->GetInt("offset"))); - auto asize = draw::GetStringLength(fonts::MENU, ">"); - draw::String(fonts::MENU, x + size.first - asize.first - 2, y + (size.second - asize.second) / 2, GUIColor(), 1, ">"); -} - -void CDropdown::OnFocusLose() { - list->Hide(); -} - -void CDropdown::SetValueInternal(int value) { - Props()->SetInt("value", value + Props()->GetInt("offset")); - if (m_pDropdownCallback) - m_pDropdownCallback(this, value + Props()->GetInt("offset")); -} - -void CDropdown::SetValue(int value) { - Props()->SetInt("value", value); -} - -void CDropdown::ShowList() { - auto pos = AbsolutePosition(); - auto size = GetSize(); - list->SetOffset(pos.first + size.first + 3, pos.second); - list->Show(); -} - -int CDropdown::Value() { - return Props()->GetInt("value"); -} - -int CDropdown::ValueCount() { - return m_values.size(); -} diff --git a/src/gui/CDropdown.h b/src/gui/CDropdown.h deleted file mode 100644 index 67137848..00000000 --- a/src/gui/CDropdown.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * CDropdown.h - * - * Created on: Jan 31, 2017 - * Author: nullifiedcat - */ - -#ifndef CDROPDOWN_H_ -#define CDROPDOWN_H_ - -#include "CBaseButton.h" -#include "CDropdownList.h" - -class CDropdown; - -typedef std::function DropdownCallbackFn_t; - -class CDropdown : public CBaseButton { -public: - CDropdown(std::string name = "unnamed", IWidget* parent = nullptr); - ~CDropdown(); - - void AddValue(std::string); - int ValueCount(); - std::string ValueName(int idx); - void SetValue(int value); - void SetValueInternal(int value); - int Value(); - - void ShowList(); - void SetCallback(DropdownCallbackFn_t callback); - - virtual void Draw(int x, int y); - virtual void OnFocusLose(); - - DropdownCallbackFn_t m_pDropdownCallback; - CDropdownList* list; - std::vector m_values; -}; - - -#endif /* CDROPDOWN_H_ */ diff --git a/src/gui/CDropdownEntry.cpp b/src/gui/CDropdownEntry.cpp deleted file mode 100644 index ef390d73..00000000 --- a/src/gui/CDropdownEntry.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * CDropdownEntry.cpp - * - * Created on: Jan 31, 2017 - * Author: nullifiedcat - */ - -#include "CDropdownEntry.h" - -#include "../common.h" -#include "../sdk.h" - -CDropdownEntry::CDropdownEntry(std::string name, CDropdownList* parent, std::string text, int value) : CBaseButton(name, parent, text) { - Props()->SetInt("value", value); - SetCallback([this](CBaseButton*) -> void { - CDropdownList* parent = dynamic_cast(GetParent()); - if (!parent) return; - parent->SetValue(Props()->GetInt("value")); - }); -} - -void CDropdownEntry::Draw(int x, int y) { - auto ssize = draw::GetStringLength(fonts::MENU, GetText()); - auto size = GetSize(); - draw::String(fonts::MENU, x + (size.first - ssize.first) / 2, y + (size.second - ssize.second) / 2, GUIColor(), 1, GetText()); -} - -CDropdownEntry::~CDropdownEntry() { - -} diff --git a/src/gui/CDropdownEntry.h b/src/gui/CDropdownEntry.h deleted file mode 100644 index 44c6c07e..00000000 --- a/src/gui/CDropdownEntry.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * CDropdownEntry.h - * - * Created on: Jan 31, 2017 - * Author: nullifiedcat - */ - -#ifndef CDROPDOWNENTRY_H_ -#define CDROPDOWNENTRY_H_ - -#include "CBaseButton.h" -#include "CDropdownList.h" - -class CDropdownEntry : public CBaseButton { -public: - CDropdownEntry(std::string name = "unnamed", CDropdownList* parent = nullptr, std::string text = "unset", int value = 0); - ~CDropdownEntry(); - - virtual void Draw(int x, int y); -}; - - - -#endif /* CDROPDOWNENTRY_H_ */ diff --git a/src/gui/CDropdownList.cpp b/src/gui/CDropdownList.cpp deleted file mode 100644 index 50bfb28d..00000000 --- a/src/gui/CDropdownList.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * CDropdownList.cpp - * - * Created on: Jan 31, 2017 - * Author: nullifiedcat - */ - -#include "CDropdownList.h" -#include "CDropdownEntry.h" -#include "CDropdown.h" - -#include "../common.h" -#include "../sdk.h" - -CDropdownList::CDropdownList(std::string name, CDropdown* menu, int offset) : CBaseContainer(name, nullptr) { - m_pMenu = menu; - Hide(); - SetZIndex(5); -} - -CDropdownList::~CDropdownList() { - for (auto entry : m_entries) { - delete entry; - } -} - -void CDropdownList::AddEntry(std::string name) { - CDropdownEntry* entry = new CDropdownEntry("entry", this, name, m_entries.size()); - auto size = GetSize(); - entry->SetSize(size.first, 18); - AddChild(entry); - m_entries.push_back(entry); - SetSize(size.first, m_entries.size() * 18); -} - -void CDropdownList::SetValue(int value) { - m_pMenu->SetValueInternal(value); - Hide(); -} - -void CDropdownList::Draw(int x, int y) { - auto size = GetSize(); - draw::DrawRect(x, y, size.first, size.second, colors::Transparent(colors::black, 0.85)); - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - CBaseContainer::Draw(x, y); -} - -void CDropdownList::MoveChildren() { - for (int i = 0; i < ChildCount(); i++) { - auto child = ChildByIndex(i); - child->SetOffset(0, i * 18); - } -} diff --git a/src/gui/CDropdownList.h b/src/gui/CDropdownList.h deleted file mode 100644 index c5bbc9a4..00000000 --- a/src/gui/CDropdownList.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * CDropdownList.h - * - * Created on: Jan 31, 2017 - * Author: nullifiedcat - */ - -#ifndef CDROPDOWNLIST_H_ -#define CDROPDOWNLIST_H_ - -#include "CBaseContainer.h" - -class CDropdown; -class CDropdownEntry; - -class CDropdownList : public CBaseContainer { -public: - CDropdownList(std::string name = "unnamed", CDropdown* menu = nullptr, int offset = 0); - ~CDropdownList(); - - virtual void Draw(int x, int y); - virtual void MoveChildren(); - inline virtual void SortByZIndex() override {}; - inline virtual bool DoesStealFocus() { return false; } - - void AddEntry(std::string name); - void SetValue(int value); - - CDropdown* m_pMenu; - std::vector m_entries; -}; - -#endif /* CDROPDOWNLIST_H_ */ diff --git a/src/gui/CKeyInput.cpp b/src/gui/CKeyInput.cpp deleted file mode 100644 index a3a0f391..00000000 --- a/src/gui/CKeyInput.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * CKeyInput.cpp - * - * Created on: Feb 1, 2017 - * Author: nullifiedcat - */ - -#include "CKeyInput.h" - -#include "../common.h" -#include "../sdk.h" - -CKeyInput::CKeyInput(std::string name, IWidget* parent) : CBaseWidget(name, parent) { - Props()->SetInt("value", 0); - Props()->SetBool("capturing", false); -} - -ButtonCode_t CKeyInput::Value() { - return (ButtonCode_t)Props()->GetInt("value"); -} - -void CKeyInput::SetValue(int value) { - Props()->SetInt("value", value); -} - -void CKeyInput::Draw(int x, int y) { - std::string key = ""; - int color = colors::white; - if (Props()->GetBool("capturing")) { - key = "< PRESS >"; - color = GUIColor(); - } else { - if (!Value()) { - if (!IsFocused()) { - key = "< CLICK >"; - } - } else { - key = g_IInputSystem->ButtonCodeToString(Value()); - } - } - auto size = GetSize(); - auto ss = draw::GetStringLength(fonts::MENU, key); - draw::String(fonts::MENU, x + (size.first - ss.first) / 2, y + (size.second - ss.second) / 2, color, 1, key); -} - -void CKeyInput::SetCallback(KeyInputCallbackFn_t callback) { - m_pCallback = callback; -} - -void CKeyInput::OnMousePress() { - if (!Props()->GetBool("capturing")) - Props()->SetBool("capturing", true); -} - -void CKeyInput::OnFocusLose() { - Props()->SetBool("capturing", false); -} - -bool CKeyInput::ConsumesKey(ButtonCode_t key) { - return key != MOUSE_LEFT && Props()->GetBool("capturing"); -} - -void CKeyInput::OnKeyPress(ButtonCode_t key, bool repeat) { - if (Props()->GetBool("capturing")) { - if (key == KEY_ESCAPE) key = (ButtonCode_t)0; - SetValue(key); - if (m_pCallback) m_pCallback(this, key); - Props()->SetBool("capturing", false); - } -} diff --git a/src/gui/CKeyInput.h b/src/gui/CKeyInput.h deleted file mode 100644 index 87e73fa4..00000000 --- a/src/gui/CKeyInput.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * CKey.h - * - * Created on: Feb 1, 2017 - * Author: nullifiedcat - */ - -#ifndef CKEYINPUT_H_ -#define CKEYINPUT_H_ - -#include "CBaseWidget.h" - -class CKeyInput; - -typedef std::function KeyInputCallbackFn_t; - -class CKeyInput : public CBaseWidget { -public: - CKeyInput(std::string name = "unnamed", IWidget* parent = nullptr); - - ButtonCode_t Value(); - void SetValue(int value); - void SetCallback(KeyInputCallbackFn_t callback); - - KeyInputCallbackFn_t m_pCallback; - - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; - virtual void Draw(int x, int y) override; - virtual void OnMousePress() override; - virtual void OnFocusLose() override; - virtual bool ConsumesKey(ButtonCode_t key) override; -}; - -#endif /* CKEYINPUT_H_ */ diff --git a/src/gui/CMenuContainer.cpp b/src/gui/CMenuContainer.cpp deleted file mode 100644 index 562ede3e..00000000 --- a/src/gui/CMenuContainer.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * CMenuContainer.cpp - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#include "CMenuContainer.h" -#include "CMenuWindow.h" -#include "CBaseButton.h" - -#include "../common.h" - -CMenuContainer::CMenuContainer(std::string name, CMenuWindow* parent) : CBaseContainer(name, parent) {} - -void CMenuContainer::MoveChildren() { - int column_size = 350; - int x = 3, y = 2; - int columns = 0; - int my = GetMaxSize().second; - for (int i = 0; i < ChildCount(); i++) { - auto c = ChildByIndex(i); - if (y + c->GetSize().second >= my) { - y = 2; - x += column_size + 3; - columns++; - } - c->SetOffset(x, y); - if (!dynamic_cast(c)) - c->SetSize(column_size, -1); - c->SetMaxSize(column_size, -1); - y += c->GetSize().second + 2; - } - Props()->SetInt("columns", columns); -} - -void CMenuContainer::Draw(int x, int y) { - CBaseContainer::Draw(x, y); - for (int i = 0; i < Props()->GetInt("columns"); i++) { - draw::DrawLine(x + (350 + 3) * (i + 1), y, 0, GetMaxSize().second, GUIColor()); - } -} diff --git a/src/gui/CMenuContainer.h b/src/gui/CMenuContainer.h deleted file mode 100644 index 23cc00ff..00000000 --- a/src/gui/CMenuContainer.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * CMenuContainer.h - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#ifndef CMENUCONTAINER_H_ -#define CMENUCONTAINER_H_ - -#include "CBaseContainer.h" - -class CMenuWindow; - -class CMenuContainer : public CBaseContainer { -public: - CMenuContainer(std::string name, CMenuWindow* parent); - - virtual inline void SortByZIndex() override {}; - virtual void MoveChildren() override; - virtual void Draw(int x, int y) override; -}; - -#endif /* CMENUCONTAINER_H_ */ diff --git a/src/gui/CMenuList.cpp b/src/gui/CMenuList.cpp deleted file mode 100644 index 4721662b..00000000 --- a/src/gui/CMenuList.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * CMenuList.cpp - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#include "CMenuList.h" - -#include "CMenuListEntry.h" -#include "CMenuWindow.h" - -#include "../common.h" -#include "../sdk.h" - -CMenuList::CMenuList(std::string name, CMenuWindow* parent) : CBaseContainer(name, parent) { - -} - -void CMenuList::AddEntry(std::string id, std::string name) { - CMenuListEntry* entry = new CMenuListEntry("entry_" + id, this, id); - entry->SetText(name); - entry->SetCallback([this](CBaseButton* thisptr) { - CMenuWindow* window = dynamic_cast(thisptr->GetParent()->GetParent()); - window->SelectTab(thisptr->Props()->GetString("entry")); - }); - AddChild(entry); -} - -void CMenuList::SelectEntry(std::string id) { - m_pSelected = dynamic_cast(ChildByName("entry_" + id)); -} - -void CMenuList::MoveChildren() { - int cc = ChildCount(); - auto ms = GetMaxSize(); - for (int i = 0; i < cc; i++) { - auto child = ChildByIndex(i); - child->SetMaxSize(ms.first, ms.second / cc); - child->SetOffset(0, (ms.second / cc) * i); - } -} diff --git a/src/gui/CMenuList.h b/src/gui/CMenuList.h deleted file mode 100644 index 1eb69f11..00000000 --- a/src/gui/CMenuList.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * CMenuList.h - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#ifndef CMENULIST_H_ -#define CMENULIST_H_ - -#include "CBaseContainer.h" - -class CMenuWindow; -class CMenuContainer; -class CMenuListEntry; - -class CMenuList : public CBaseContainer { -public: - CMenuList(std::string name, CMenuWindow* parent); - - void SelectEntry(std::string id); - void AddEntry(std::string id, std::string name); - - virtual void MoveChildren() override; - - CMenuListEntry* m_pSelected; -}; - -#endif /* CMENULIST_H_ */ diff --git a/src/gui/CMenuListEntry.cpp b/src/gui/CMenuListEntry.cpp deleted file mode 100644 index cfbca3ba..00000000 --- a/src/gui/CMenuListEntry.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * CMenuListEntry.cpp - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#include "CMenuListEntry.h" -#include "CMenuList.h" - -#include "../common.h" -#include "../sdk.h" - -CMenuListEntry::CMenuListEntry(std::string name, CMenuList* parent, std::string entry) : CBaseButton(name, parent, entry) { - Props()->SetString("entry", entry.c_str()); -} - -void CMenuListEntry::SetMaxSize(int x, int y) { - CBaseWidget::SetMaxSize(x, y); - SetSize(x, y); -} - -bool CMenuListEntry::IsSelected() { - return (dynamic_cast(GetParent())->m_pSelected == this); -} - -void CMenuListEntry::Draw(int x, int y) { - auto texts = draw::GetStringLength(fonts::MENU_BIG, GetText()); - auto size = GetSize(); - if (IsSelected()) { - draw::DrawLine(x, y, size.first, 0, GUIColor()); - draw::DrawLine(x, y + size.second, size.first, 0, GUIColor()); - draw::DrawLine(x, y, 0, size.second, GUIColor()); - } else { - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - } - if (IsHovered()) { - draw::DrawRect(x, y, size.first, size.second, colors::Transparent(GUIColor(), 0.25)); - } - draw::String(fonts::MENU_BIG, x + (size.first - texts.first) / 2, y + (size.second - texts.second) / 2, IsSelected() ? colors::white : GUIColor(), 1, GetText()); -} diff --git a/src/gui/CMenuListEntry.h b/src/gui/CMenuListEntry.h deleted file mode 100644 index 21623fce..00000000 --- a/src/gui/CMenuListEntry.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * CMenuListEntry.h - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#ifndef CMENULISTENTRY_H_ -#define CMENULISTENTRY_H_ - -#include "CBaseButton.h" - -class CMenuList; - -class CMenuListEntry : public CBaseButton { -public: - CMenuListEntry(std::string name, CMenuList* parent, std::string entry); - - bool IsSelected(); - - virtual void SetMaxSize(int x, int y) override; - virtual void Draw(int x, int y) override; -}; - - -#endif /* CMENULISTENTRY_H_ */ diff --git a/src/gui/CMenuWindow.cpp b/src/gui/CMenuWindow.cpp deleted file mode 100644 index cdd55699..00000000 --- a/src/gui/CMenuWindow.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * CMenuWindow.cpp - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#include "CMenuWindow.h" -#include "CMenuList.h" -#include "CTextLabel.h" -#include "CMenuContainer.h" -#include "CCVarContainer.h" -#include "CBaseButton.h" -#include "../common.h" -#include "../sdk.h" -#include "CCTitleBar.h" - -CMenuWindow::CMenuWindow(std::string name, IWidget* parent) : CBaseWindow(name, parent) { - m_pList = new CMenuList("list", this); - AddChild(m_pList); - m_pActiveTab = 0; - AddChild(m_pTitle = new CTitleBar(this, "cathook menu")); -} - -#define ADDCVAR(x) tab->AddChild(new CCVarContainer(tab, (x))) -#define ADDLABEL(x) tab->AddChild(new CTextLabel("label", tab, x, true)) -#define ADDCVARS(x) for (auto var : FindCatVars(x)) ADDCVAR(var) - -std::vector FindCatVars(const std::string name) { - std::vector result = {}; - for (auto var : CatVarList()) { - if (var->name.find(name) == 0) result.push_back(var); - } - return result; -} - -void CMenuWindow::AddElements() { - /*AddTab("aimbot", "Aimbot"); - CMenuContainer* tab = GetTab("aimbot"); - for (auto var : FindCatVars("aimbot_")) ADDCVAR(var); - AddTab("esp", "ESP"); - tab = GetTab("esp"); - for (auto var : FindCatVars("esp_")) ADDCVAR(var); - AddTab("triggerbot", "Triggerbot"); - tab = GetTab("triggerbot"); - for (auto var : FindCatVars("triggerbot_")) ADDCVAR(var); - if (TF) { - ADDLABEL("AutoSticky"); - for (auto var : FindCatVars("sticky_")) ADDCVAR(var); - ADDLABEL("AutoReflect"); - for (auto var : FindCatVars("reflect_")) ADDCVAR(var); - } - AddTab("misc", "Misc"); - tab = GetTab("misc"); - ADDCVARS("thirdperson"); - ADDCVARS("log"); - ADDCVARS("no_"); - ADDCVARS("fov"); - ADDCVARS("clean_"); - ADDCVARS("tauntslide"); - ADDCVARS("airstuck"); - ADDCVARS("fast_"); - ADDCVARS("ignore_"); - ADDCVARS("rollspeedhack"); - ADDCVARS("minigun"); - ADDCVARS("disconnect"); - - if (TF) ADDCVAR(&hacks::tf::autoheal::enabled); - if (TF) ADDCVAR(&hacks::tf2::antidisguise::enabled); - if (TF2C) { - - } - - ADDCVAR(&cathook); - - if (TF) { - ADDLABEL("Spy Alert"); - for (auto var : FindCatVars("spyalert_")) ADDCVAR(var); - } - ADDLABEL("Bunnyhop"); - ADDCVARS("bhop"); - AddTab("antiaim", "Anti-Aim"); - tab = GetTab("antiaim"); - for (auto var : FindCatVars("aa_")) ADDCVAR(var); - AddTab("spam", "Spam/Killsay"); - tab = GetTab("spam"); - ADDLABEL("Spam"); - ADDCVARS("spam"); - tab->AddChild(new CBaseButton("spam_reload", tab, "Reload spam", [this](CBaseButton*) { - hacks::shared::spam::Reload(); - })); - ADDLABEL("Killsay"); - ADDCVARS("killsay"); - tab->AddChild(new CBaseButton("killsay_reload", tab, "Reload killsays", [this](CBaseButton*) { - hacks::shared::killsay::Reload(); - })); - AddTab("multibox", "Bots"); - tab = GetTab("multibox"); - for (auto var : FindCatVars("ipc_")) ADDCVAR(var); - for (auto var : FindCatVars("fb_")) ADDCVAR(var); - ADDLABEL("Stats window/bot management coming soon!");*/ -} - -CMenuContainer* CMenuWindow::GetTab(std::string tab) { - return dynamic_cast(ChildByName("tab_" + tab)); -} - -void CMenuWindow::AddTab(std::string tab, std::string name) { - m_pList->AddEntry(tab, name); - CMenuContainer* container = new CMenuContainer("tab_" + tab, this); - if (!m_pActiveTab) m_pActiveTab = container; - AddChild(container); - container->Hide(); -} - -void CMenuWindow::SelectTab(std::string tab) { - if (m_pActiveTab) m_pActiveTab->Hide(); - m_pActiveTab = GetTab(tab); - m_pList->SelectEntry(tab); - if (m_pActiveTab) m_pActiveTab->Show(); -} - -void CMenuWindow::MoveChildren() { - auto ms = GetMaxSize(); - auto th = m_pTitle->GetSize().second; - SetSize(ms.first, ms.second); - m_pList->SetMaxSize(200, ms.second - th); - m_pList->SetSize(200, ms.second - th); - m_pList->SetOffset(0, th); - if (m_pActiveTab) { - m_pActiveTab->SetOffset(200, th); - m_pActiveTab->SetMaxSize(ms.first - 200, ms.second - th); - m_pActiveTab->SetSize(ms.first - 200, ms.second - th); - } -} diff --git a/src/gui/CMenuWindow.h b/src/gui/CMenuWindow.h deleted file mode 100644 index e0ccc9ea..00000000 --- a/src/gui/CMenuWindow.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * CMenuWindow.h - * - * Created on: Feb 3, 2017 - * Author: nullifiedcat - */ - -#ifndef CMENUWINDOW_H_ -#define CMENUWINDOW_H_ - -#include "CBaseWindow.h" - -class CMenuList; -class CMenuContainer; -class CTitleBar; - -class CMenuWindow : public CBaseWindow { -public: - CMenuWindow(std::string name, IWidget* parent); - - void AddElements(); - - void SelectTab(std::string tab); - void AddTab(std::string tab, std::string name); - CMenuContainer* GetTab(std::string tab); - - virtual void MoveChildren() override; - - CMenuList* m_pList; - CTitleBar* m_pTitle; - CMenuContainer* m_pActiveTab; -}; - - -#endif /* CMENUWINDOW_H_ */ diff --git a/src/gui/CSlider.cpp b/src/gui/CSlider.cpp deleted file mode 100644 index 9b37011b..00000000 --- a/src/gui/CSlider.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* - * CSlider.cpp - * - * Created on: Jan 28, 2017 - * Author: nullifiedcat - */ - -#include "CSlider.h" -#include "../common.h" -#include "../sdk.h" - -CSlider::CSlider(std::string name, IWidget* parent) : CBaseWidget(name, parent) { - Setup(0.0f, 1.0f); - SetSize(80, 16); - m_nLastX = 0; - m_nSliderPos = 40; - m_bDragInit = false; - m_pCallback = 0; -} - -void CSlider::Setup(float min, float max) { - Props()->SetFloat("value_min", min); - Props()->SetFloat("value_max", max); - SetValue((min + max) / 2.0f); -} - -void CSlider::SetStep(float step) { - Props()->SetFloat("step", step); -} - -void CSlider::SetCallback(SliderCallbackFn_t callback) { - m_pCallback = callback; -} - -void CSlider::SetValue(float value) { - float old = Value(); - if (Props()->GetFloat("step")) { - value -= fmod(value, Props()->GetFloat("step")); - } - Props()->SetFloat("value", value); - if (old != value) { - if (m_pCallback) { - m_pCallback(this, old, value); - } - } - m_nSliderPos = (GetSize().first) * (float)(value - Props()->GetFloat("value_min")) / (float)(Props()->GetFloat("value_max") - Props()->GetFloat("value_min")); -} - -float CSlider::Value() { - return Props()->GetFloat("value"); -} - -void CSlider::Update() { - if (IsPressed()) { - if (m_bDragInit) { - int delta = m_nLastX - g_pGUI->m_iMouseX; - if (delta) { - auto abs = AbsolutePosition(); - auto size = GetSize(); - int mv = g_pGUI->m_iMouseX - abs.first; - if (mv < 0) mv = 0; - if (mv > size.first) mv = size.first; - SetValue(((float)mv / (float)size.first) * (Props()->GetFloat("value_max") - Props()->GetFloat("value_min")) + Props()->GetFloat("value_min")); - m_nSliderPos = mv; - } - } - m_nLastX = g_pGUI->m_iMouseX; - m_bDragInit = true; - } else m_bDragInit = false; -} - -void CSlider::Draw(int x, int y) { - auto size = GetSize(); - draw::DrawRect(x, y, size.first, size.second, colors::Create(0, 0, 0, 200)); - draw::DrawRect(x, y, m_nSliderPos, size.second, GUIColor()); - char* s = strfmt("%.2f", Value()); - std::string str(s); - delete [] s; - auto sl = draw::GetStringLength(fonts::MENU, str); - draw::String(fonts::MENU, x + (size.first - sl.first) / 2, y + (size.second - sl.second) / 2, colors::white, 1, str); -} diff --git a/src/gui/CSlider.h b/src/gui/CSlider.h deleted file mode 100644 index 63c99cab..00000000 --- a/src/gui/CSlider.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * CSlider.h - * - * Created on: Jan 27, 2017 - * Author: nullifiedcat - */ - -#ifndef CSLIDER_H_ -#define CSLIDER_H_ - -#include "CBaseWidget.h" - -class CSlider; - -typedef std::function SliderCallbackFn_t; - -class CSlider : public CBaseWidget { -public: - CSlider(std::string name = "", IWidget* parent = nullptr); - - void Setup(float min, float max); - void SetStep(float step); - float Value(); - void SetValue(float value); - void SetCallback(SliderCallbackFn_t callback); - - virtual void Update(); - virtual void Draw(int x, int y); - - SliderCallbackFn_t m_pCallback; - - int m_nLastX; - bool m_bDragInit; - int m_nSliderPos; - -}; - - -#endif /* CSLIDER_H_ */ diff --git a/src/gui/CSplitContainer.cpp b/src/gui/CSplitContainer.cpp deleted file mode 100644 index 12532750..00000000 --- a/src/gui/CSplitContainer.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * CSplitContainer.cpp - * - * Created on: Jan 28, 2017 - * Author: nullifiedcat - */ - -#include "CSplitContainer.h" -#include "../common.h" - -CSplitContainer::CSplitContainer(std::string name, IWidget* parent) : CBaseContainer(name, parent) {} - -void CSplitContainer::MoveChildren() { - auto newsize = std::make_pair(GetMaxSize().first, 0); - auto size = GetSize(); - if (!ChildCount()) return; - int width = ((size.first - 4) / ChildCount()) - 2; // TODO padding! - for (int i = 0; i < ChildCount(); i++) { - auto child = ChildByIndex(i); - child->SetOffset(2 + i * width, 2); - child->SetMaxSize(width, -1); - auto csize = child->GetSize(); - if (csize.second + 2 > newsize.second) newsize.second = csize.second + 2; - } - SetSize(-1, newsize.second); -} diff --git a/src/gui/CSplitContainer.h b/src/gui/CSplitContainer.h deleted file mode 100644 index e7e54059..00000000 --- a/src/gui/CSplitContainer.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * CSplitContainer.h - * - * Created on: Jan 28, 2017 - * Author: nullifiedcat - */ - -#ifndef CSPLITCONTAINER_H_ -#define CSPLITCONTAINER_H_ - -#include "CBaseContainer.h" - -class CSplitContainer : public CBaseContainer { -public: - CSplitContainer(std::string name = "unnamed", IWidget* parent = nullptr); - - virtual void MoveChildren() override; -}; - - - -#endif /* CSPLITCONTAINER_H_ */ diff --git a/src/gui/CTextInput.cpp b/src/gui/CTextInput.cpp deleted file mode 100644 index 5c1cfe73..00000000 --- a/src/gui/CTextInput.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * CTextInput.cpp - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#include "CTextInput.h" - -#include "../common.h" -#include "../sdk.h" -#include "GUI.h" - -CTextInput::CTextInput(std::string name, IWidget* parent) : CBaseWidget(name, parent) { - Props()->SetString("value", ""); -} - -bool CTextInput::ConsumesKey(ButtonCode_t key) { - return key >= ButtonCode_t::KEY_FIRST && key <= ButtonCode_t::KEY_BACKSPACE; -} - -void CTextInput::SetMaxWidth(int width) { - auto length = draw::GetStringLength(fonts::MENU, "W"); - SetSize(length.first * width + 4, length.second + 4); // TODO PADDING -} - -std::string CTextInput::Value() { - return std::string(Props()->GetString("value")); -} - -void CTextInput::SetValue(std::string value) { - std::string oldv = Value(); - if (m_pCallback) - m_pCallback(this, oldv, value); - Props()->SetString("value", value.c_str()); -} - -void CTextInput::Draw(int x, int y) { - auto wsize = draw::GetStringLength(fonts::MENU, "W"); - auto size = GetSize(); - int color = colors::Create(0, 0, 0, 80); - if (IsFocused()) color = colors::Transparent(GUIColor(), 0.25); - draw::DrawRect(x, y, size.first, size.second, color); - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - int ml = 0; - int md = 0; - auto dotssize = draw::GetStringLength(fonts::MENU, "..."); // TODO static? - std::string value = Value(); - for (int i = 0; i < value.length(); i++) { - auto strsize = draw::GetStringLength(fonts::MENU, value.substr(i)); - if (strsize.first + 10 + dotssize.first >= size.first) md = i; - if (strsize.first + 8 > size.first) ml = i; - } - if (ml) { - draw::FString(fonts::MENU, x + 2, y + 2, colors::white, 1, "...%s", value.substr(md).c_str()); - } else { - draw::String(fonts::MENU, x + 2, y + 2, colors::white, 1, value); // TODO recalc on update - } -} - -void CTextInput::SetCallback(TextInputCallbackFn_t callback) { - m_pCallback = callback; -} - -void CTextInput::PutChar(char ch) { - SetValue(Value() + std::string(1, ch)); -} - -void CTextInput::OnKeyPress(ButtonCode_t key, bool repeat) { - if (key == ButtonCode_t::KEY_BACKSPACE) { - std::string val = Value(); - if (val.length() > 0) { - SetValue(val.substr(0, val.length() - 1)); - } - return; - } else if (key == ButtonCode_t::KEY_SPACE) { - PutChar(' '); - return; - } else { - char ch = 0; - if (g_pGUI->m_bPressedState[ButtonCode_t::KEY_LSHIFT] || g_pGUI->m_bPressedState[ButtonCode_t::KEY_RSHIFT]) { - ch = GetUpperChar(key); - } else { - ch = GetChar(key); - } - if (ch) { - PutChar(ch); - } - } -} - diff --git a/src/gui/CTextInput.h b/src/gui/CTextInput.h deleted file mode 100644 index f4e8aa1f..00000000 --- a/src/gui/CTextInput.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * CTextInput.h - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#ifndef CTEXTINPUT_H_ -#define CTEXTINPUT_H_ - -#include "CBaseWidget.h" - -class CTextInput; - -typedef std::function TextInputCallbackFn_t; - -class CTextInput : public CBaseWidget { -public: - CTextInput(std::string name = "unnamed", IWidget* parent = nullptr); - - virtual void OnKeyPress(ButtonCode_t key, bool repeat); - virtual void Draw(int x, int y); - virtual bool ConsumesKey(ButtonCode_t key); - - void PutChar(char ch); - void SetLength(int newlength); - void SetMaxWidth(int width); - void SetCallback(TextInputCallbackFn_t callback); - std::string Value(); - void SetValue(std::string value); - - TextInputCallbackFn_t m_pCallback; -}; - -#endif /* CTEXTINPUT_H_ */ diff --git a/src/gui/CTextLabel.cpp b/src/gui/CTextLabel.cpp deleted file mode 100644 index c8fd3137..00000000 --- a/src/gui/CTextLabel.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * CTextLabel.cpp - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#include "CTextLabel.h" - -#include "../common.h" -#include "../sdk.h" - -CTextLabel::CTextLabel(std::string name, IWidget* parent, std::string text, bool centered) : CBaseWidget(name, parent) { - if (centered) { - SetAutoSize(false); - SetCentered(true); - } else { - SetAutoSize(true); - SetCentered(false); - } - SetText(text); -} - -void CTextLabel::SetAutoSize(bool autosize) { - Props()->SetBool("autosize", autosize); -} - -void CTextLabel::SetCentered(bool centered) { - Props()->SetBool("centered", centered); -} - -void CTextLabel::SetPadding(int x, int y) { - Props()->SetInt("padding_x", x); - Props()->SetInt("padding_y", y); -} - -void CTextLabel::SetText(std::string text) { - unsigned long font_handle = Props()->GetInt("font", fonts::MENU); - Props()->SetString("text", text.c_str()); - auto padding = std::make_pair(Props()->GetInt("padding_x"), Props()->GetInt("padding_y")); - auto size = draw::GetStringLength(font_handle, text); - if (Props()->GetBool("autosize")) { - SetSize(size.first + padding.first * 2, size.second + padding.second * 2); - } else { - auto ms = GetMaxSize(); - SetSize(-1, size.second + padding.second * 2); - if (ms.first > 0) { - std::string txt = WordWrap(text, ms.first - 2 * padding.first, menu::ncc::font_item); - auto size2 = draw::GetStringLength(font_handle, txt); - SetSize(size2.first + padding.first * 2, size2.second + padding.second * 2); - Props()->SetString("text", txt.c_str()); - } - } -} - -std::string CTextLabel::GetText() { - return std::string(Props()->GetString("text", "")); -} - -void CTextLabel::Draw(int x, int y) { - if (Props()->GetBool("centered")) { - auto size = GetSize(); - auto ssize = draw::GetStringLength(fonts::MENU, GetText()); - draw::String(fonts::MENU, x + (size.first - ssize.first) / 2, y + (size.second - ssize.second) / 2, colors::white, 1, GetText()); - } else draw::String(fonts::MENU, x, y, colors::white, 1, GetText()); -} diff --git a/src/gui/CTextLabel.h b/src/gui/CTextLabel.h deleted file mode 100644 index 1b29f887..00000000 --- a/src/gui/CTextLabel.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * CTextLabel.h - * - * Created on: Jan 26, 2017 - * Author: nullifiedcat - */ - -#ifndef CTEXTLABEL_H_ -#define CTEXTLABEL_H_ - -#include "CBaseWidget.h" - -#include "../fixsdk.h" -#include "Color.h" - -class CTextLabel : public CBaseWidget { -public: - CTextLabel(std::string name = "unnamed", IWidget* parent = nullptr, std::string text = "", bool centered = false); - - void SetText(std::string text); - std::string GetText(); - void SetPadding(int x, int y); - void SetAutoSize(bool autosize); - void SetCentered(bool centered); - - virtual void Draw(int x, int y); -}; - -#endif /* CTEXTLABEL_H_ */ diff --git a/src/gui/CTooltip.cpp b/src/gui/CTooltip.cpp deleted file mode 100644 index 6f8c23f8..00000000 --- a/src/gui/CTooltip.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* - * CTooltip.cpp - * - * Created on: Jan 28, 2017 - * Author: nullifiedcat - */ - -#include "CTooltip.h" -#include "../common.h" -#include "../sdk.h" - -#include - -CTooltip::CTooltip(IWidget* parent) : CTextLabel("tooltip", parent) { - SetZIndex(999); - SetPadding(4, 4); - SetMaxSize(100, -1); - SetAutoSize(false); - SetSize(100, -1); -} - -void CTooltip::Draw(int x, int y) { - auto size = GetSize(); - draw::DrawRect(x, y, size.first, size.second, colors::Create(0, 0, 0, 230)); - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - draw::String(fonts::MENU, x + Props()->GetInt("padding_x"), y + Props()->GetInt("padding_y"), GUIColor(), 1, GetText()); -} diff --git a/src/gui/CTooltip.h b/src/gui/CTooltip.h deleted file mode 100644 index 3217fea9..00000000 --- a/src/gui/CTooltip.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * CTooltip.h - * - * Created on: Jan 28, 2017 - * Author: nullifiedcat - */ - -#ifndef CTOOLTIP_H_ -#define CTOOLTIP_H_ - -#include "CTextLabel.h" - -class CTooltip : public CTextLabel { -public: - CTooltip(IWidget* parent = nullptr); - - virtual void Draw(int x, int y); - inline virtual PositionMode GetPositionMode() { return PositionMode::FLOATING; } -}; - -#endif /* CTOOLTIP_H_ */ diff --git a/src/gui/GUI.cpp b/src/gui/GUI.cpp index d9bdefd5..44901895 100644 --- a/src/gui/GUI.cpp +++ b/src/gui/GUI.cpp @@ -6,43 +6,27 @@ */ #include "GUI.h" -#include "IWidget.h" -#include "RootWindow.h" -#include "CTooltip.h" #include "../common.h" #include "../sdk.h" - - void GUIVisibleCallback(IConVar* var, const char* pOldValue, float flOldValue) { g_IInputSystem->SetCursorPosition(draw::width / 2, draw::height / 2); g_ISurface->SetCursor(vgui::CursorCode::dc_none); - //g_IMatSystemSurface->SetCursorAlwaysVisible(false); if (gui_visible) { g_ISurface->UnlockCursor(); g_ISurface->SetCursorAlwaysVisible(true); - //g_IMatSystemSurface->UnlockCursor(); } else { g_ISurface->LockCursor(); g_ISurface->SetCursorAlwaysVisible(false); - //g_IMatSystemSurface->LockCursor(); } } CatVar gui_visible(CV_SWITCH, "gui_visible", "0", "GUI Active", "GUI switch (bind it to a key!)"); -CatVar gui_draw_bounds(CV_SWITCH, "gui_bounds", "0", "Draw Bounds", "Draw GUI elements' bounding boxes"); -//CatVar gui_nullcore(CV_SWITCH, "gui_nullcore", "1", "NullCore GUI", "Use NullCoreCheat GUI"); -CatGUI::CatGUI() { - root_nullcore = nullptr; - m_pRootWindow = 0; -} +CatGUI::CatGUI() {} -CatGUI::~CatGUI() { - delete root_nullcore; - delete m_pRootWindow; -} +CatGUI::~CatGUI() {} bool CatGUI::Visible() { return gui_visible; @@ -52,56 +36,47 @@ CatVar gui_color_r(CV_INT, "gui_color_r", "255", "Main GUI color (red)", "Define CatVar gui_color_g(CV_INT, "gui_color_g", "105", "Main GUI color (green)", "Defines green component of main gui color", 0, 255); CatVar gui_color_b(CV_INT, "gui_color_b", "180", "Main GUI color (blue)", "Defines blue component of main gui color", 0, 255); +CatVar gui_debug(CV_SWITCH, "gui_debug", "0", "Debug GUI"); + static CatVar gui_rainbow(CV_SWITCH, "gui_rainbow", "0", "Rainbow GUI", "RGB all the things!!!"); -int GUIColor() { - return gui_rainbow ? colors::RainbowCurrent() : colors::Create((int)gui_color_r, (int)gui_color_g, (int)gui_color_b, 255); +rgba_t GUIColor() { + return gui_rainbow ? colors::RainbowCurrent() : colors::FromRGBA8(int(gui_color_r), int(gui_color_g), int(gui_color_b), 255); } void CatGUI::Setup() { - m_pRootWindow = new RootWindow(); - m_pRootWindow->Setup(); - menu::ncc::Init(); - root_nullcore = menu::ncc::root; gui_visible.OnRegister([](CatVar* var) { var->convar->InstallChangeCallback(GUIVisibleCallback); }); } -void CatGUI::ShowTooltip(std::string text) { - m_pTooltip->SetText(text); - m_pTooltip->SetOffset(m_iMouseX + 5, m_iMouseY + 5); - m_pTooltip->Show(); - m_bShowTooltip = true; -} - - void CatGUI::Update() { + int nx = g_IInputSystem->GetAnalogValue(AnalogCode_t::MOUSE_X); + int ny = g_IInputSystem->GetAnalogValue(AnalogCode_t::MOUSE_Y); + + mouse_dx = nx - m_iMouseX; + mouse_dy = ny - m_iMouseY; + + m_iMouseX = nx; + m_iMouseY = ny; + try { - CBaseWindow* root = gui_nullcore ? dynamic_cast(root_nullcore) : dynamic_cast(m_pRootWindow); - if (gui_nullcore) m_pRootWindow->Hide(); - else root_nullcore->Hide(); - m_bShowTooltip = false; int new_scroll = g_IInputSystem->GetAnalogValue(AnalogCode_t::MOUSE_WHEEL); - //logging::Info("scroll: %i", new_scroll); if (last_scroll_value < new_scroll) { - // Scrolled up m_bPressedState[ButtonCode_t::MOUSE_WHEEL_DOWN] = false; m_bPressedState[ButtonCode_t::MOUSE_WHEEL_UP] = true; } else if (last_scroll_value > new_scroll) { - // Scrolled down m_bPressedState[ButtonCode_t::MOUSE_WHEEL_DOWN] = true; m_bPressedState[ButtonCode_t::MOUSE_WHEEL_UP] = false; } else { - // Didn't scroll m_bPressedState[ButtonCode_t::MOUSE_WHEEL_DOWN] = false; m_bPressedState[ButtonCode_t::MOUSE_WHEEL_UP] = false; } last_scroll_value = new_scroll; for (int i = 0; i < ButtonCode_t::BUTTON_CODE_COUNT; i++) { - bool down = false, changed = false;; + bool down = false, changed = false; if (i != ButtonCode_t::MOUSE_WHEEL_DOWN && i != ButtonCode_t::MOUSE_WHEEL_UP) { - down = g_IInputSystem->IsButtonDown((ButtonCode_t)(i)); + down = g_IInputSystem->IsButtonDown(ButtonCode_t(i)); changed = m_bPressedState[i] != down; } else { down = m_bPressedState[i]; @@ -111,79 +86,26 @@ void CatGUI::Update() { m_bPressedState[i] = down; if (m_bKeysInit) { if (changed) { - //logging::Info("Key %i changed! Now %i.", i, down); + if (gui_debug) { + logging::Info("Key %d changed, now %d", i, down); + } if (i == ButtonCode_t::MOUSE_LEFT) { if (Visible()) { - if (down) root->OnMousePress(); - else root->OnMouseRelease(); + // Mouse is pressed. } - } else { - if ((i == ButtonCode_t::KEY_INSERT || i == ButtonCode_t::KEY_F11) && down) { - gui_visible = !gui_visible; - } - if (Visible()) { - if (down) root->OnKeyPress((ButtonCode_t)i, false); - else root->OnKeyRelease((ButtonCode_t)i); - } - } - } else { - if (down) { - int frame = g_GlobalVars->framecount - m_iPressedFrame[i]; - bool shouldrepeat = false; - if (frame) { - if (frame > 150) { - if (frame > 400) { - if (frame % 30 == 0) shouldrepeat = true; - } else { - if (frame % 80 == 0) shouldrepeat = true; - } + } else if (down) { + if ((i == ButtonCode_t::KEY_INSERT || i == ButtonCode_t::KEY_F11)) { + if (gui_debug) { + logging::Info("GUI key pressed"); } - } - if (Visible()) { - if (shouldrepeat) root->OnKeyPress((ButtonCode_t)i, true); + gui_visible = !gui_visible; } } } } } - int nx = g_IInputSystem->GetAnalogValue(AnalogCode_t::MOUSE_X); - int ny = g_IInputSystem->GetAnalogValue(AnalogCode_t::MOUSE_Y); - - mouse_dx = nx - m_iMouseX; - mouse_dy = ny - m_iMouseY; - - m_iMouseX = nx; - m_iMouseY = ny; - if (!m_bKeysInit) m_bKeysInit = 1; - if (!root->IsVisible()) - root->Show(); - root->Update(); - if (!m_bShowTooltip && m_pTooltip->IsVisible()) m_pTooltip->Hide(); - root->Draw(0, 0); - if (Visible()) { - draw::DrawRect(m_iMouseX - 5, m_iMouseY - 5, 10, 10, colors::Transparent(colors::white)); - draw::OutlineRect(m_iMouseX - 5, m_iMouseY - 5, 10, 10, GUIColor()); - } - if (gui_draw_bounds) { - root->DrawBounds(0, 0); - } - /*if (gui_visible) { - if (!root->IsVisible()) - root->Show(); - root->Update(); - if (!m_bShowTooltip && m_pTooltip->IsVisible()) m_pTooltip->Hide(); - root->Draw(0, 0); - draw::DrawRect(m_iMouseX - 5, m_iMouseY - 5, 10, 10, colors::Transparent(colors::white)); - draw::OutlineRect(m_iMouseX - 5, m_iMouseY - 5, 10, 10, GUIColor()); - if (gui_draw_bounds) { - root->DrawBounds(0, 0); - } - } else { - if (root->IsVisible()) - root->Hide(); - }*/ } catch (std::exception& ex) { logging::Info("ERROR: %s", ex.what()); } @@ -191,14 +113,11 @@ void CatGUI::Update() { } bool CatGUI::ConsumesKey(ButtonCode_t key) { - CBaseWindow* root = gui_nullcore ? dynamic_cast(root_nullcore) : dynamic_cast(m_pRootWindow); - if (root->IsVisible()) - return root->ConsumesKey(key); - else return false; -} - -RootWindow* CatGUI::GetRootWindow() { - return m_pRootWindow; + static const std::vector keys_noconsume({KEY_ESCAPE, KEY_BACKQUOTE}); + for (const auto& i : keys_noconsume) { + if (i == key) return false; + } + return Visible(); } CatGUI* g_pGUI = 0; diff --git a/src/gui/GUI.h b/src/gui/GUI.h index e610b4a3..d9b36758 100644 --- a/src/gui/GUI.h +++ b/src/gui/GUI.h @@ -11,27 +11,15 @@ class IWidget; class CatVar; -#include "../beforecheaders.h" -#include -#include "../aftercheaders.h" - -#include "ncc/Root.hpp" -#include "ncc/Menu.hpp" - -#include "../fixsdk.h" -#include "../inputsystem/ButtonCode.h" - -class CTooltip; -class RootWindow; +#include "../common.h" extern CatVar gui_color_r; extern CatVar gui_color_g; extern CatVar gui_color_b; -int GUIColor(); +extern CatVar gui_debug; +rgba_t GUIColor(); extern CatVar gui_visible; -extern CatVar gui_draw_bounds; -constexpr bool gui_nullcore = true; class CatGUI { public: @@ -41,17 +29,8 @@ public: bool Visible(); void Update(); void Setup(); - RootWindow* GetRootWindow(); bool ConsumesKey(ButtonCode_t key); - void ShowTooltip(std::string text); - - CTooltip* m_pTooltip; - RootWindow* m_pRootWindow; - - // TODO NullCore tooltip - menu::ncc::Root* root_nullcore; - int last_scroll_value; bool m_bShowTooltip; bool m_bConsumeKeys; diff --git a/src/gui/IWidget.cpp b/src/gui/IWidget.cpp deleted file mode 100644 index 244994cc..00000000 --- a/src/gui/IWidget.cpp +++ /dev/null @@ -1,10 +0,0 @@ -/* - * IWidget.cpp - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#include "IWidget.h" - -IWidget::~IWidget() {} diff --git a/src/gui/IWidget.h b/src/gui/IWidget.h deleted file mode 100644 index 1f149d8b..00000000 --- a/src/gui/IWidget.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * IWidget.h - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#ifndef IWIDGET_H_ -#define IWIDGET_H_ - -#include "../beforecheaders.h" -#include -#include -#include -#include "../aftercheaders.h" - -#include "../inputsystem/ButtonCode.h" - -enum PositionMode { - ABSOLUTE = 0, - INLINE, - FLOATING -}; - -class KeyValues; - -class IWidget { -public: - virtual ~IWidget(); - - virtual void Update() = 0; - virtual void Draw(int x, int y) = 0; - virtual void DrawBounds(int x, int y) = 0; - - virtual KeyValues* Props() = 0; - - virtual void OnMouseEnter() = 0; - virtual void OnMouseLeave() = 0; - virtual void OnMousePress() = 0; - virtual void OnMouseRelease() = 0; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) = 0; - virtual void OnKeyRelease(ButtonCode_t key) = 0; - virtual void OnFocusGain() = 0; - virtual void OnFocusLose() = 0; - - virtual void HandleCustomEvent(KeyValues* event) = 0; - - virtual bool ConsumesKey(ButtonCode_t key) = 0; - - // Widget will be visible even when gui is turned off - virtual bool AlwaysVisible() = 0; - virtual void Show() = 0; - virtual void Hide() = 0; - virtual bool IsVisible() = 0; - - virtual bool IsHovered() = 0; - virtual bool IsFocused() = 0; - virtual bool IsPressed() = 0; - - virtual bool DoesStealFocus() = 0; - - virtual void SetOffset(int x, int y) = 0; - virtual void SetMaxSize(int x, int y) = 0; - virtual void SetSize(int x, int y) = 0; - virtual std::pair GetOffset() = 0; - virtual std::pair GetSize() = 0; - virtual std::pair GetMaxSize() = 0; - virtual int GetZIndex() = 0; - virtual void SetZIndex(int idx) = 0; - - virtual std::string GetTooltip() = 0; - - virtual PositionMode GetPositionMode() = 0; - virtual void SetPositionMode(PositionMode) = 0; - - virtual IWidget* GetParent() = 0; - virtual void SetParent(IWidget*) = 0; - virtual std::string GetName() = 0; -}; - - -#endif /* IWIDGET_H_ */ diff --git a/src/gui/RootWindow.cpp b/src/gui/RootWindow.cpp deleted file mode 100644 index fa1e892d..00000000 --- a/src/gui/RootWindow.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * RootWindow.cpp - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#include "RootWindow.h" -#include "CTextLabel.h" -#include "CCheckbox.h" -#include "CBaseButton.h" -#include "CTextInput.h" -#include "CSplitContainer.h" -#include "CSlider.h" -#include "CTooltip.h" -#include "CBaseContainer.h" -#include "CDropdown.h" -#include "CMenuContainer.h" -#include "CCVarContainer.h" -#include "CMenuWindow.h" - -#include "../common.h" -#include "CCTitleBar.h" - -void B1Callback(CBaseButton* thisptr) { - CBaseContainer* container = dynamic_cast(thisptr->GetParent()); - CTextLabel* label = dynamic_cast(container->ChildByName("td")); - if (label) { - char* text = strfmt("wow! this[\"%s\"] = %i", "test_value", thisptr->Props()->GetInt("test_value")); - label->SetText(text); - delete [] text; - } -} - -void TICallback(CTextInput* thisptr, std::string olds, std::string news) { - CBaseContainer* container = dynamic_cast(thisptr->GetParent()); - CTextLabel* tl = dynamic_cast(container->ChildByName("td")); - if (tl) { - char* text = strfmt("wow! text: %s", news.c_str()); - tl->SetText(text); - delete [] text; - } -} - -RootWindow::RootWindow() : CBaseWindow("root") {} - -void RootWindow::Setup() { - g_pGUI->m_pTooltip = new CTooltip(); - AddChild(g_pGUI->m_pTooltip); - SetMaxSize(draw::width, draw::height); - CBaseWindow* ws = new CBaseWindow("splitwindow"); - ws->SetPositionMode(ABSOLUTE); - CTitleBar* wst = new CTitleBar(ws, "Window Layout Test"); - ws->AddChild(wst); - ws->SetMaxSize(500, 0); - CMenuWindow* win = new CMenuWindow("menu_window", this); - win->SetMaxSize(912, 410); - auto ms = GetMaxSize(); - win->AddElements(); - win->SetOffset((draw::width - 912) / 2, (draw::height - 410) / 2); - AddChild(win); -} diff --git a/src/gui/RootWindow.h b/src/gui/RootWindow.h deleted file mode 100644 index 3515c098..00000000 --- a/src/gui/RootWindow.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * RootWindow.h - * - * Created on: Jan 25, 2017 - * Author: nullifiedcat - */ - -#ifndef ROOTWINDOW_H_ -#define ROOTWINDOW_H_ - -#include "CBaseWindow.h" - -class RootWindow : public CBaseWindow { -public: - RootWindow(); - - void Setup(); - - inline virtual void MoveChildren() override {}; -}; - -#endif /* ROOTWINDOW_H_ */ diff --git a/src/gui/guicommon.h b/src/gui/guicommon.h deleted file mode 100644 index 81b81ac3..00000000 --- a/src/gui/guicommon.h +++ /dev/null @@ -1,15 +0,0 @@ -/* - * guicommon.h - * - * Created on: Apr 21, 2017 - * Author: nullifiedcat - */ - -#ifndef GUICOMMON_H_ -#define GUICOMMON_H_ - -#include "CBaseContainer.h" -#include "CBaseWidget.h" -#include "GUI.h" - -#endif /* GUICOMMON_H_ */ diff --git a/src/gui/im/Im.cpp b/src/gui/im/Im.cpp new file mode 100644 index 00000000..6672c525 --- /dev/null +++ b/src/gui/im/Im.cpp @@ -0,0 +1,383 @@ +/* + * Im.cpp + * + * Created on: May 21, 2017 + * Author: nullifiedcat + */ + +#include "Im.hpp" +#include "Schema.hpp" +#include "Playerlist.hpp" +#include "InfoPanel.hpp" + +#include "../../common.h" + +#include "imgui.h" + +namespace menu { namespace im { + +void CatVar_Integer(CatVar& var) { + const char* label = var.name.c_str(); + if (var.desc_short.size() > 0) label = var.desc_short.c_str(); + + float minval = 0; + float maxval = 100; + if (var.restricted) { + minval = var.min; + maxval = var.max; + } + + ImGui::PushID(var.id); + + int value = var; + ImGui::PushItemWidth(120.0f); + int step = var.restricted ? (var.max - var.min) / 50 : 1; + if (step == 0) step = 1; + if (ImGui::InputInt(label, &value, step, step * 20)) { + var = value; + } + /*if (ImGui::SliderInt(label, &value, minval, maxval)) { + var = value; + }*/ + if (ImGui::IsItemHovered() && var.desc_long.size()) { + ImGui::BeginTooltip(); + ImGui::Text("%s", var.desc_long.c_str()); + ImGui::EndTooltip(); + } + + ImGui::PopID(); +} + +void CatVar_Float(CatVar& var) { + const char* label = var.name.c_str(); + if (var.desc_short.size() > 0) label = var.desc_short.c_str(); + + float minval = 0; + float maxval = 100; + if (var.restricted) { + minval = var.min; + maxval = var.max; + } + + ImGui::PushID(var.id); + + float value = var; + ImGui::PushItemWidth(120.0f); + float step = var.restricted ? (var.max - var.min) / 50 : 1; + if (ImGui::InputFloat(label, &value, step, step * 20)) { + var = value; + } + /*if (ImGui::SliderFloat(label, &value, minval, maxval)) { + var = value; + }*/ + if (ImGui::IsItemHovered() && var.desc_long.size()) { + ImGui::BeginTooltip(); + ImGui::Text("%s", var.desc_long.c_str()); + ImGui::EndTooltip(); + } + + ImGui::PopID(); +} + +void CatVar_Enum(CatVar& var) { + const char* label = var.name.c_str(); + if (var.desc_short.size() > 0) label = var.desc_short.c_str(); + + ImGui::PushID(var.id); + + int value = var; + const char** items = new const char*[var.enum_type->value_names.size()]; + for (int i = 0; i < var.enum_type->value_names.size(); i++) { + items[i] = var.enum_type->value_names[i].c_str(); + } + ImGui::PushItemWidth(120.0f); + if (ImGui::Combo(label, &value, items, var.enum_type->value_names.size())) { + var = value; + } + if (ImGui::IsItemHovered() && var.desc_long.size()) { + ImGui::BeginTooltip(); + ImGui::Text(var.desc_long.c_str()); + ImGui::EndTooltip(); + } + + ImGui::PopID(); +} + +void CatVar_String(CatVar& var) { + const char* label = var.name.c_str(); + if (var.desc_short.size() > 0) label = var.desc_short.c_str(); + + ImGui::PushID(var.id); + + char buf[256] { 0 }; + snprintf(buf, 255, "%s", var.GetString()); + ImGui::PushItemWidth(100.0f); + if (ImGui::InputText(label, buf, 256)) { + var.SetValue(std::string(buf)); + } + + if (ImGui::IsItemHovered() && var.desc_long.size()) { + ImGui::BeginTooltip(); + ImGui::Text("%s", var.desc_long.c_str()); + ImGui::EndTooltip(); + } + + ImGui::PopID(); +} + +void CatVar_Key(CatVar& var) { + static const char** keys_array = nullptr; + if (!keys_array) { + keys_array = new const char*[ButtonCode_t::BUTTON_CODE_COUNT]; + for (int i = 0; i < ButtonCode_t::BUTTON_CODE_COUNT; i++) { + keys_array[i] = g_IInputSystem->ButtonCodeToString(ButtonCode_t(i)); + } + } + + const char* label = var.name.c_str(); + if (var.desc_short.size() > 0) label = var.desc_short.c_str(); + + ImGui::PushID(var.id); + + int value = var; + ImGui::PushItemWidth(75.0f); + if (ImGui::Combo(label, &value, keys_array, BUTTON_CODE_COUNT)) { + var = value; + } + if (ImGui::IsItemHovered() && var.desc_long.size()) { + ImGui::BeginTooltip(); + ImGui::Text("%s", var.desc_long.c_str()); + ImGui::EndTooltip(); + } + + ImGui::PopID(); + +} + +void CatVar_Switch(CatVar& var) { + const char* label = var.name.c_str(); + if (var.desc_short.size() > 0) label = var.desc_short.c_str(); + + ImGui::PushID(var.id); + + bool value = var; + if (ImGui::Checkbox(label, &value)) { + var = value; + } + if (ImGui::IsItemHovered() && var.desc_long.size()) { + ImGui::BeginTooltip(); + ImGui::Text("%s", var.desc_long.c_str()); + ImGui::EndTooltip(); + } + + ImGui::PopID(); +} + +void RenderList(ListEntry_List* list) { + int column = 0; + for (const auto& j : list->entries) { + switch (j->type) { + case VARIABLE: { + if (!column) { + ImGui::Columns(3, nullptr, 0); + } + CatVar& v = ((ListEntry_Variable*)j.get())->var; + switch (v.type) { + case CV_SWITCH: CatVar_Switch(v); break; + case CV_INT: CatVar_Integer(v); break; + case CV_FLOAT: CatVar_Float(v); break; + case CV_STRING: CatVar_String(v); break; + case CV_KEY: CatVar_Key(v); break; + case CV_ENUM: CatVar_Enum(v); break; + } + if (column < 2) { + ImGui::NextColumn(); + column++; + } else { + column = 0; + } + } break; + case LABEL: + ImGui::Text(((ListEntry_Label*)j.get())->text.c_str()); + break; + case SUBLIST: + ImGui::Columns(1); + column = 0; + if (ImGui::CollapsingHeader(((ListEntry_List*)j.get())->name.c_str())) { + RenderList((ListEntry_List*)j.get()); + } + } + } +} + +int active_list = 0; + +struct ImVec3 { float x, y, z; ImVec3(float _x = 0.0f, float _y = 0.0f, float _z = 0.0f) { x = _x; y = _y; z = _z; } }; + +void imgui_easy_theming(ImVec3 color_for_text, ImVec3 color_for_head, ImVec3 color_for_area, ImVec3 color_for_body, ImVec3 color_for_pops) +{ + ImGuiStyle& style = ImGui::GetStyle(); + + style.Colors[ImGuiCol_Text] = ImVec4( color_for_text.x, color_for_text.y, color_for_text.z, 1.00f ); + style.Colors[ImGuiCol_TextDisabled] = ImVec4( color_for_text.x, color_for_text.y, color_for_text.z, 0.58f ); + style.Colors[ImGuiCol_WindowBg] = ImVec4( color_for_body.x, color_for_body.y, color_for_body.z, 0.95f ); + style.Colors[ImGuiCol_ChildWindowBg] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 0.58f ); + style.Colors[ImGuiCol_Border] = ImVec4( color_for_body.x, color_for_body.y, color_for_body.z, 0.00f ); + style.Colors[ImGuiCol_BorderShadow] = ImVec4( color_for_body.x, color_for_body.y, color_for_body.z, 0.00f ); + style.Colors[ImGuiCol_FrameBg] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 1.00f ); + style.Colors[ImGuiCol_FrameBgHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.78f ); + style.Colors[ImGuiCol_FrameBgActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_TitleBg] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 1.00f ); + style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 0.75f ); + style.Colors[ImGuiCol_TitleBgActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_MenuBarBg] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 0.47f ); + style.Colors[ImGuiCol_ScrollbarBg] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 1.00f ); + style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.21f ); + style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.78f ); + style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_ComboBg] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 1.00f ); + style.Colors[ImGuiCol_CheckMark] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.80f ); + style.Colors[ImGuiCol_SliderGrab] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.50f ); + style.Colors[ImGuiCol_SliderGrabActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_Button] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.50f ); + style.Colors[ImGuiCol_ButtonHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.86f ); + style.Colors[ImGuiCol_ButtonActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_Header] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.76f ); + style.Colors[ImGuiCol_HeaderHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.86f ); + style.Colors[ImGuiCol_HeaderActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_Column] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.32f ); + style.Colors[ImGuiCol_ColumnHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.78f ); + style.Colors[ImGuiCol_ColumnActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_ResizeGrip] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.15f ); + style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.78f ); + style.Colors[ImGuiCol_ResizeGripActive] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_CloseButton] = ImVec4( color_for_text.x, color_for_text.y, color_for_text.z, 0.16f ); + style.Colors[ImGuiCol_CloseButtonHovered] = ImVec4( color_for_text.x, color_for_text.y, color_for_text.z, 0.39f ); + style.Colors[ImGuiCol_CloseButtonActive] = ImVec4( color_for_text.x, color_for_text.y, color_for_text.z, 1.00f ); + style.Colors[ImGuiCol_PlotLines] = ImVec4( color_for_text.x, color_for_text.y, color_for_text.z, 0.63f ); + style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_PlotHistogram] = ImVec4( color_for_text.x, color_for_text.y, color_for_text.z, 0.63f ); + style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 1.00f ); + style.Colors[ImGuiCol_TextSelectedBg] = ImVec4( color_for_head.x, color_for_head.y, color_for_head.z, 0.43f ); + style.Colors[ImGuiCol_PopupBg] = ImVec4( color_for_pops.x, color_for_pops.y, color_for_pops.z, 0.92f ); + style.Colors[ImGuiCol_ModalWindowDarkening] = ImVec4( color_for_area.x, color_for_area.y, color_for_area.z, 0.73f ); +} + +#define IM3_RGB(r,g,b) ImVec3((float)r / 255.f, (float)g / 255.f, (float)b / 255.f) + +void Render() { + static bool styles_setup = false; + if (!styles_setup) { + ImGuiStyle * style = &ImGui::GetStyle(); + + style->WindowPadding = ImVec2(15, 15); + //style->WindowRounding = 5.0f; + style->WindowRounding = 1.0f; + + style->FramePadding = ImVec2(5, 5); + //style->FrameRounding = 4.0f; + style->FrameRounding = 1.0f; + + style->ItemSpacing = ImVec2(12, 8); + //style->ItemInnerSpacing = ImVec2(8, 6); + style->ItemInnerSpacing = ImVec2(6, 6); + style->IndentSpacing = 25.0f; + style->ScrollbarSize = 15.0f; + //style->ScrollbarRounding = 9.0f; + style->ScrollbarRounding = 1.0f; + + style->GrabMinSize = 5.0f; + //style->GrabRounding = 3.0f; + style->GrabRounding = 1.0f; + + + style->Colors[ImGuiCol_Text] = ImVec4(0.80f, 0.80f, 0.83f, 1.00f); + style->Colors[ImGuiCol_TextDisabled] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); + style->Colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); + style->Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); + style->Colors[ImGuiCol_PopupBg] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); + style->Colors[ImGuiCol_Border] = ImVec4(0.80f, 0.80f, 0.83f, 0.88f); + style->Colors[ImGuiCol_BorderShadow] = ImVec4(0.92f, 0.91f, 0.88f, 0.00f); + style->Colors[ImGuiCol_FrameBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); + style->Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); + style->Colors[ImGuiCol_FrameBgActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); + style->Colors[ImGuiCol_TitleBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); + style->Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 0.98f, 0.95f, 0.75f); + style->Colors[ImGuiCol_TitleBgActive] = ImVec4(0.07f, 0.07f, 0.09f, 1.00f); + style->Colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); + style->Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); + style->Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); + style->Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); + style->Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); + style->Colors[ImGuiCol_ComboBg] = ImVec4(0.19f, 0.18f, 0.21f, 1.00f); + style->Colors[ImGuiCol_CheckMark] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); + style->Colors[ImGuiCol_SliderGrab] = ImVec4(0.80f, 0.80f, 0.83f, 0.31f); + style->Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); + style->Colors[ImGuiCol_Button] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); + style->Colors[ImGuiCol_ButtonHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); + style->Colors[ImGuiCol_ButtonActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); + style->Colors[ImGuiCol_Header] = ImVec4(0.10f, 0.09f, 0.12f, 1.00f); + style->Colors[ImGuiCol_HeaderHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); + style->Colors[ImGuiCol_HeaderActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); + style->Colors[ImGuiCol_Column] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); + style->Colors[ImGuiCol_ColumnHovered] = ImVec4(0.24f, 0.23f, 0.29f, 1.00f); + style->Colors[ImGuiCol_ColumnActive] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); + style->Colors[ImGuiCol_ResizeGrip] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + style->Colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.56f, 0.56f, 0.58f, 1.00f); + style->Colors[ImGuiCol_ResizeGripActive] = ImVec4(0.06f, 0.05f, 0.07f, 1.00f); + style->Colors[ImGuiCol_CloseButton] = ImVec4(0.40f, 0.39f, 0.38f, 0.16f); + style->Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.40f, 0.39f, 0.38f, 0.39f); + style->Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.40f, 0.39f, 0.38f, 1.00f); + style->Colors[ImGuiCol_PlotLines] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); + style->Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); + style->Colors[ImGuiCol_PlotHistogram] = ImVec4(0.40f, 0.39f, 0.38f, 0.63f); + style->Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.25f, 1.00f, 0.00f, 1.00f); + style->Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 1.00f, 0.00f, 0.43f); + style->Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(1.00f, 0.98f, 0.95f, 0.73f); + styles_setup = true; + } + + // Info panel should be rendered even with main gui disabled + //RenderInfoPanel(); + + if (!gui_visible) { + ImGui::GetIO().MouseDrawCursor = false; + return; + } else { + ImGui::GetIO().MouseDrawCursor = true; + ImGui::SetMouseCursor(ImGuiMouseCursor_Arrow); + } + + if (gui_debug) + ImGui::ShowTestWindow(); + RenderPlayerlist(); + /*ImGui::Begin("Colors"); + static ImVec3 color_for_text = IM3_RGB(246, 236, 255); + static ImVec3 color_for_head = IM3_RGB(209, 96, 165); + static ImVec3 color_for_area = IM3_RGB(104, 57, 78); + static ImVec3 color_for_body = IM3_RGB(80, 44, 68); + static ImVec3 color_for_pops = IM3_RGB(58, 33, 59); + if (ImGui::ColorEdit3("Text", &color_for_text.x) || + ImGui::ColorEdit3("Head", &color_for_head.x) || + ImGui::ColorEdit3("Area", &color_for_area.x) || + ImGui::ColorEdit3("Body", &color_for_body.x) || + ImGui::ColorEdit3("Pops", &color_for_pops.x)) { + imgui_easy_theming(color_for_text, color_for_head, color_for_area, color_for_body, color_for_pops); + } + ImGui::End();*/ + if (!main_list_array.size()) return; + ImGui::Begin("Config Menu"); + ImGui::SetWindowSize(ImVec2{900, 600}); + if (active_list >= main_list_array.size()) active_list = 0; + for (int i = 0; i < main_list_array.size(); i++) { + if (ImGui::Button(main_list_array.at(i)->name.c_str())) { + active_list = i; + } + ImGui::SameLine(); + } + ImGui::NewLine(); + RenderList(main_list_array.at(active_list)); + ImGui::End(); +} + +}} diff --git a/src/gui/im/Im.hpp b/src/gui/im/Im.hpp new file mode 100644 index 00000000..11703a21 --- /dev/null +++ b/src/gui/im/Im.hpp @@ -0,0 +1,26 @@ +/* + * Im.hpp + * + * Created on: May 21, 2017 + * Author: nullifiedcat + */ + +#ifndef IM_HPP_ +#define IM_HPP_ + +class CatVar; + +namespace menu { namespace im { + +void CatVar_Integer(CatVar& var); +void CatVar_Float(CatVar& var); +void CatVar_Enum(CatVar& var); +void CatVar_String(CatVar& var); +void CatVar_Key(CatVar& var); +void CatVar_Switch(CatVar& var); + +void Render(); + +}} + +#endif /* IM_HPP_ */ diff --git a/src/gui/im/InfoPanel.cpp b/src/gui/im/InfoPanel.cpp new file mode 100644 index 00000000..caac2bc4 --- /dev/null +++ b/src/gui/im/InfoPanel.cpp @@ -0,0 +1,73 @@ +/* + * InfoPanel.cpp + * + * Created on: Jul 7, 2017 + * Author: nullifiedcat + */ + +/* +#include "../../common.h" +#include "../../cvwrapper.h" +#include "imgui.h" +#include "InfoPanel.hpp" + +namespace menu { namespace im { + +// User settings +CatVar enabled(CV_SWITCH, "info_panel_enabled", "0", "Enable Info Panel"); +CatVar aimbot_enabled(CV_SWITCH, "info_panel_aimbot", "0", "Show Aimbot"); +CatVar aimkey_enabled(CV_SWITCH, "info_panel_aimkey_toggle", "0", "Show Aimkey Toggle"); + +// Main ImGui menu creator +void RenderInfoPanel() { + + // Check if info menu is enabled + if (!enabled) return; + + // Check if in-game + if (!g_IEngine->IsInGame()) return; + + // Menu creation stuff pasted from playerlist + if (ImGui::Begin("Info Panel")) { + ImGui::SetWindowSize(ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); + + // The main meat of the info panel + if (aimbot_enabled) AddInfoItem(EInfo::AIMBOT, 169); + if (aimkey_enabled) AddInfoItem(EInfo::AIMKEY, 269); + + + ImGui::PopStyleVar(); + } + ImGui::End(); +} + +// Function to add individual items to menu +void AddInfoItem(EInfo info_type, int id) { + + // Dont know what this does but i just use some numbers with 69 to make it somewhat different + ImGui::PushID(id); + + // Switch based on into_type + switch (info_type) { + case EInfo::AIMBOT: + ImGui::Text(format("Aimbot: ", GetCatVar("aimbot_enabled") ? "enabled" : "disabled").c_str()); + break; + case EInfo::AIMKEY: + ImGui::Text(format("Todo, get toggle mode from aimkey").c_str()); + break; + }; + + // Dont know what this does but im expecting i would need it + ImGui::PopID(); +} + +// Helper function ripped from schema.cpp due to ussues if i tri to use it directly from there +CatVar* GetCatVar(const std::string name) { + for (auto var : CatVarList()) { + if (var->name == name) return var; + } + return nullptr; +} + +}}*/ \ No newline at end of file diff --git a/src/gui/im/InfoPanel.hpp b/src/gui/im/InfoPanel.hpp new file mode 100644 index 00000000..fae5869a --- /dev/null +++ b/src/gui/im/InfoPanel.hpp @@ -0,0 +1,28 @@ +/* + * InfoPanel.hpp + * + * Created on: Jul 7, 2017 + * Author: nullifiedcat + */ +/* +#include "../../common.h" +#include "../../sdk.h" + +namespace menu { namespace im { + +// used to determine what var we need to display +enum class EInfo { + AIMBOT, + AIMKEY +}; + +void RenderInfoPanel(); +void AddInfoItem(EInfo info_type, int id); + + +std::string GetBoolString(CatVar* value); +CatVar* GetCatVar(const std::string name); + + + +}}*/ diff --git a/src/gui/im/Playerlist.cpp b/src/gui/im/Playerlist.cpp new file mode 100644 index 00000000..3fa7d176 --- /dev/null +++ b/src/gui/im/Playerlist.cpp @@ -0,0 +1,155 @@ +/* + * Playerlist.cpp + * + * Created on: May 21, 2017 + * Author: nullifiedcat + */ + +#include "Playerlist.hpp" +#include "../../common.h" +#include "../../playerlist.hpp" + +#include "imgui.h" + +namespace menu { namespace im { + +void RenderPlayer(int eid) { + ImGui::PushID(eid); + player_info_s info; + bool success = g_IEngine->GetPlayerInfo(eid, &info); + if (success) { + int x = 0; + // UserID + ImGui::Text("%d", info.userID); + x += 48; + ImGui::SameLine(x); + // SteamID + ImGui::Text("%u", info.friendsID); + x += 80; + ImGui::SameLine(x); + + char safename[32]; + for (int i = 0, j = 0; i < 32; i++) { + if (info.name[i] == 0) { + safename[j] = 0; + break; + } + if (info.name[i] == '\n') continue; + safename[j++] = info.name[i]; + } + + ImGui::Text("%s", safename); + x += 8 * 32; + ImGui::SameLine(x); + + int iclazz = 0; + rgba_t bgcolor = colors::empty; + const char* text = "N/A"; + IF_GAME (IsTF()) { + iclazz = g_pPlayerResource->GetClass(ENTITY(eid)); + int team = g_pPlayerResource->GetTeam(eid); + if (eid != g_IEngine->GetLocalPlayer()) { + if (team == TEAM_RED) { + bgcolor = colors::red; + } else if (team == TEAM_BLU) { + bgcolor = colors::blu; + } + } + if (iclazz && iclazz < 10) { + text = classes[iclazz - 1].c_str(); + } + } + + if (bgcolor.a) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(bgcolor.r, bgcolor.g, bgcolor.b, bgcolor.a)); + } + + ImGui::Text("%s", text); + x += 80; + ImGui::SameLine(x); + + if (bgcolor.a) { + ImGui::PopStyleColor(); + } + + playerlist::userdata& data = playerlist::AccessData(info.friendsID); + int& state = *reinterpret_cast(&data.state); + bgcolor = playerlist::Color(info.friendsID); + if (bgcolor.a) { + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(bgcolor.r, bgcolor.g, bgcolor.b, bgcolor.a)); + } + ImGui::PushItemWidth(120); + ImGui::Combo("", &state, playerlist::k_pszNames, 5); + ImGui::PopItemWidth(); + + x += 124; + + if (bgcolor.a) { + ImGui::PopStyleColor(); + } + + if (backpacktf::enabled()) { + ImGui::SameLine(x); + if (info.fakeplayer) { + ImGui::Text("[BOT]"); + } else if (!info.friendsID) { + ImGui::Text("Unknown"); + } else { + const auto& d = backpacktf::get_data(info.friendsID); + if (d.bad && not d.pending) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); + ImGui::Text("Error"); + } else if (d.pending) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.6f, 0.6f, 0.6f, 1.0f)); + ImGui::Text("Loading"); + } else if (d.no_value) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.0f, 1.0f)); + ImGui::Text("Private?"); + } else if (d.outdated_value) { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.6f, 0.6f, 0.6f, 1.0f)); + ImGui::Text("$%.2f", d.value); + } else { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.0f, 0.8f, 0.0f, 1.0f)); + ImGui::Text("$%.2f", d.value); + } + ImGui::PopStyleColor(); + } + x += 80; + } + ImGui::SameLine(x); + ImGui::PushItemWidth(200.0f); + if (ImGui::ColorEdit3("", data.color)) { + if (!data.color.r && !data.color.b && !data.color.g) { + data.color = colors::empty; + } else { + data.color.a = 255.0f; + } + } + x += 200; + ImGui::PopItemWidth(); + } + ImGui::PopID(); +} + +void RenderPlayerlist() { + if (!g_IEngine->IsInGame()) return; + if (ImGui::Begin("Player List")) { + ImGui::SetWindowSize(ImVec2(0, 0)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 1)); + std::vector teammates {}; + for (int i = 1; i < 32; i++) { + if (!g_Settings.bInvalid && (g_pPlayerResource->GetTeam(i) == LOCAL_E->m_iTeam)) { + teammates.push_back(i); + continue; + } + RenderPlayer(i); + } + for (auto i : teammates) { + RenderPlayer(i); + } + ImGui::PopStyleVar(); + } + ImGui::End(); +} + +}} diff --git a/src/gui/im/Playerlist.hpp b/src/gui/im/Playerlist.hpp new file mode 100644 index 00000000..df42b529 --- /dev/null +++ b/src/gui/im/Playerlist.hpp @@ -0,0 +1,17 @@ +/* + * Playerlist.hpp + * + * Created on: May 21, 2017 + * Author: nullifiedcat + */ + +#ifndef IM_PLAYERLIST_HPP_ +#define IM_PLAYERLIST_HPP_ + +namespace menu { namespace im { + +void RenderPlayerlist(); + +}} + +#endif /* IM_PLAYERLIST_HPP_ */ diff --git a/src/gui/im/Schema.cpp b/src/gui/im/Schema.cpp new file mode 100644 index 00000000..3cbe0c50 --- /dev/null +++ b/src/gui/im/Schema.cpp @@ -0,0 +1,142 @@ +/* + * Schema.cpp + * + * Created on: May 21, 2017 + * Author: nullifiedcat + */ + +#include "Schema.hpp" + + +#include "../../helpers.h" +#include "../../cvwrapper.h" +#include "../../logging.h" + +namespace menu { namespace im { + +CatVar* FindCatVar(const std::string name) { + for (auto var : CatVarList()) { + if (var->name == name) return var; + } + logging::Info("can't find %s", name.c_str()); + throw std::runtime_error("can't find catvar " + name); +} + +ListEntry_Dummy* FromJson(nlohmann::json json) { + if (json.is_string()) { + const std::string var_name = json; + ListEntry_Dummy* cv; + try { + cv = (ListEntry_Dummy*)(new ListEntry_Variable(*FindCatVar(var_name))); + } catch (std::runtime_error& er) { + logging::Info("[Error] %s", er.what()); + cv = (ListEntry_Dummy*)(new ListEntry_Label(format("[", var_name, "]"))); + } + return cv; + } else if (json.is_object()) { +#ifndef IPC_ENABLED + if (json.find("data") != json.end()) { + if (json["data"] == "ipc") { + return nullptr; + } + } +#endif + if (json.find("type") == json.end()) { + logging::Info("[Warning] JSON object has no type!"); + return (ListEntry_Dummy*)(new ListEntry_Label("malformed object")); + } + if (json["type"] == "label") { + std::string label = json["text"]; + return (ListEntry_Dummy*)(new ListEntry_Label(label)); + } else if (json["type"] == "var") { + ListEntry_Variable* cv = new ListEntry_Variable(*FindCatVar(json["var"])); + cv->data = json["data"]; + return (ListEntry_Dummy*)cv; + } else if (json["type"] == "list") { + const auto& list = json["list"]; + ListEntry_List* ll = new ListEntry_List(); + if (json.find("data") != json.end()) { + ll->data = json["data"]; + } + ll->name = json["name"]; + if (!list.is_array()) { + logging::Info("List is not an array!"); + throw std::runtime_error("list is not an array"); + } + for (const auto& item : list) { + auto it = FromJson(item); + if (it) + ll->entries.push_back(std::auto_ptr(it)); + } + return (ListEntry_Dummy*)ll; + } + } + return (ListEntry_Dummy*)(new ListEntry_Label("malformed object")); +} + +void PopulateList(nlohmann::json json) { + try { + if (!json.is_array()) { + throw std::runtime_error("list is not an array"); + } + for (const auto& item : json) { + ListEntry_Dummy* entry = FromJson(item); + if (entry) { + if (entry->type != SUBLIST) { + throw std::runtime_error("main sublist is not a list!"); + } + main_list_array.push_back((ListEntry_List*)entry); + } + } + } catch (std::exception& ex) { + logging::Info("LIST POPULATION FATAL ERROR: %s", ex.what()); + } +} + +std::vector main_list_array; + +std::map map_present {}; + +void TraverseList(const ListEntry_List* list) { + for (const auto& x : list->entries) { + switch (x.get()->type) { + case LABEL: + //logging::Info("Label: %s", ((ListEntry_Label*)(x.get()))->text.c_str()); + break; + case VARIABLE: + map_present[&(((ListEntry_Variable*)(x.get()))->var)] = true; + //logging::Info("Variable: %s", ((ListEntry_Variable*)(x.get()))->var.name.c_str()); + break; + case SUBLIST: + TraverseList((ListEntry_List*)x.get()); + } + } +} + +CatCommand reloadscheme("reloadscheme", "Reload Scheme", []() { + main_list_array.clear(); + try { + std::ifstream in("cathook/menu.json", std::ios::in); + nlohmann::json jo("[]"); + if (in.good()) { + jo = jo.parse(in); + in.close(); + } + PopulateList(jo); + logging::Info("Done populating list.. traversing now!"); + map_present.clear(); + for (const auto& i : main_list_array) { + TraverseList(i); + } + for (const auto& v : CatVarList()) { + if (map_present.find(v) == map_present.end()) { + logging::Info("%s is not present in the GUI!", v->name.c_str()); + } + } + //TraverseList(&main_list); + } catch (std::exception& ex) { + logging::Info("Error: %s", ex.what()); + } +}); + +}} diff --git a/src/gui/im/Schema.hpp b/src/gui/im/Schema.hpp new file mode 100644 index 00000000..2e419e5c --- /dev/null +++ b/src/gui/im/Schema.hpp @@ -0,0 +1,65 @@ +/* + * Schema.hpp + * + * Created on: May 20, 2017 + * Author: nullifiedcat + */ + +#ifndef SCHEMA_HPP_ +#define SCHEMA_HPP_ + +#include "../json.hpp" + +#include "../../beforecheaders.h" +#include +#include +#include +#include "../../aftercheaders.h" + +class CatVar; + +namespace menu { namespace im { + +enum ListEntryType { + DUMMY, + VARIABLE, + SUBLIST, + LABEL +}; + +struct ListEntry_Dummy { + const ListEntryType type { DUMMY }; +}; + +struct ListEntry_Variable { + const ListEntryType type { VARIABLE }; + nlohmann::json data {}; + CatVar& var; + + inline ListEntry_Variable(CatVar& v) : var(v) {} +}; + +struct ListEntry_List { + const ListEntryType type { SUBLIST }; + nlohmann::json data {}; + std::string name; + std::vector> entries {}; + + inline ListEntry_List() {}; +}; + +struct ListEntry_Label { + const ListEntryType type { LABEL }; + std::string text; + + inline ListEntry_Label(const std::string& text) : text(text) {}; +}; + +ListEntry_Dummy* FromJson(nlohmann::json json); +void PopulateList(nlohmann::json json, ListEntry_List* out); + +extern std::vector main_list_array; + +}} + +#endif /* SCHEMA_HPP_ */ diff --git a/src/gui/ncc/Background.cpp b/src/gui/ncc/Background.cpp index ebb2dd98..bad094bb 100644 --- a/src/gui/ncc/Background.cpp +++ b/src/gui/ncc/Background.cpp @@ -5,7 +5,7 @@ * Author: nullifiedcat */ -#include "Menu.hpp" +/*#include "Menu.hpp" namespace menu { namespace ncc { @@ -150,4 +150,4 @@ void Background::Particle::Update(float dt) { if (y > (int)particle_safe + 255) dead = true; } -}} +}}*/ diff --git a/src/gui/ncc/Background.hpp b/src/gui/ncc/Background.hpp index 133c345e..72d66db4 100644 --- a/src/gui/ncc/Background.hpp +++ b/src/gui/ncc/Background.hpp @@ -8,7 +8,7 @@ #ifndef BACKGROUND_HPP_ #define BACKGROUND_HPP_ -#include "Menu.hpp" +/*#include "Menu.hpp" extern unsigned char _binary_snowflake_start; extern unsigned char _binary_flame_start; @@ -52,6 +52,6 @@ public: Particle* list_tail { nullptr }; }; -}} +}}*/ #endif /* BACKGROUND_HPP_ */ diff --git a/src/gui/ncc/CritIndicator.cpp b/src/gui/ncc/CritIndicator.cpp index c69b2ec7..71ce182c 100644 --- a/src/gui/ncc/CritIndicator.cpp +++ b/src/gui/ncc/CritIndicator.cpp @@ -5,7 +5,7 @@ * Author: nullifiedcat */ -#include "CritIndicator.hpp" +/*#include "CritIndicator.hpp" #include "../../common.h" namespace menu { namespace ncc { @@ -72,5 +72,5 @@ void CritIndicator::Update() { } } -}} +}}*/ diff --git a/src/gui/ncc/CritIndicator.hpp b/src/gui/ncc/CritIndicator.hpp index 0907b900..d4473a56 100644 --- a/src/gui/ncc/CritIndicator.hpp +++ b/src/gui/ncc/CritIndicator.hpp @@ -8,7 +8,7 @@ #ifndef CRITINDICATOR_HPP_ #define CRITINDICATOR_HPP_ -#include "Menu.hpp" +/*#include "Menu.hpp" extern unsigned char _binary_crit_1_start; extern unsigned char _binary_crit_2_start; @@ -37,6 +37,6 @@ public: Texture crit_disabled; }; -}} +}}*/ #endif /* CRITINDICATOR_HPP_ */ diff --git a/src/gui/ncc/Item.cpp b/src/gui/ncc/Item.cpp deleted file mode 100644 index f854f14d..00000000 --- a/src/gui/ncc/Item.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Item.cpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#include "Item.hpp" -#include "Menu.hpp" - -#include "../../common.h" - -namespace menu { namespace ncc { - -int Item::size_x = 0; -int Item::size_y = 0; - -Item::Item(std::string name) : CBaseWidget(name, nullptr) { - SetSize(psize_x, psize_y); - SetMaxSize(psize_x, psize_y); -} - -void Item::Draw(int x, int y) { - const auto& size = GetSize(); - //draw::DrawRect(x, y, size.first, size.second, colors::red); - draw::DrawRect(x, y, size.first, size.second, colors::Create(0, 0, 0, 77)); - if (IsHovered()) { - draw::DrawRect(x, y, size.first, size.second, colors::Transparent(GUIColor(), 0.32f)); - } -} - -void Item::HandleCustomEvent(KeyValues* event) { - if (!strcmp(event->GetName(), "scale_update")) { - size_x = psize_x * (float)scale; - size_y = psize_y * (float)scale; - SetSize(size_x, size_y); - SetMaxSize(size_x, size_y); - } -} - -}} diff --git a/src/gui/ncc/Item.hpp b/src/gui/ncc/Item.hpp deleted file mode 100644 index 3621cfa9..00000000 --- a/src/gui/ncc/Item.hpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Item.hpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#ifndef ITEM_HPP_ -#define ITEM_HPP_ - -#include "../CBaseWidget.h" - -namespace menu { namespace ncc { - -class Item : public CBaseWidget { -public: - constexpr static int psize_x = 220; - constexpr static int psize_y = 15; - - static int size_x; - static int size_y; - - Item(std::string name = "ncc_menu_item"); - - virtual void Draw(int x, int y) override; - virtual void HandleCustomEvent(KeyValues* event) override; -}; - -}} - -#endif /* ITEM_HPP_ */ diff --git a/src/gui/ncc/ItemSublist.cpp b/src/gui/ncc/ItemSublist.cpp deleted file mode 100644 index 48ad5bc7..00000000 --- a/src/gui/ncc/ItemSublist.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * ItemSublist.cpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#include "ItemSublist.hpp" -#include "Menu.hpp" - -#include "../../common.h" - -namespace menu { namespace ncc { - -ItemSublist::ItemSublist(std::string title, List* list) : - Item("ncc_item_sublist"), title(title), list(list) { -} - -void ItemSublist::SetParent(IWidget* widget) { - Item::SetParent(widget); - List* listp = dynamic_cast(widget); - if (!listp) throw std::runtime_error("ItemSublist parent isnt List"); - listp->AddChild(list); -} - -bool ItemSublist::IsHovered() { - List* parent = dynamic_cast(GetParent()); - if (!parent) throw std::runtime_error("Sublist parent can't be casted to List!"); - return Item::IsHovered() || (dynamic_cast(parent->open_sublist) == list && !parent->open_sublist->ShouldClose()); -} - -void ItemSublist::Update() { - if (!IsHovered()) { - List* parent = dynamic_cast(GetParent()); - if (!parent) throw std::runtime_error("Sublist parent can't be casted to List!"); - if (dynamic_cast(parent->open_sublist) == list) { - parent->OpenSublist(nullptr, 0); - } - } -} - -void ItemSublist::Draw(int x, int y) { - Item::Draw(x, y); - List* parent = dynamic_cast(GetParent()); - if (!parent) throw std::runtime_error("Sublist parent can't be casted to List!"); - const auto& size = GetSize(); - if (parent->open_sublist == list) - draw::DrawRect(x, y, size.first, size.second, colors::Transparent(GUIColor(), 0.5f)); - draw::String(font_item, x + 2, y, colors::white, 2, format((IsHovered() ? "[-] " : "[+] "), title)); -} - -void ItemSublist::OnKeyPress(ButtonCode_t code, bool repeated) { - Item::OnKeyPress(code, repeated); -} - -void ItemSublist::OnMouseEnter() { - Item::OnMouseEnter(); - List* parent = dynamic_cast(GetParent()); - if (!parent) throw std::runtime_error("Sublist parent can't be casted to List!"); - parent->OpenSublist(list, GetOffset().second - 1); -} - -void ItemSublist::OnMouseLeave() { - Item::OnMouseLeave(); - List* parent = dynamic_cast(GetParent()); - if (!parent) throw std::runtime_error("Sublist parent can't be casted to List!"); - if (dynamic_cast(parent->open_sublist)) { - if (parent->open_sublist->ShouldClose()) { -// parent->OpenSublist(nullptr, 0); - } - } -} - -}} diff --git a/src/gui/ncc/ItemSublist.hpp b/src/gui/ncc/ItemSublist.hpp deleted file mode 100644 index c2461178..00000000 --- a/src/gui/ncc/ItemSublist.hpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * ItemSublist.hpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#ifndef ITEMSUBLIST_HPP_ -#define ITEMSUBLIST_HPP_ - -#include "Item.hpp" -#include "List.hpp" - -class CatVar; - -namespace menu { namespace ncc { - -class List; // ???? - -class ItemSublist : public Item { -public: - ItemSublist(std::string title, List* list); - - virtual void SetParent(IWidget*) override; - virtual bool IsHovered() override; - virtual void Update() override; - virtual void Draw(int x, int y) override; - virtual void OnKeyPress(ButtonCode_t code, bool repeated) override; - virtual void OnMouseEnter(); - virtual void OnMouseLeave(); -public: - List* const list; - const std::string title; -}; - -}} - -#endif /* ITEMSUBLIST_HPP_ */ diff --git a/src/gui/ncc/ItemTitle.cpp b/src/gui/ncc/ItemTitle.cpp deleted file mode 100644 index 6a09420f..00000000 --- a/src/gui/ncc/ItemTitle.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ItemTitle.cpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#include "ItemTitle.hpp" -#include "Menu.hpp" - -#include "../../common.h" - -namespace menu { namespace ncc { - -ItemTitle::ItemTitle(std::string title) : Item("ncc_list_title"), title(title) {} - -void ItemTitle::Draw(int x, int y) { - Item::Draw(x, y); - // nailed it - bool brackets3 = Props()->GetBool("brackets3", false); - std::string str = format(brackets3 ? ">>> " : ">> ", title, brackets3 ? " <<<" : " <<"); - const auto& size = draw::GetStringLength(font_title, str); - draw::String(font_title, x + ((Item::size_x - size.first) / 2), y, colors::white, 2, str); -} - -}} diff --git a/src/gui/ncc/ItemTitle.hpp b/src/gui/ncc/ItemTitle.hpp deleted file mode 100644 index cdb7269d..00000000 --- a/src/gui/ncc/ItemTitle.hpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ItemTitle.hpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#ifndef ITEMTITLE_HPP_ -#define ITEMTITLE_HPP_ - -#include "Item.hpp" - -namespace menu { namespace ncc { - -class ItemTitle : public Item { -public: - ItemTitle(std::string title); - - virtual void Draw(int x, int y) override; -public: - const std::string title; -}; - -}} - -#endif /* ITEMTITLE_HPP_ */ diff --git a/src/gui/ncc/ItemVariable.cpp b/src/gui/ncc/ItemVariable.cpp deleted file mode 100644 index e2931df5..00000000 --- a/src/gui/ncc/ItemVariable.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * ItemVariable.cpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#include "ItemVariable.hpp" -#include "Item.hpp" -#include "../../common.h" - -namespace menu { namespace ncc { - -ItemVariable::ItemVariable(CatVar& variable) : Item("ncc_item_variable_" + variable.name), catvar(variable) { - -} - -void ItemVariable::Update() { - Item::Update(); - if (catvar.desc_long.length() && IsHovered() && catvar.desc_long != "no description") - ShowTooltip(catvar.desc_long); -} - -void ItemVariable::Change(float amount) { - if (!amount) return; - switch (catvar.type) { - case CV_SWITCH: { - catvar = !catvar; - } break; - case CV_ENUM: - case CV_INT: { - catvar = (int)catvar + (int)amount; - if (catvar.restricted && (int)catvar > catvar.max) catvar = (int)catvar.max; - if (catvar.restricted && (int)catvar < catvar.min) catvar = (int)catvar.min; - } break; - case CV_FLOAT: { - catvar = (float)catvar + amount; - if (catvar.restricted && (float)catvar > catvar.max) catvar = (float)catvar.max; - if (catvar.restricted && (float)catvar < catvar.min) catvar = (float)catvar.min; - } break; - } -} - -bool ItemVariable::ConsumesKey(ButtonCode_t key) { - if (capturing) return true; - if (key == ButtonCode_t::MOUSE_WHEEL_DOWN || key == ButtonCode_t::MOUSE_WHEEL_UP || key == ButtonCode_t::MOUSE_FIRST) return true; - return false; -} - -void ItemVariable::OnMousePress() { - if (catvar.type == CV_KEY) - capturing = true; - if (catvar.type == CV_SWITCH) - catvar = !catvar; -} - -void ItemVariable::OnFocusLose() { - capturing = false; -} - -void ItemVariable::OnKeyPress(ButtonCode_t key, bool repeat) { - if (capturing) { - catvar = (int)key; - capturing = false; - return; - } - - float change = 0.0f; - - switch (catvar.type) { - case CV_ENUM: - case CV_SWITCH: - change = 1.0f; break; - case CV_INT: - case CV_FLOAT: { - if (catvar.restricted) { - change = float(catvar.max - catvar.min) / 50.0f; - } else { - change = 1.0f; - } - } - } - - if (change < 1.0f && catvar.type == CV_INT) change = 1.0f; - - if ((catvar.type == CV_SWITCH && key == ButtonCode_t::MOUSE_FIRST) || key == ButtonCode_t::MOUSE_WHEEL_UP) { - Change(change); - } else if (key == ButtonCode_t::MOUSE_WHEEL_DOWN) { - Change(-change); - } -} - -void ItemVariable::Draw(int x, int y) { - Item::Draw(x, y); - std::string val = "[UNDEFINED]"; - switch (catvar.type) { - case CV_SWITCH: { - val = catvar ? "ON" : "OFF"; - } break; - case CV_INT: { - val = std::to_string((int)catvar); - } break; - case CV_FLOAT: { - val = std::to_string((float)catvar); - } break; - case CV_ENUM: { - val = catvar.enum_type->Name((int)catvar); - } break; - case CV_STRING: { - val = std::string(catvar.GetString()); - } break; - case CV_KEY: { - if (capturing) { - val = "[PRESS A KEY]"; - } else { - if (catvar) { - const char* name = g_IInputSystem->ButtonCodeToString((ButtonCode_t)((int)catvar)); - if (name) { - val = std::string(name); - } - } else { - val = "[CLICK TO SET]"; - } - } - } break; - } - draw::String(menu::ncc::font_item, x + 2, y, colors::white, 2, format(catvar.desc_short, ": ", val)); -} - -}} diff --git a/src/gui/ncc/ItemVariable.hpp b/src/gui/ncc/ItemVariable.hpp deleted file mode 100644 index d1f0aeba..00000000 --- a/src/gui/ncc/ItemVariable.hpp +++ /dev/null @@ -1,36 +0,0 @@ -/* - * ItemVariable.hpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#ifndef ITEMVARIABLE_HPP_ -#define ITEMVARIABLE_HPP_ - -#include "Item.hpp" - -class CatVar; - -namespace menu { namespace ncc { - -class ItemVariable : public Item { -public: - ItemVariable(CatVar& variable); - - void Change(float amount); - - virtual void Update() override; - virtual bool ConsumesKey(ButtonCode_t key) override; - virtual void OnMousePress() override; - virtual void OnFocusLose() override; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; - virtual void Draw(int x, int y) override; -public: - CatVar& catvar; - bool capturing { false }; -}; - -}} - -#endif /* ITEMVARIABLE_HPP_ */ diff --git a/src/gui/ncc/List.cpp b/src/gui/ncc/List.cpp deleted file mode 100644 index 17ba89c6..00000000 --- a/src/gui/ncc/List.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* - * List.cpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#include "List.hpp" -#include "Item.hpp" -#include "ItemTitle.hpp" -#include "Menu.hpp" -#include "ItemVariable.hpp" -#include "ItemSublist.hpp" - -#include "../../common.h" - -namespace menu { namespace ncc { - -List::List(std::string title) : open_sublist(nullptr), title(title), got_mouse(false), CBaseContainer("ncc_list") { - AddChild(new ItemTitle(title)); - Hide(); - root_list = this; -} - -List::List() : open_sublist(nullptr), title(""), got_mouse(false), CBaseContainer("ncc_list") { - Hide(); - root_list = this; -} - -void List::Show() { - CBaseContainer::Show(); - got_mouse = false; -} - -void List::FillWithCatVars(std::vector vec) { - for (auto var : vec) { - AddChild(new ItemVariable(*var)); - } -} - -void List::OnKeyPress(ButtonCode_t key, bool repeat) { - if (GetHoveredChild()) GetHoveredChild()->OnKeyPress(key, repeat); -} - -void List::OpenSublist(List* sublist, int dy) { - if (open_sublist) open_sublist->Hide(); - open_sublist = sublist; - if (sublist) { - sublist->SetOffset(Item::size_x + 1, dy); - sublist->Show(); - } -} - -bool List::ShouldClose() { - if (open_sublist) { - if (!open_sublist->ShouldClose()) return false; - } - return !IsHovered() && !got_mouse; -} - -/*IWidget* List::ChildByPoint(int x, int y) { - IWidget* rr = CBaseContainer::ChildByPoint(x, y); - if (rr) return rr; - List* list = dynamic_cast(open_sublist); - if (list) { - auto co = list->GetOffset(); - auto cs = list->GetSize(); - if (x >= co.first && x <= co.first + cs.first && - y >= co.second && y <= co.second + cs.second) { - return list; - } - } - return nullptr; -}*/ - -CatVar* FindCatVar(const std::string name) { - for (auto var : CatVarList()) { - if (var->name == name) return var; - } - logging::Info("can't find %s", name.c_str()); - throw std::runtime_error("can't find catvar " + name); -} -// abc def, ghj, [, fdg sgf saqw rter, ], gs -void FillFromTokens(List* list, const std::vector& tokens) { - list->title = tokens[0]; - list->AddChild(new ItemTitle(tokens[0])); - for (int i = 1; i < tokens.size(); i++) { - const std::string& str = tokens.at(i); - if (i == tokens.size() - 1 || tokens[i + 1] != "[") { - list->AddChild(new ItemVariable(*FindCatVar(str))); - } else { - list->AddChild(new ItemSublist(str, List::FromString(tokens[i + 2]))); - i += 3; - } - } -} - -List* List::FromString(const std::string& string) { - List* result = new List(); - bool readingkey = false; - std::string last_read_key = ""; - std::stringstream readkey(""); - std::vector tokens = {}; - int brackets = 0; - for (const auto& c : string) { - if (c == '[') { - brackets++; - if (brackets == 1) { - tokens.push_back("["); - readkey.str(""); - readkey.clear(); - continue; - } - } else if (c == ']') { - brackets--; - if (!brackets) { - tokens.push_back(readkey.str()); - tokens.push_back("]"); - readkey.str(""); - readkey.clear(); - continue; - } - } - if (!brackets) { - if (c == '"') { - readingkey = !readingkey; - if (!readingkey) { - tokens.push_back(readkey.str()); - readkey.str(""); - readkey.clear(); - } - } else { - if (readingkey) readkey << c; - } - } else { - readkey << c; - } - } - FillFromTokens(result, tokens); - logging::Info("done making list %s - has %i children.", result->title.c_str(), result->ChildCount()); - return result; -} - -void List::FillWithCatVars(std::vector vec) { - for (const auto& string : vec) { - AddChild(new ItemVariable(*FindCatVar(string))); - } -} - -void List::OnMouseLeave() { - CBaseContainer::OnMouseLeave(); - if (ShouldClose()) { - List* parent_list = dynamic_cast(GetParent()); - if (parent_list) { - parent_list->OpenSublist(nullptr, 0); - } - } -} - -void List::Draw(int x, int y) { - //const auto& size = GetSize(); - draw::OutlineRect(x, y, 2 + Item::size_x, Props()->GetInt("items") * Item::size_y + 2, GUIColor()); - for (int i = 1; i < Props()->GetInt("items"); i++) { - draw::DrawLine(x + 1, y + Item::size_y * i, Item::size_x, 0, GUIColor()); - } - //CBaseContainer::Draw(x, y); - for (int i = 0; i < ChildCount(); i++) { - Item* item = dynamic_cast(ChildByIndex(i)); - if (!item) { - if (ChildByIndex(i)->GetName().find("ncc_list") == 0) continue; - throw std::runtime_error("Invalid cast in NCC-List:Draw!"); - } - const auto& offset = item->GetOffset(); - item->Draw(x + offset.first, y + offset.second); - } - if (dynamic_cast(open_sublist)) { - const auto& offset = open_sublist->GetOffset(); - open_sublist->Draw(x + offset.first, y + offset.second); - } -} - -void List::OnMouseEnter() { - CBaseContainer::OnMouseEnter(); - got_mouse = true; -} - -void List::SetParent(IWidget* parent) { - CBaseContainer::SetParent(parent); - List* parent_list = dynamic_cast(parent); - if (parent_list) { - root_list = parent_list->root_list; - } else root_list = this; -} - -void List::Update() { - CBaseContainer::Update(); - if (IsPressed() && root_list == this) { - const auto& offset = root_list->GetOffset(); - root_list->SetOffset(offset.first + g_pGUI->mouse_dx, offset.second + g_pGUI->mouse_dy); - } -} - -void List::MoveChildren() { - int accy = 2; - int j = 0; - for (int i = 0; i < ChildCount(); i++) { - Item* item = dynamic_cast(ChildByIndex(i)); - if (!item) { - if (ChildByIndex(i)->GetName().find("ncc_list") == 0) continue; - throw std::runtime_error("Invalid cast in NCC-List:MoveChildren! Offender " + ChildByIndex(i)->GetName()); - } - item->SetOffset(1, j * Item::size_y + 1); - accy += Item::size_y; - j++; - } - Props()->SetInt("items", j); - List* list = dynamic_cast(open_sublist); - if (list) { - const auto& size = list->GetSize(); - const auto& offset = list->GetOffset(); - SetSize(Item::size_x + 2 + size.first, max(accy, offset.second + size.second)); - } else { - SetSize(Item::size_x + 2, accy); - } -} - -}} diff --git a/src/gui/ncc/List.hpp b/src/gui/ncc/List.hpp deleted file mode 100644 index e50bc6e2..00000000 --- a/src/gui/ncc/List.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/* - * List.hpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#ifndef LIST_HPP_ -#define LIST_HPP_ - -#include "../CBaseContainer.h" -#include "../../common.h" - -class Item; - -namespace menu { namespace ncc { - -class List : public CBaseContainer { -public: - List(std::string title); - List(); - - void FillWithCatVars(std::vector vec); - void FillWithCatVars(std::vector vec); - void OpenSublist(List* sublist, int dy); - bool ShouldClose(); - - static List* FromString(const std::string& string); - - //virtual IWidget* ChildByPoint(int x, int y) override; - inline virtual void SortByZIndex() override {}; - virtual void Show() override; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; - virtual void OnMouseEnter() override; - virtual void OnMouseLeave() override; - virtual void Draw(int x, int y) override; - virtual void Update() override; - virtual void MoveChildren() override; - virtual void SetParent(IWidget* parent) override; -public: - List* root_list { nullptr }; - bool got_mouse { false }; - List* open_sublist { nullptr }; - std::string title; -}; - -}} - -#endif /* LIST_HPP_ */ diff --git a/src/gui/ncc/Logo.cpp b/src/gui/ncc/Logo.cpp deleted file mode 100644 index 1053528c..00000000 --- a/src/gui/ncc/Logo.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Logo.cpp - * - * Created on: Apr 28, 2017 - * Author: nullifiedcat - */ - -#include "Menu.hpp" - -namespace menu { namespace ncc { - -static CatEnum logo_enum({"NEVER", "MENU", "ALWAYS"}); -CatVar logo(logo_enum, "logo", "1", "Show logo", "Show cathook logo when"); - -Logo::Logo() : CBaseWidget("nc_logo"), texture(&_binary_logo_start, 576, 288) { - SetSize(576, 288); -} - -bool Logo::AlwaysVisible() { - return (int)logo == 2; -} - -void Logo::Draw(int x, int y) { - if (logo) { - if (!texture.id) texture.Load(); - texture.Draw(x, y, 576, 288, GUIColor()); - } -} - -void Logo::Update() { - if (IsPressed()) { - auto offset = GetOffset(); - offset.first += g_pGUI->mouse_dx; - offset.second += g_pGUI->mouse_dy; - SetOffset(offset.first, offset.second); - } -} - -}} diff --git a/src/gui/ncc/Logo.hpp b/src/gui/ncc/Logo.hpp deleted file mode 100644 index c4e6c9a3..00000000 --- a/src/gui/ncc/Logo.hpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Logo.hpp - * - * Created on: Apr 28, 2017 - * Author: nullifiedcat - */ - -#ifndef LOGO_HPP_ -#define LOGO_HPP_ - -#include "Menu.hpp" - -extern unsigned char _binary_logo_start; - -namespace menu { namespace ncc { - -class Logo : public CBaseWidget { -public: - Logo(); - virtual bool AlwaysVisible() override; - virtual void Draw(int x, int y) override; - virtual void Update() override; - Texture texture; -}; - -}} - -#endif /* LOGO_HPP_ */ diff --git a/src/gui/ncc/Menu.cpp b/src/gui/ncc/Menu.cpp deleted file mode 100644 index c52741ab..00000000 --- a/src/gui/ncc/Menu.cpp +++ /dev/null @@ -1,633 +0,0 @@ -/* - * Menu.cpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#include "../../common.h" - -#include "Menu.hpp" -#include "List.hpp" -#include "ItemSublist.hpp" -#include "Tooltip.hpp" - -namespace menu { namespace ncc { - -unsigned long font_title = 0; -unsigned long font_item = 0; - -CatVar scale(CV_FLOAT, "gui_ncc_scale", "1", "NCC GUI Scale", "Defines scale of NCC gui", 0.5f, 4.0f); -CatVar font_family(fonts::family_enum, "gui_ncc_font_family", "3", "NCC Font Family", "Defines font family for NCC menu"); -CatVar font_title_family(fonts::family_enum, "gui_ncc_font_title_family", "4", "NCC Title Family", "Defines font family for NCC menu titles"); - -Tooltip* tooltip = nullptr;; -Root* root = nullptr; - -void ShowTooltip(const std::string& text) { - tooltip->Show(); - tooltip->SetText(text); -} - -std::vector FindCatVars(const std::string name) { - std::vector result = {}; - for (auto var : CatVarList()) { - if (var->name.find(name) == 0) result.push_back(var); - } - return result; -} - -bool init_done = false; - -void ChangeCallback(IConVar* var, const char* pszOldValue, float flOldValue) { - if (init_done) - RefreshFonts(); -} - -void Init() { - root = new Root(); - root->Setup(); - scale.InstallChangeCallback([](IConVar* var, const char* pszOldValue, float flOldValue) { - if (init_done) RefreshFonts(); - logging::Info("Scale Changed"); - root->HandleCustomEvent(KeyValues::AutoDelete("scale_update")); - }); - font_family.InstallChangeCallback(ChangeCallback); - font_title_family.InstallChangeCallback(ChangeCallback); - init_done = true; - RefreshFonts(); -} - -void RefreshFonts() { - font_title = g_ISurface->CreateFont(); - font_item = g_ISurface->CreateFont(); - g_ISurface->SetFontGlyphSet(font_title, fonts::fonts.at(_clamp(0, (int)(fonts::fonts.size() - 1), (int)font_title_family)).c_str(), psize_font_title * (float)scale, 0, 0, 0, 0x0); - g_ISurface->SetFontGlyphSet(font_item, fonts::fonts.at(_clamp(0, (int)(fonts::fonts.size() - 1), (int)font_family)).c_str(), psize_font_item * (float)scale, 0, 0, 0, 0x0); - root->HandleCustomEvent(KeyValues::AutoDelete("font_update")); -} - -static const std::string list_hl2dm = R"( -"Cat Hook" -"Aim Bot" [ - "Aim Bot Menu" - "aimbot_enabled" - "aimbot_aimkey" - "aimbot_aimkey_mode" - "aimbot_autoshoot" - "aimbot_hitboxmode" - "aimbot_fov" - "aimbot_prioritymode" - "aimbot_charge" - "aimbot_teammates" - "Preferences" [ - "Aim Bot Preferences" - "aimbot_silent" - "aimbot_hitbox" - "aimbot_only_when_can_shoot" - "aimbot_enable_attack_only" - "aimbot_maxrange" - "aimbot_interp" - "aimbot_slow" - "aimbot_slow_smooth" - "aimbot_slow_autoshoot" - ] -] - -"Trigger Bot" [ - "Trigger Bot Menu" - "trigger_enabled" - "trigger_accuracy" - "trigger_range" - "trigger_hitbox" -] - - - -"Visuals" [ - "Visuals Menu" - "ESP" [ - "ESP Menu" - "esp_enabled" - "font_esp_family" - "font_esp_height" - "esp_name" - "esp_distance" - "esp_box" - "esp_box_text_position" - "esp_box_nodraw" - "esp_box_expand" - "3D Box" [ - "3D Box Settings" - "esp_3d_box" - "esp_3d_box_thick" - "esp_3d_box_health" - "esp_3d_box_expand" - "esp_3d_box_smoothing" - "esp_3d_box_expand_size" - "esp_3d_box_healthbar" - ] - "esp_legit" - "esp_health_num" - "esp_weapon_spawners" - "esp_model_name" - "esp_weapon" - "esp_vischeck" - "esp_entity_id" - "esp_followbot_id" - "esp_teammates" - "esp_entity" - "esp_local" - "Items" [ - "Item ESP Menu" - "esp_item" - "esp_item_adrenaline" - "esp_item_powerups" - "esp_item_health" - "esp_item_ammo" - "esp_item_weapons" - ] - ] - "Chams" [ - "Chams Menu" - "chams_enable" - "chams_health" - "chams_players" - "chams_teammates" - "chams_flat" - "chams_weapons" - "chams_medkits" - "chams_ammo" - ] - - "Glow" [ - "Glow Menu" - "glow_enable" - "glow_solid_when" - "glow_blur_scale" - "glow_health" - "glow_players" - "glow_teammates" - "glow_medkits" - "glow_ammo" - ] - "GUI" [ - "GUI Settings" - "logo" - "gui_bg_particles" - "gui_bg_particles_type" - "gui_bg_particles_chance" - "gui_bg_particles_pack_size" - "gui_bg_particles_safe_zone" - "gui_bg_particles_gravity" - "gui_bg_particles_jittering" - "gui_bg_particles_jittering_chance" - "gui_bg_particles_wind" - "gui_bg_visible" - "gui_color_b" - "gui_color_g" - "gui_color_r" - "gui_rainbow" - "fast_outline" - "gui_bounds" - "gui_visible" - ] - "Miscellaneous" [ - "Miscellaneous" - "pure_bypass" - "no_arms" - "fov" - "clean_screenshots" - "logo" - ] -] - -"Anti-/Anti-Aim" [ - "Anti-Aim Menu" - "aa_enabled" - "aa_pitch" - "aa_pitch_mode" - "aa_yaw" - "aa_yaw_mode" - "aa_spin" - "aa_roll" - "aa_no_clamp" - "resolver" - "Anti-Anti-Anti-Aim" [ - "Anti-Anti-Anti-Aim Menu" - "aa_aaaa_enabled" - "aa_aaaa_interval" - "aa_aaaa_interval_low" - "aa_aaaa_interval_high" - "aa_aaaa_mode" - "aa_aaaa_flip_key" - ] -] - -"Chat" [ - "Chat Options Menu" - "chat_newlines" - "clean_chat" - "killsay" - "spam" - "spam_random" -] - -"Follow Bot" [ - "Follow Bot Settings" - "fb_bot" - "fb_mimic_slot" - "fb_always_medigun" - "fb_autoclass" - "fb_follow_distance" -] - -"Miscellaneous" [ - "Miscellaneous Settings" - "bhop_enabled" - "fast_vischeck" - "anti_afk" - "rollspeedhack" - "info" - "Debug" [ - "Debug Menu" - "software_cursor_mode" - "enabled" - "no_visuals" - "debug_info" - "log" - ] -] -)"; - -static const std::string list_tf2 = R"( -"Cat Hook" -"Aim Bot" [ - "Aim Bot Menu" - "aimbot_enabled" - "aimbot_aimkey" - "aimbot_aimkey_mode" - "aimbot_autoshoot" - "aimbot_hitboxmode" - "aimbot_fov" - "aimbot_prioritymode" - "aimbot_charge" - "Ignore" [ - "Ignore/Respect Menu" - "aimbot_respect_vaccinator" - "ignore_taunting" - "aimbot_ignore_hoovy" - "aimbot_respect_cloak" - "aimbot_buildings" - "aimbot_teammates" - ] - "Auto Heal" [ - "Auto Heal Menu" - "autoheal_enabled" - "autoheal_uber" - "autoheal_uber_health" - "autoheal_silent" - "autoheal_share_uber" - ] - "Preferences" [ - "Aim Bot Preferences" - "aimbot_silent" - "aimbot_hitbox" - "aimbot_zoomed" - "aimbot_only_when_can_shoot" - "aimbot_enable_attack_only" - "aimbot_maxrange" - "aimbot_interp" - "aimbot_engine_pred" - "aimbot_instant_rezoom_enabled" - "aimbot_slow" - "aimbot_slow_smooth" - "aimbot_slow_autoshoot" - "Projectile Aimbot" [ - "Projectile Aimbot Tweaks" - "aimbot_projectile" - "aimbot_proj_fovpred" - "aimbot_proj_vispred" - "aimbot_proj_gravity" - "aimbot_proj_speed" - "aimbot_huntsman_charge" - "aimbot_full_auto_huntsman" - ] - ] -] - -"Trigger Bot" [ - "Trigger Bot Menu" - "trigger_enabled" - "autobackstab" - "Auto Vaccinator" [ - "Auto Vaccinator" - "auto_vacc" - "auto_vacc_reset_timer" - "auto_vacc_default_resist" - "auto_vacc_bullets" - "auto_vacc_blast" - "auto_vacc_fire" - "auto_vacc_sniper_pop" - "auto_vacc_blast_pop_health" - "auto_vacc_blast_pop_crit" - "auto_vacc_rocket_range" - "auto_vacc_fire_pop_pyro" - "auto_vacc_afterburn" - "auto_vacc_pyro_range" - "auto_vacc_bullet_pop_ubers" - "auto_vacc_blast_pop_ubers" - "auto_vacc_fire_pop_ubers" - ] - "Auto Sticky" [ - "Auto Sticky Menu" - "sticky_enabled" - "sticky_distance" - "sticky_buildings" - "sticky_visable" - ] - "Auto Reflect" [ - "Auto Reflect Menu" - "reflect_enabled" - "reflect_distance" - "reflect_stickybombs" - "reflect_only_idle" - ] - "Triggerbot Ignores" [ - "Ignore/Respect Menu" - "trigger_respect_vaccinator" - "trigger_respect_cloak" - "trigger_buildings" - ] - "Triggerbot Preferences" [ - "Triggerbot Preferences" - "trigger_accuracy" - "trigger_ambassador" - "trigger_range" - "trigger_finish" - "trigger_bodyshot" - "trigger_hitbox" - "trigger_zoomed" - ] -] - - - -"Visuals" [ - "Visuals Menu" - "ESP" [ - "ESP Menu" - "esp_enabled" - "font_esp_family" - "font_esp_height" - "esp_conds" - "esp_class" - "esp_name" - "esp_distance" - "esp_ubercharge" - "esp_box" - "esp_box_text_position" - "esp_box_nodraw" - "esp_box_expand" - "3D Box" [ - "3D Box Settings" - "esp_3d_box" - "esp_3d_box_thick" - "esp_3d_box_health" - "esp_3d_box_expand" - "esp_3d_box_smoothing" - "esp_3d_box_expand_size" - "esp_3d_box_healthbar" - ] - "esp_legit" - "esp_health_num" - "esp_weapon_spawners" - "esp_model_name" - "esp_weapon" - "esp_vischeck" - "esp_show_tank" - "esp_entity_id" - "esp_followbot_id" - "esp_teammates" - "esp_entity" - "esp_buildings" - "esp_local" - "Items" [ - "Item ESP Menu" - "esp_item" - "esp_item_adrenaline" - "esp_item_powerups" - "esp_item_health" - "esp_item_ammo" - "esp_item_weapons" - "esp_money_red" - "esp_money" - ] - "Projectiles" [ - "Projectile ESP Menu" - "esp_proj" - "esp_proj_enemy" - "esp_proj_stickies" - "esp_proj_pipes" - "esp_proj_arrows" - "esp_proj_rockets" - ] - ] - "Radar" [ - "Radar Menu" - "radar" - "radar_size" - "radar_zoom" - "radar_health" - "radar_enemies_top" - "radar_icon_size" - "radar_x" - "radar_y" - ] - "Chams" [ - "Chams Menu" - "chams_enable" - "chams_health" - "chams_players" - "chams_teammates" - "chams_buildings" - "chams_teammate_buildings" - "chams_flat" - "chams_weapons" - "chams_medkits" - "chams_ammo" - "chams_stickies" - ] - - "Glow" [ - "Glow Menu" - "glow_enable" - "glow_solid_when" - "glow_blur_scale" - "glow_health" - "glow_players" - "glow_teammates" - "glow_buildings" - "glow_teammate_buildings" - "glow_medkits" - "glow_ammo" - "glow_stickies" - ] - - "TF2 Glow Outline" [ - "TF2 Glow Menu" - "glow_old_enabled" - "glow_old_players" - "glow_old_color_scheme" - "glow_old_health_packs" - "glow_old_ammo_boxes" - "glow_old_alpha" - "glow_old_teammates" - "glow_old_teammate_buildings" - "glow_old_buildings" - "glow_old_stickies" - ] - "GUI" [ - "GUI Settings" - "logo" - "gui_bg_particles" - "gui_bg_particles_type" - "gui_bg_particles_chance" - "gui_bg_particles_pack_size" - "gui_bg_particles_safe_zone" - "gui_bg_particles_gravity" - "gui_bg_particles_jittering" - "gui_bg_particles_jittering_chance" - "gui_bg_particles_wind" - "gui_bg_visible" - "gui_color_b" - "gui_color_g" - "gui_color_r" - "gui_rainbow" - "fast_outline" - "gui_bounds" - "gui_visible" - ] - "Miscellaneous" [ - "Miscellaneous" - "pure_bypass" - "antidisguise" - "no_arms" - "no_hats" - "thirdperson" - "thirdperson_angles" - "render_zoomed" - "fov" - "fov_zoomed" - "no_zoom" - "clean_screenshots" - "logo" - ] -] - -"Anti-/Anti-Aim" [ - "Anti-Aim Menu" - "aa_enabled" - "aa_pitch" - "aa_pitch_mode" - "aa_yaw" - "aa_yaw_mode" - "aa_spin" - "aa_roll" - "aa_no_clamp" - "resolver" - "Anti-Anti-Anti-Aim" [ - "Anti-Anti-Anti-Aim Menu" - "aa_aaaa_enabled" - "aa_aaaa_interval" - "aa_aaaa_interval_low" - "aa_aaaa_interval_high" - "aa_aaaa_mode" - "aa_aaaa_flip_key" - ] -] - -"Crit Hack" [ - "Crit Hack Menu" - "crit_info" - "crit_hack_next" - "crit_hack" - "crit_suppress" - "crit_melee" - "crit_hack_experimental" -] - -"Chat" [ - "Chat Options Menu" - "chat_newlines" - "clean_chat" - "killsay" - "spam" - "spam_random" - "spam_teamname" - "uberspam" - "uberspam_build" - "uberspam_ready" - "uberspam_used" - "uberspam_ended" - "uberspam_team" -] - -"Follow Bot" [ - "Follow Bot Settings" - "fb_bot" - "fb_mimic_slot" - "fb_always_medigun" - "fb_autoclass" - "fb_follow_distance" -] - -"Miscellaneous" [ - "Miscellaneous Settings" - "removecond_master" - "removecond_value" - "removecond_key" - "removecond_fire" - "removecond_taunt" - "removecond_bleeding" - "removecond_stun" - "spycrab" - "Spy Alert" [ - "Spy Alert Settings" - "spyalert_enabled" - "spyalert_warning" - "spyalert_backstab" - "spyalert_sound" - "spyalert_interval" - ] - "Anti Backstab" [ - "Anti Backstab Menu" - "antibackstab" - "antibackstab_nope" - "antibackstab_angle" - "antibackstab_distance" - "antibackstab_silent" - ] - "bhop_enabled" - "noisemaker" - "nopush_enabled" - "fast_vischeck" - "anti_afk" - "rollspeedhack" - "info" - "Debug" [ - "Debug Menu" - "software_cursor_mode" - "enabled" - "no_visuals" - "debug_info" - "log" - ] -] -)"; - -List& MainList() { - static List* main = List::FromString(IsTF2() ? list_tf2 : list_hl2dm); - return *main; -} - -}} diff --git a/src/gui/ncc/Menu.hpp b/src/gui/ncc/Menu.hpp deleted file mode 100644 index 46dff553..00000000 --- a/src/gui/ncc/Menu.hpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Menu.hpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#ifndef MENU_HPP_ -#define MENU_HPP_ - -#include "../../drawing.h" - -#include "../guicommon.h" - -#include "List.hpp" -#include "Item.hpp" -#include "ItemSublist.hpp" -#include "ItemTitle.hpp" -#include "ItemVariable.hpp" -#include "List.hpp" -#include "PlayerList.hpp" -#include "PlayerListEntry.hpp" -#include "Radar.hpp" -#include "Root.hpp" -#include "Tooltip.hpp" -#include "Background.hpp" -#include "CritIndicator.hpp" -#include "Logo.hpp" - -namespace menu { namespace ncc { - -class List; -class Tooltip; - -extern CatVar scale; -extern CatVar font_family; -extern CatVar font_title_family; - -constexpr int psize_font_item = 12; -constexpr int psize_font_title = 14; - -extern unsigned long font_title; // Verdana Bold 10px? -extern unsigned long font_item; // Verdana 10px? - -extern Tooltip* tooltip; -extern Root* root; - -void RefreshFonts(); -void ShowTooltip(const std::string& text); - -void Init(); -List& MainList(); - -}} - -#endif /* MENU_HPP_ */ diff --git a/src/gui/ncc/PlayerList.cpp b/src/gui/ncc/PlayerList.cpp deleted file mode 100644 index bc542e56..00000000 --- a/src/gui/ncc/PlayerList.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * PlayerList.cpp - * - * Created on: Apr 11, 2017 - * Author: nullifiedcat - */ - -#include "Menu.hpp" - -namespace menu { namespace ncc { - -int size_table_width() { - int accum = 1; - for (int i = 0; i < sizeof(size_table) / sizeof(int); i++) { - accum += (size_table[i] + 1) * (float)scale; - } - return accum; -} - -PlayerList::PlayerList() : CBaseContainer() { - for (int i = 0; i <= 32; i++) { - AddChild(new PlayerListEntry(i)); - } -} - -bool PlayerList::IsVisible() { - return !g_Settings.bInvalid; -} - -void PlayerList::Draw(int x, int y) { - if (g_Settings.bInvalid) return; - const auto& size = GetSize(); - draw::DrawRect(x, y, size.first, size.second, colors::Create(0, 0, 0, 77)); - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - for (int i = 0; i < Props()->GetInt("vischildren"); i++) { - draw::DrawLine(x, y + i * (Item::size_y + 2), size_table_width(), 0, GUIColor()); - } - int accum = 0; - for (int i = 0; i < sizeof(size_table) / sizeof(int); i++) { - draw::DrawLine(x + accum, y, 0, size.second, GUIColor()); - accum += (size_table[i] + 1) * (float)scale; - } - CBaseContainer::Draw(x, y); -} - -void PlayerList::OnKeyPress(ButtonCode_t key, bool repeat) { - if (GetHoveredChild()) GetHoveredChild()->OnKeyPress(key, repeat); -} - -void PlayerList::Update() { - if (g_Settings.bInvalid) return; - if (IsPressed()) { - auto offset = GetOffset(); - offset.first += g_pGUI->mouse_dx; - offset.second += g_pGUI->mouse_dy; - SetOffset(offset.first, offset.second); - } - CBaseContainer::Update(); -} - -void PlayerList::MoveChildren() { - int visible = 0; - for (int i = 0; i < ChildCount(); i++) { - ChildByIndex(i)->SetOffset(0, 1 + visible * (Item::size_y + 2)); - if (ChildByIndex(i)->IsVisible()) visible++; - } - SetSize(size_table_width(), visible * (Item::size_y + 2) + 1); - Props()->SetInt("vischildren", visible); -} - -}} diff --git a/src/gui/ncc/PlayerList.hpp b/src/gui/ncc/PlayerList.hpp deleted file mode 100644 index 2a6ef6ce..00000000 --- a/src/gui/ncc/PlayerList.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/* - * PlayerList.hpp - * - * Created on: Apr 11, 2017 - * Author: nullifiedcat - */ - -#ifndef GUI_NCC_PLAYERLIST_HPP_ -#define GUI_NCC_PLAYERLIST_HPP_ - -#include "../CBaseContainer.h" -#include "Menu.hpp" - -namespace menu { namespace ncc { - -constexpr int size_table[] = { 32, 32, 80, 160, 80, 80, 32, 32, 32 }; -int size_table_width(); - -class PlayerList : public CBaseContainer { -public: - PlayerList(); - - virtual void Draw(int x, int y) override; - virtual void Update() override; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; - virtual void MoveChildren() override; - virtual bool IsVisible() override; - inline virtual void SortByZIndex() override {}; -}; - -}} - -#endif /* GUI_NCC_PLAYERLIST_HPP_ */ diff --git a/src/gui/ncc/PlayerListEntry.cpp b/src/gui/ncc/PlayerListEntry.cpp deleted file mode 100644 index eb2de3ef..00000000 --- a/src/gui/ncc/PlayerListEntry.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* - * PlayerListEntry.cpp - * - * Created on: Apr 21, 2017 - * Author: nullifiedcat - */ - -#include "PlayerListEntry.hpp" -#include "../../helpers.h" - -namespace menu { namespace ncc { - -using namespace entrysubs; - -void PlayerListEntry::Draw(int x, int y) { - CBaseContainer::Draw(x, y); -} - -void PlayerListEntry::Update() { - if (idx) { - SubBase* uid = dynamic_cast(ChildByIndex(1)); - SubBase* steamid = dynamic_cast(ChildByIndex(2)); - SubBase* name = dynamic_cast(ChildByIndex(3)); - SubBase* clazz = dynamic_cast(ChildByIndex(4)); - if (uid && steamid && name && clazz) { - player_info_s info; - bool success = g_IEngine->GetPlayerInfo(idx, &info); - if (success) { - uid->text = format(info.userID); - steamid->text = format(info.friendsID); - char safename[32]; - for (int i = 0, j = 0; i < 32; i++) { - if (info.name[i] == 0) { - safename[j] = 0; - break; - } - if (info.name[i] == '\n') continue; - safename[j++] = info.name[i]; - } - name->text = format(safename); - int iclazz = 0; - IF_GAME (IsTF()) iclazz = g_pPlayerResource->GetClass(ENTITY(idx)); - int team = g_pPlayerResource->GetTeam(idx); - clazz->color_bg = 0; - if (idx != g_IEngine->GetLocalPlayer()) { - if (team == TEAM_RED) { - clazz->color_bg = colors::red; - } else if (team == TEAM_BLU) { - clazz->color_bg = colors::blu; - } - } - if (iclazz && iclazz < 10) { - clazz->text = classes[iclazz - 1]; - } else { - clazz->text = "N/A"; - } - Show(); - } else { - uid->text = "N/A"; - steamid->text = "N/A"; - name->text = "N/A"; - clazz->text = "N/A"; - Hide(); - } - } else { - Hide(); - } - } - CBaseContainer::Update(); -} - -void PlayerListEntry::MoveChildren() { - int it = 1; - for (int i = 0; i < ChildCount() && i < (sizeof(size_table) / sizeof(int)); i++) { - IWidget* child = ChildByIndex(i); - child->SetOffset(it, 0); - child->SetSize(size_table[i] * (float)scale, Item::size_y + 1); - it += (size_table[i] + 1) * (float)scale; - } - SetSize(it, Item::size_y + 1); -} - -void PlayerListEntry::OnKeyPress(ButtonCode_t key, bool repeat) { - if (GetHoveredChild()) GetHoveredChild()->OnKeyPress(key, repeat); -} - -PlayerListEntry::PlayerListEntry(int eid) : CBaseContainer(), idx(eid) { - // If IDX == 0, this is a title. - if (!idx) { - AddChild(new SubTitle(*this, "EID")); - AddChild(new SubTitle(*this, "UID")); - AddChild(new SubTitle(*this, "SteamID")); - AddChild(new SubTitle(*this, "Name")); - AddChild(new SubTitle(*this, "Class")); - AddChild(new SubTitle(*this, "State")); - AddChild(new SubTitle(*this, "R")); - AddChild(new SubTitle(*this, "G")); - AddChild(new SubTitle(*this, "B")); - Show(); - } else { - Hide(); - SubBase* eid = new SubBase(*this); - eid->text = format(idx); - AddChild(eid); // EID - AddChild(new SubBase(*this)); // UID - AddChild(new SubBase(*this)); // SteamID - AddChild(new SubBase(*this)); // Name - AddChild(new SubBase(*this)); // Class - AddChild(new SubState(*this)); - AddChild(new SubColorComponent(*this, SubColorComponent::Component::R)); - AddChild(new SubColorComponent(*this, SubColorComponent::Component::G)); - AddChild(new SubColorComponent(*this, SubColorComponent::Component::B)); - } -} - -SubBase::SubBase(PlayerListEntry& base) : parent(base), CBaseWidget() {} - -void SubBase::Draw(int x, int y) { - if (color_bg) { - const auto& size = GetSize(); - draw::DrawRect(x, y, size.first, size.second, color_bg); - } - draw::String(menu::ncc::font_item, x + 2, y + 2, color_fg ? color_fg : colors::white, 2, text); -} - -SubTitle::SubTitle(PlayerListEntry& parent, const std::string& title) : SubBase(parent) { - text = title; -} - -void SubTitle::Draw(int x, int y) { - draw::String(menu::ncc::font_title, x + 2, y + 2, colors::white, 2, text); -} - -SubColorComponent::SubColorComponent(PlayerListEntry& parent, Component component) : SubBase(parent), component(component) {} - -void SubColorComponent::Update() { - player_info_s info; - bool success = g_IEngine->GetPlayerInfo(parent.idx, &info); - if (success) { - playerlist::userdata& data = playerlist::AccessData(info.friendsID); - color_bg = data.color; - } else { - color_bg = 0; - } - text = format((int)(reinterpret_cast(&color_bg)[static_cast(component)])); -} - -bool SubColorComponent::ConsumesKey(ButtonCode_t key) { - return key == MOUSE_WHEEL_DOWN || key == MOUSE_WHEEL_UP; -} -void SubColorComponent::OnKeyPress(ButtonCode_t key, bool repeat) { - player_info_s info; - bool success = g_IEngine->GetPlayerInfo(parent.idx, &info); - if (!success) return; - playerlist::userdata& data = playerlist::AccessData(info.friendsID); - int change = 0; - if (key == MOUSE_WHEEL_UP) { - if (g_IInputSystem->IsButtonDown(KEY_LSHIFT)) { - change = 50; - } else if (g_IInputSystem->IsButtonDown(KEY_LCONTROL)) { - change = 10; - } else { - change = 1; - } - } else if (key == MOUSE_WHEEL_DOWN) { - if (g_IInputSystem->IsButtonDown(KEY_LSHIFT)) { - change = -50; - } else if (g_IInputSystem->IsButtonDown(KEY_LCONTROL)) { - change = -10; - } else { - change = -1; - } - } - int result = _clamp(0, 255, (int)(reinterpret_cast(&data.color)[static_cast(component)]) + change); - (reinterpret_cast(&data.color)[static_cast(component)]) = (unsigned char)result; - if (!(data.color & 0x00FFFFFF)) { - data.color = 0; - } else { - data.color |= 0xFF000000; - } -} - -void SubState::Update() { - player_info_s info; - bool success = g_IEngine->GetPlayerInfo(parent.idx, &info); - if (!success) { - text = "N/A"; - return; - } - playerlist::userdata& data = playerlist::AccessData(info.friendsID); - if (parent.idx == g_IEngine->GetLocalPlayer()) { - text = "Local Player"; - return; - } - const int state = static_cast(data.state); - color_bg = playerlist::Color(info.friendsID); - if (state >= 0 && state <= static_cast(playerlist::k_EState::STATE_LAST)) { - text = playerlist::k_Names[state]; - } else { - text = "N/A"; - } -} - -bool SubState::ConsumesKey(ButtonCode_t key) { - return key == MOUSE_WHEEL_DOWN || key == MOUSE_WHEEL_UP; -} -void SubState::OnKeyPress(ButtonCode_t key, bool repeat) { - if (parent.idx == g_IEngine->GetLocalPlayer()) return; - player_info_s info; - bool success = g_IEngine->GetPlayerInfo(parent.idx, &info); - if (!success) return; - playerlist::userdata& data = playerlist::AccessData(info.friendsID); - int state = static_cast(data.state); - int change = 0; - if (key == MOUSE_WHEEL_UP) { - change = 1; - } else if (key == MOUSE_WHEEL_DOWN) { - change = -1; - } - int result = _clamp(0, static_cast(playerlist::k_EState::STATE_LAST), state + change); - data.state = static_cast(result); -} - -}} diff --git a/src/gui/ncc/PlayerListEntry.hpp b/src/gui/ncc/PlayerListEntry.hpp deleted file mode 100644 index a6ecd037..00000000 --- a/src/gui/ncc/PlayerListEntry.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * PlayerListEntry.hpp - * - * Created on: Apr 11, 2017 - * Author: nullifiedcat - */ - -#ifndef PLAYERLISTENTRY_HPP_ -#define PLAYERLISTENTRY_HPP_ - -#include "Menu.hpp" - -namespace menu { namespace ncc { - -class PlayerListEntry : public CBaseContainer { -public: - PlayerListEntry(int eid); - inline virtual void SortByZIndex() override {}; - virtual void Draw(int x, int y) override; - virtual void MoveChildren() override; - virtual void Update() override; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; -public: - const int idx; -}; - -namespace entrysubs { - -class SubBase : public CBaseWidget { -public: - SubBase(PlayerListEntry&); - virtual void Draw(int x, int y) override; -public: - PlayerListEntry& parent; - int color_fg { 0 }; - int color_bg { 0 }; - std::string text { "" }; -}; -class SubTitle : public SubBase { -public: - SubTitle(PlayerListEntry& parent, const std::string& title); - virtual void Draw(int x, int y) override; -}; -class SubState : public SubBase { -public: - inline SubState(PlayerListEntry& parent) : SubBase(parent) {}; - virtual void Update() override; - virtual bool ConsumesKey(ButtonCode_t key) override; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; -}; -class SubColorComponent : public SubBase { -public: - enum class Component { - R, - G, - B - }; - SubColorComponent(PlayerListEntry&, Component); - virtual void Update() override; - virtual bool ConsumesKey(ButtonCode_t key) override; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; -public: - const Component component; -}; - -} - -}} - -#endif /* PLAYERLISTENTRY_HPP_ */ diff --git a/src/gui/ncc/Radar.cpp b/src/gui/ncc/Radar.cpp deleted file mode 100644 index a2859912..00000000 --- a/src/gui/ncc/Radar.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Radar.cpp - * - * Created on: Mar 28, 2017 - * Author: nullifiedcat - */ - -#include "Radar.hpp" -#include "../../common.h" - -namespace menu { namespace ncc { - -Radar::Radar() : CBaseWidget("ncc_radar") {} - -std::pair Radar::GetSize() { - return { (int)hacks::tf::radar::size, (int)hacks::tf::radar::size }; -} - -void Radar::Update() { - if (!hacks::tf::radar::radar_enabled) Hide(); - else Show(); - SetOffset((int)hacks::tf::radar::radar_x, (int)hacks::tf::radar::radar_y); - if (IsPressed()) { - hacks::tf::radar::radar_x = (int)hacks::tf::radar::radar_x + g_pGUI->mouse_dx; - hacks::tf::radar::radar_y = (int)hacks::tf::radar::radar_y + g_pGUI->mouse_dy; - } -} - -}} diff --git a/src/gui/ncc/Radar.hpp b/src/gui/ncc/Radar.hpp deleted file mode 100644 index e07d3a10..00000000 --- a/src/gui/ncc/Radar.hpp +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Radar.hpp - * - * Created on: Mar 28, 2017 - * Author: nullifiedcat - */ - -#ifndef RADAR_HPP_ -#define RADAR_HPP_ - -#include "../CBaseWidget.h" - -namespace menu { namespace ncc { - -class Radar : public CBaseWidget { -public: - Radar(); - virtual void Update() override; - virtual std::pair GetSize() override; - //virtual void Draw() override; -}; - -}} - -#endif /* RADAR_HPP_ */ diff --git a/src/gui/ncc/Root.cpp b/src/gui/ncc/Root.cpp deleted file mode 100644 index 867af4cc..00000000 --- a/src/gui/ncc/Root.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Root.cpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#include "Root.hpp" -#include "Menu.hpp" -#include "Tooltip.hpp" -#include "Radar.hpp" -#include "../../common.h" - -namespace menu { namespace ncc { - -Texture logo_texture(&_binary_logo_start, 768, 384); - -Root::Root() : CBaseWindow("root_nullcore", nullptr) { - SetMaxSize(draw::width, draw::height); -} - -void Root::Update() { - tooltip->Hide(); - CBaseWindow::Update(); -} - -void Root::Draw(int x, int y) { - if (tooltip->IsVisible()) { - tooltip->SetOffset(g_pGUI->m_iMouseX + 24, g_pGUI->m_iMouseY + 8); - } - CBaseContainer::Draw(x, y); -} - -void Root::Setup() { - tooltip = new Tooltip(); - Logo* logo = new Logo(); - logo->SetOffset(draw::width / 2 - 288, 25); - AddChild(new Background()); - AddChild(logo); - AddChild(tooltip); - AddChild(&menu::ncc::MainList()); - menu::ncc::MainList().ChildByIndex(0)->Props()->SetBool("brackets3", true); - AddChild(new Radar()); - menu::ncc::MainList().Show(); - menu::ncc::MainList().SetOffset(draw::width / 2, draw::height / 2); - PlayerList* pl = new PlayerList(); - pl->SetOffset(200, 200); - AddChild(pl); - AddChild(new CritIndicator()); -} - -void Root::OnKeyPress(ButtonCode_t key, bool repeat) { - if (GetHoveredChild()) GetHoveredChild()->OnKeyPress(key, repeat); -} - -}} diff --git a/src/gui/ncc/Root.hpp b/src/gui/ncc/Root.hpp deleted file mode 100644 index ec81a609..00000000 --- a/src/gui/ncc/Root.hpp +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Root.hpp - * - * Created on: Mar 26, 2017 - * Author: nullifiedcat - */ - -#ifndef ROOT_HPP_ -#define ROOT_HPP_ - -#include "../CBaseWindow.h" - -namespace menu { namespace ncc { - -class Root : public CBaseWindow { -public: - Root(); - void Setup(); - virtual void Update() override; - virtual void OnKeyPress(ButtonCode_t key, bool repeat) override; - virtual void Draw(int x, int y) override; - inline virtual void MoveChildren() override {}; -}; - -}} - -#endif /* ROOT_HPP_ */ diff --git a/src/gui/ncc/Tooltip.cpp b/src/gui/ncc/Tooltip.cpp deleted file mode 100644 index d859111d..00000000 --- a/src/gui/ncc/Tooltip.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Tooltip.cpp - * - * Created on: Mar 27, 2017 - * Author: nullifiedcat - */ - -#include "Tooltip.hpp" -#include "../CTextLabel.h" -#include "../../common.h" - -namespace menu { namespace ncc { - -Tooltip::Tooltip() : CTextLabel("ncc_tooltip") { - SetZIndex(999); - SetPadding(3, 2); - SetMaxSize(220, -1); - SetAutoSize(false); - SetSize(220, -1); - Props()->SetInt("font", font_item); -} - -void Tooltip::HandleCustomEvent(KeyValues* event) { - if (!strcmp(event->GetName(), "scale_update")) { - SetMaxSize(Item::psize_x * (float)scale, -1); - SetSize(Item::psize_x * (float)scale, -1); - SetText(GetText()); // To update word wrapping. - } else if (!strcmp(event->GetName(), "font_update")) { - Props()->SetInt("font", font_item); - } -} - -void Tooltip::Draw(int x, int y) { - const auto& size = GetSize(); - int originx = x; - int originy = y; - if (originx + size.first > draw::width) originx -= size.first; - if (originx + size.second > draw::height) originy -= size.second; - static int bgcolor = colors::Create(0, 0, 0, 77); //colors::Create(70, 86, 47, 28); - static int fgcolor = colors::Create(200, 200, 190, 255); - draw::DrawRect(x, y, size.first, size.second, bgcolor); - draw::OutlineRect(x, y, size.first, size.second, GUIColor()); - draw::String(font_item, x + Props()->GetInt("padding_x"), y + Props()->GetInt("padding_y"), fgcolor, 2, GetText()); -} - -}} diff --git a/src/gui/ncc/Tooltip.hpp b/src/gui/ncc/Tooltip.hpp deleted file mode 100644 index 65672715..00000000 --- a/src/gui/ncc/Tooltip.hpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Tooltip.hpp - * - * Created on: Mar 27, 2017 - * Author: nullifiedcat - */ - -#ifndef TOOLTIP_HPP_ -#define TOOLTIP_HPP_ - -#include "../CTextLabel.h" - -#include "../../common.h" - -namespace menu { namespace ncc { - -class Tooltip : public CTextLabel { -public: - Tooltip(); - - virtual void Draw(int x, int y) override; - virtual void HandleCustomEvent(KeyValues* event) override; - inline virtual PositionMode GetPositionMode() override { return PositionMode::FLOATING; } -}; - -}} - -#endif /* TOOLTIP_HPP_ */ diff --git a/src/hack.cpp b/src/hack.cpp index 624fbbf5..cd0cfd00 100644 --- a/src/hack.cpp +++ b/src/hack.cpp @@ -26,6 +26,7 @@ #include "aftercheaders.h" #include +#include // All Hacks #include "hacks/hacklist.h" @@ -39,11 +40,12 @@ #define STRINGIFY(x) #x #define TO_STRING(x) STRINGIFY(x) -#if NOGUI != 1 -#include "gui/GUI.h" +#ifndef TEXTMODE +#include "ftrender.hpp" #endif #include "hooks/hookedmethods.h" +#include "init.hpp" #include "sdk.h" #include "vfunc.h" @@ -64,15 +66,42 @@ const std::string& hack::GetVersion() { if (version_set) return version; #if defined(GIT_COMMIT_HASH) && defined(GIT_COMMIT_DATE) version = "Version: #" GIT_COMMIT_HASH " " GIT_COMMIT_DATE; -#if NOGUI == 1 +#endif + version_set = true; + return version; +} + +const std::string& hack::GetType() { + static std::string version("Unknown Type"); + static bool version_set = false; + if (version_set) return version; + version = ""; +#if not defined(IPC_ENABLED) + version += " NOIPC"; +#endif +#if not ENABLE_GUI version += " NOGUI"; -#endif -#ifdef BUILD_GAME - version += " S " TO_STRING(BUILD_GAME); #else - version += " U"; + version += " IMGUI"; #endif + +#ifndef DYNAMIC_CLASSES + +#ifdef BUILD_GAME + version += " GAME " TO_STRING(BUILD_GAME); +#else + version += " UNIVERSAL"; #endif + +#else + version += " DYNAMIC"; +#endif + +#ifdef TEXTMODE + version += " TEXTMODE"; +#endif + + version = version.substr(1); version_set = true; return version; } @@ -83,27 +112,80 @@ std::stack& hack::command_stack() { return stack; } +#ifndef TEXTMODE /* Why would we need colored chat stuff in textmode? */ + +class AdvancedEventListener : public IGameEventListener { +public: + virtual void FireGameEvent( KeyValues * event) { + if (!event_log) return; + const char* name = event->GetName(); + if (!strcmp(name, "player_connect_client")) { + PrintChat("\x07%06X%s\x01 \x07%06X%s\x01 joining", 0xa06ba0, event->GetString("name"), 0x914e65, event->GetString("networkid")); + } else if (!strcmp(name, "player_activate")) { + int uid = event->GetInt("userid"); + int entity = g_IEngine->GetPlayerForUserID(uid); + player_info_s info; + if (g_IEngine->GetPlayerInfo(entity, &info)) { + PrintChat("\x07%06X%s\x01 connected", 0xa06ba0, info.name); + } + } else if (!strcmp(name, "player_disconnect")) { + CachedEntity* player = ENTITY(g_IEngine->GetPlayerForUserID(event->GetInt("userid"))); + PrintChat("\x07%06X%s\x01 \x07%06X%s\x01 disconnected", colors::chat::team(player->m_iTeam), event->GetString("name"), 0x914e65, event->GetString("networkid")); + } else if (!strcmp(name, "player_team")) { + if (event->GetBool("disconnect") != 1) { + int oteam = event->GetInt("oldteam"); + int nteam = event->GetInt("team"); + const char* oteam_s = teamname(oteam); + const char* nteam_s = teamname(nteam); + PrintChat("\x07%06X%s\x01 changed team (\x07%06X%s\x01 -> \x07%06X%s\x01)", 0xa06ba0, event->GetString("name"), colors::chat::team(oteam), oteam_s, colors::chat::team(nteam), nteam_s); + } + } + } +}; + +AdvancedEventListener adv_event_listener {}; + +#endif /* TEXTMODE */ + void hack::ExecuteCommand(const std::string command) { std::lock_guard guard(hack::command_stack_mutex); hack::command_stack().push(command); } + ConCommand* hack::c_Cat = 0; void hack::CC_Cat(const CCommand& args) { - int white = colors::white, blu = colors::blu, red = colors::red; - g_ICvar->ConsoleColorPrintf(*reinterpret_cast(&white), "cathook"); - g_ICvar->ConsoleColorPrintf(*reinterpret_cast(&blu), " by "); - g_ICvar->ConsoleColorPrintf(*reinterpret_cast(&red), "nullifiedcat\n"); - g_ICvar->ConsoleColorPrintf(*reinterpret_cast(&white), GetVersion().c_str()); - g_ICvar->ConsoleColorPrintf(*reinterpret_cast(&white), "\n"); + g_ICvar->ConsoleColorPrintf(Color(255, 255, 255, 255), "cathook"); + g_ICvar->ConsoleColorPrintf(Color( 0, 0, 255, 255), " by "); + g_ICvar->ConsoleColorPrintf(Color(255, 0, 0, 255), "nullifiedcat\n"); } void hack::Initialize() { + // Essential files must always exist, except when the game is running in text mode. +#ifndef TEXTMODE + + { + std::vector essential = { + "shaders/v2f-c4f.frag", "shaders/v2f-c4f.vert", + "shaders/v2f-t2f-c4f.frag", "shaders/v2f-t2f-c4f.vert", + "shaders/v3f-t2f-c4f.frag", "shaders/v3f-t2f-c4f.vert", + "menu.json", "fonts/opensans-bold.ttf" + }; + for (const auto& s : essential) { + std::ifstream exists("cathook/" + s, std::ios::in); + if (not exists) { + Error("Missing essential file: cathook/%s\nYou MUST run update-data script to finish installation", s.c_str()); + } + } + } + +#endif /* TEXTMODE */ + + logging::Info("Initializing..."); srand(time(0)); prctl(PR_SET_DUMPABLE,0,42,42,42); sharedobj::LoadAllSharedObjects(); - g_pszTFPath = tf_path_from_maps(); CreateInterfaces(); CDumper dumper; dumper.SaveDump(); @@ -113,6 +195,9 @@ void hack::Initialize() { logging::Info("Is CSS? %d", IsCSS()); logging::Info("Is TF? %d", IsTF()); InitClassTable(); + +#ifndef TEXTMODE /* We don't need medal to flip 100% when running textmode */ + IF_GAME (IsTF2()) { uintptr_t mmmf = (gSignatures.GetClientSignature("C7 44 24 04 09 00 00 00 BB ? ? ? ? C7 04 24 00 00 00 00 E8 ? ? ? ? BA ? ? ? ? 85 C0 B8 ? ? ? ? 0F 44 DA") + 37); if (mmmf) { @@ -127,26 +212,33 @@ void hack::Initialize() { Patch((void*)canInspectSig, (void*)patch, 3); }*/ } + +#endif /* TEXTMODE */ + BeginConVars(); hack::c_Cat = CreateConCommand(CON_NAME, &hack::CC_Cat, "Info"); g_Settings.Init(); EndConVars(); + +#ifndef TEXTMODE + draw::Initialize(); -#if NOGUI != 1 +#if ENABLE_GUI g_pGUI = new CatGUI(); g_pGUI->Setup(); #endif + +#endif /* TEXTMODE */ + gNetvars.init(); InitNetVars(); g_pLocalPlayer = new LocalPlayer(); g_pPlayerResource = new TFPlayerResource(); - - /* - * TIME FOR HOOKING! wow - */ +#ifndef TEXTMODE hooks::panel.Set(g_IPanel); hooks::panel.HookMethod((void*)PaintTraverse_hook, offsets::PaintTraverse()); hooks::panel.Apply(); +#endif uintptr_t* clientMode = 0; // Bad way to get clientmode. // FIXME [MP]? @@ -155,21 +247,48 @@ void hack::Initialize() { } hooks::clientmode.Set((void*)clientMode); hooks::clientmode.HookMethod((void*)CreateMove_hook, offsets::CreateMove()); +#ifndef TEXTMODE hooks::clientmode.HookMethod((void*)OverrideView_hook, offsets::OverrideView()); +#endif /* TEXTMODE */ hooks::clientmode.HookMethod((void*)LevelInit_hook, offsets::LevelInit()); hooks::clientmode.HookMethod((void*)LevelShutdown_hook, offsets::LevelShutdown()); hooks::clientmode.Apply(); + hooks::clientmode4.Set((void*)(clientMode), 4); + hooks::clientmode4.HookMethod((void*)FireGameEvent_hook, offsets::FireGameEvent()); + hooks::clientmode4.Apply(); hooks::client.Set(g_IBaseClient); hooks::client.HookMethod((void*)FrameStageNotify_hook, offsets::FrameStageNotify()); hooks::client.HookMethod((void*)DispatchUserMessage_hook, offsets::DispatchUserMessage()); + +#if TEXTMODE + //g_IMaterialSystem->SetInStubMode(true); + /*IF_GAME(IsTF2()) { + logging::Info("Graphics Nullified"); + // TODO offsets::()? + hooks::materialsystem.Set((void*)g_IMaterialSystem); + uintptr_t base = *(uintptr_t*)(g_IMaterialSystem); + hooks::materialsystem.HookMethod((void*)ReloadTextures_null_hook, 70); + hooks::materialsystem.HookMethod((void*)ReloadMaterials_null_hook, 71); + hooks::materialsystem.HookMethod((void*)FindMaterial_null_hook, 73); + hooks::materialsystem.HookMethod((void*)FindTexture_null_hook, 81); + hooks::materialsystem.HookMethod((void*)ReloadFilesInList_null_hook, 121); + hooks::materialsystem.HookMethod((void*)FindMaterialEx_null_hook, 123); + hooks::materialsystem.Apply(); + //hooks::materialsystem.HookMethod(); + }*/ +#endif +#ifndef TEXTMODE hooks::client.HookMethod((void*)IN_KeyEvent_hook, offsets::IN_KeyEvent()); +#endif /* TEXTMODE */ hooks::client.Apply(); hooks::input.Set(g_IInput); hooks::input.HookMethod((void*)GetUserCmd_hook, offsets::GetUserCmd()); hooks::input.Apply(); +#ifndef TEXTMODE hooks::modelrender.Set(g_IVModelRender); hooks::modelrender.HookMethod((void*)DrawModelExecute_hook, offsets::DrawModelExecute()); hooks::modelrender.Apply(); +#endif /* TEXTMODE */ hooks::steamfriends.Set(g_ISteamFriends); hooks::steamfriends.HookMethod((void*)GetFriendPersonaName_hook, offsets::GetFriendPersonaName()); hooks::steamfriends.Apply(); @@ -186,14 +305,18 @@ void hack::Initialize() { //hooks::hkBaseClientState8->Apply(); // FIXME [MP] - IF_GAME (IsTF2()) g_GlowObjectManager = *reinterpret_cast(gSignatures.GetClientSignature("C1 E0 05 03 05") + 5); - InitStrings(); hacks::shared::killsay::Init(); - hack::command_stack().push("exec cat_autoexec"); - hack::command_stack().push("cat_killsay_reload"); - hack::command_stack().push("cat_spam_reload"); logging::Info("Hooked!"); + velocity::Init(); playerlist::Load(); + +#ifndef TEXTMODE + + InitStrings(); +#if ENABLE_GUI + // cat_reloadscheme to load imgui + hack::command_stack().push("cat_reloadscheme"); +#endif if (g_ppScreenSpaceRegistrationHead && g_pScreenSpaceEffects) { effect_chams::g_pEffectChams = new CScreenSpaceEffectRegistration("_cathook_chams", &effect_chams::g_EffectChams); g_pScreenSpaceEffects->EnableScreenSpaceEffect("_cathook_chams"); @@ -201,10 +324,39 @@ void hack::Initialize() { effect_glow::g_pEffectGlow = new CScreenSpaceEffectRegistration("_cathook_glow", &effect_glow::g_EffectGlow); g_pScreenSpaceEffects->EnableScreenSpaceEffect("_cathook_glow"); } - //for (CScreenSpaceEffectRegistration* reg = *g_ppScreenSpaceRegistrationHead; reg; reg = reg->m_pNext) { - // logging::Info("%s", reg->m_pEffectName); - //} logging::Info("SSE enabled.."); + DoSDLHooking(); + logging::Info("SDL hooking done"); + g_IGameEventManager->AddListener(&adv_event_listener, false); + +#endif /* TEXTMODE */ + + hacks::shared::anticheat::Init(); + hacks::tf2::healarrow::Init(); + +#ifndef TEXTMODE + InitSpinner(); + logging::Info("Initialized Fidget Spinner"); + hacks::shared::spam::Init(); + backpacktf::init(); + logging::Info("Initialized Backpack.TF integration"); +#endif + + hacks::shared::walkbot::Initialize(); + + logging::Info("Clearing initializer stack"); + while (!init_stack().empty()) { + init_stack().top()(); + init_stack().pop(); + } + logging::Info("Initializer stack done"); + +#ifdef TEXTMODE + hack::command_stack().push("exec cat_autoexec_textmode"); +#endif + hack::command_stack().push("exec cat_autoexec"); + hack::command_stack().push("cat_killsay_reload"); + hack::command_stack().push("cat_spam_reload"); } void hack::Think() { @@ -215,6 +367,7 @@ void hack::Shutdown() { if (hack::shutdown) return; hack::shutdown = true; playerlist::Save(); + DoSDLUnhooking(); logging::Info("Unregistering convars.."); ConVar_Unregister(); logging::Info("Shutting down killsay..."); diff --git a/src/hack.h b/src/hack.h index 93ef3fb9..b9ec31ce 100644 --- a/src/hack.h +++ b/src/hack.h @@ -30,6 +30,7 @@ void ExecuteCommand(const std::string command); extern bool shutdown; const std::string& GetVersion(); +const std::string& GetType(); void Initialize(); void Think(); void Shutdown(); diff --git a/src/hacks/Achievement.cpp b/src/hacks/Achievement.cpp index 91a3b0f1..1a798aa8 100644 --- a/src/hacks/Achievement.cpp +++ b/src/hacks/Achievement.cpp @@ -51,7 +51,7 @@ CatCommand unlock_single("achievement_unlock_single", "Unlocks single achievemen logging::Info("NaN achievement ID!"); return; } - IAchievement* ach = (IAchievement*)g_IAchievementMgr->GetAchievementByID(id); + IAchievement* ach = reinterpret_cast(g_IAchievementMgr->GetAchievementByID(id)); if (ach) { g_IAchievementMgr->AwardAchievement(id); } diff --git a/src/hacks/Achievement.h b/src/hacks/Achievement.h index 14a81732..3968c75f 100644 --- a/src/hacks/Achievement.h +++ b/src/hacks/Achievement.h @@ -8,8 +8,6 @@ #ifndef HACKS_ACHIEVEMENT_H_ #define HACKS_ACHIEVEMENT_H_ -#include "IHack.h" - namespace hacks { namespace tf2 { namespace achievement { void Lock(); diff --git a/src/hacks/Aimbot.cpp b/src/hacks/Aimbot.cpp index f251b4da..294f48d5 100644 --- a/src/hacks/Aimbot.cpp +++ b/src/hacks/Aimbot.cpp @@ -5,132 +5,758 @@ * Author: nullifiedcat */ -#include "Aimbot.h" - -#include -#include -#include -#include -#include -#include - -#include "../aftercheaders.h" #include "../common.h" -#include "../conditions.h" -#include "../crits.h" -#include "../cvwrapper.h" -#include "../drawing.h" -#include "../entitycache.h" -#include "../globals.h" -#include "../helpers.h" -#include "../hoovy.hpp" -#include "../interfaces.h" -#include "../localplayer.h" -#include "../netvars.h" -#include "../playerlist.hpp" -#include "../prediction.h" -#include "../sdk/in_buttons.h" -#include "../targethelper.h" -#include "../usercmd.h" -#include "AntiAim.h" -#include "ESP.h" -#include "FollowBot.h" namespace hacks { namespace shared { namespace aimbot { - -EAimbotState state { EAimbotState::DISABLED }; -int target_eid { 0 }; -CachedEntity* target_highest = 0; -int minigun_fix_ticks { 0 }; -bool projectile_mode { false }; -float cur_proj_speed { 0.0f }; -float cur_proj_grav { 0.0f }; -bool headonly { false }; -int last_target { -1 }; -bool silent_huntsman { false }; -// This array will store calculated projectile/hitscan predictions -// for current frame, to avoid performing them again -AimbotCalculatedData_s calculated_data_array[2048] {}; - -static CatVar huntsman_full_auto(CV_SWITCH, "aimbot_full_auto_huntsman", "1", "Auto Huntsman", "Autoshoot will pull huntsman's string"); -static CatVar ignore_hoovy(CV_SWITCH, "aimbot_ignore_hoovy", "0", "Ignore Hoovies", "Aimbot won't attack hoovies"); -static CatVar wait_for_charge(CV_SWITCH, "aimbot_charge", "0", "Wait for sniper rifle charge", "Aimbot waits until it has enough charge to kill"); -static CatVar respect_vaccinator(CV_SWITCH, "aimbot_respect_vaccinator", "1", "Respect Vaccinator", "Hitscan weapons won't fire if enemy is vaccinated against bullets"); + +// User settings are stored and used by these vars +static CatVar enabled(CV_SWITCH, "aimbot_enabled", "0", "Enable Aimbot", "Main aimbot switch"); static CatVar aimkey(CV_KEY, "aimbot_aimkey", "0", "Aimkey", "Aimkey. Look at Aimkey Mode too!"); static CatEnum aimkey_modes_enum({ "DISABLED", "AIMKEY", "REVERSE", "TOGGLE" }); static CatVar aimkey_mode(aimkey_modes_enum, "aimbot_aimkey_mode", "1", "Aimkey mode", "DISABLED: aimbot is always active\nAIMKEY: aimbot is active when key is down\nREVERSE: aimbot is disabled when key is down\nTOGGLE: pressing key toggles aimbot"); +static CatVar autoshoot(CV_SWITCH, "aimbot_autoshoot", "1", "Autoshoot", "Shoot automatically when the target is locked, isn't compatible with 'Enable when attacking'"); static CatEnum hitbox_mode_enum({ "AUTO-HEAD", "AUTO-CLOSEST", "STATIC" }); static CatVar hitbox_mode(hitbox_mode_enum, "aimbot_hitboxmode", "0", "Hitbox Mode", "Defines hitbox selection mode"); -static CatVar enabled(CV_SWITCH, "aimbot_enabled", "0", "Enable Aimbot", "Main aimbot switch"); -static CatVar fov(CV_FLOAT, "aimbot_fov", "0", "Aimbot FOV", "FOV range for aimbot to lock targets. \"Smart FOV\" coming eventually.", 360.0f); +static CatVar fov(CV_FLOAT, "aimbot_fov", "0", "Aimbot FOV", "FOV range for aimbot to lock targets. \"Smart FOV\" coming eventually.", 180.0f); +static CatEnum priority_mode_enum({ "SMART", "FOV", "DISTANCE", "HEALTH" }); +static CatVar priority_mode(priority_mode_enum, "aimbot_prioritymode", "0", "Priority mode", "Priority mode.\n" + "SMART: Basically Auto-Threat. Will be tweakable eventually. " + "FOV, DISTANCE, HEALTH are self-explainable. HEALTH picks the weakest enemy"); +static CatVar wait_for_charge(CV_SWITCH, "aimbot_charge", "0", "Wait for sniper rifle charge", "Aimbot waits until it has enough charge to kill"); +static CatVar ignore_vaccinator(CV_SWITCH, "aimbot_ignore_vaccinator", "1", "Ignore Vaccinator", "Hitscan weapons won't fire if enemy is vaccinated against bullets"); +static CatVar ignore_hoovy(CV_SWITCH, "aimbot_ignore_hoovy", "0", "Ignore Hoovies", "Aimbot won't attack hoovies"); +static CatVar ignore_cloak(CV_SWITCH, "aimbot_ignore_cloak", "1", "Ignore cloaked", "Don't aim at invisible enemies"); +static CatVar ignore_deadringer(CV_SWITCH, "aimbot_ignore_deadringer", "1", "Ignore deadringer", "Don't aim at deadringed enemies"); +static CatVar buildings_sentry(CV_SWITCH, "aimbot_buildings_sentry", "1", "Aim Sentry", "Should aimbot aim at sentryguns?"); +static CatVar buildings_other(CV_SWITCH, "aimbot_buildings_other", "1", "Aim Other building", "Should aimbot aim at other buildings"); +static CatVar stickybot(CV_SWITCH, "aimbot_stickys", "0", "Aim Sticky", "Should aimbot aim at stickys"); +static CatEnum teammates_enum({ "ENEMY ONLY", "TEAMMATE ONLY", "BOTH" }); +static CatVar teammates(teammates_enum, "aimbot_teammates", "0", "Aim at teammates", "Use to choose which team/s to target"); +static CatVar silent(CV_SWITCH, "aimbot_silent", "1", "Silent", "Your screen doesn't get snapped to the point where aimbot aims at"); +static CatVar target_lock(CV_SWITCH, "aimbot_target_lock", "0", "Target Lock", "Keeps your previously chosen target untill target check fails"); static CatEnum hitbox_enum({ "HEAD", "PELVIS", "SPINE 0", "SPINE 1", "SPINE 2", "SPINE 3", "UPPER ARM L", "LOWER ARM L", "HAND L", "UPPER ARM R", "LOWER ARM R", "HAND R", "HIP L", "KNEE L", "FOOT L", "HIP R", "KNEE R", "FOOT R" }); static CatVar hitbox(hitbox_enum, "aimbot_hitbox", "0", "Hitbox", "Hitbox to aim at. Ignored if AutoHitbox is on"); -static CatVar lerp(CV_SWITCH, "aimbot_interp", "1", "Latency interpolation", "Enable basic latency interpolation"); -static CatVar autoshoot(CV_SWITCH, "aimbot_autoshoot", "1", "Autoshoot", "Shoot automatically when the target is locked, isn't compatible with 'Enable when attacking'"); -static CatVar silent(CV_SWITCH, "aimbot_silent", "1", "Silent", "Your screen doesn't get snapped to the point where aimbot aims at"); static CatVar zoomed_only(CV_SWITCH, "aimbot_zoomed", "1", "Zoomed only", "Don't autoshoot with unzoomed rifles"); -static CatVar teammates(CV_SWITCH, "aimbot_teammates", "0", "Aim at teammates", "Aim at your own team. Useful for HL2DM"); -static CatVar huntsman_autoshoot(CV_FLOAT, "aimbot_huntsman_charge", "0.5", "Huntsman autoshoot", "Minimum charge for autoshooting with huntsman.\n" - "Set it to 0.01 if you want to shoot as soon as you start pulling the arrow", 0.01f, 1.0f); +static CatVar only_can_shoot(CV_SWITCH, "aimbot_only_when_can_shoot", "1", "Active when can shoot", "Aimbot only activates when you can instantly shoot, sometimes making the autoshoot invisible for spectators"); +static CatVar attack_only(CV_SWITCH, "aimbot_enable_attack_only", "0", "Active when attacking", "Basically makes Mouse1 an AimKey, isn't compatible with AutoShoot"); static CatVar max_range(CV_INT, "aimbot_maxrange", "0", "Max distance", "Max range for aimbot\n" "900-1100 range is efficient for scout/widowmaker engineer", 4096.0f); -//CatVar* v_iMaxAutoshootRange; // TODO IMPLEMENT -static CatVar respect_cloak(CV_SWITCH, "aimbot_respect_cloak", "1", "Respect cloak", "Don't aim at invisible enemies"); -static CatVar attack_only(CV_SWITCH, "aimbot_enable_attack_only", "0", "Active when attacking", "Basically makes Mouse1 an AimKey, isn't compatible with AutoShoot"); +static CatVar extrapolate(CV_SWITCH, "aimbot_extrapolate", "0", "Latency extrapolation", "(NOT RECOMMENDED) latency extrapolation"); +static CatVar slowaim(CV_SWITCH, "aimbot_slow", "0", "Slow Aim", "Slowly moves your crosshair onto the target for more legit play\nDisables silent aimbot"); +static CatVar slowaim_smoothing(CV_INT, "aimbot_slow_smooth", "10", "Slow Aim Smooth", "How slow the slow aim's aiming should be", 50); +static CatVar slowaim_autoshoot(CV_INT, "aimbot_slow_autoshoot", "10", "Slow Aim Threshhold", "Distance to autoshoot while smooth aiming", 25); static CatVar projectile_aimbot(CV_SWITCH, "aimbot_projectile", "1", "Projectile aimbot", "If you turn it off, aimbot won't try to aim with projectile weapons"); +static CatVar proj_fov(CV_SWITCH, "aimbot_proj_fovpred", "0", "Projectile FOV mode", "If disabled, FOV restrictions apply to current target position"); +static CatVar proj_visibility(CV_SWITCH, "aimbot_proj_vispred", "0", "Projectile visibility prediction", "If enabled, projectile aimbot will perform additional visibility checking and won't try to predict enemies behind walls"); +static CatVar proj_gravity(CV_FLOAT, "aimbot_proj_gravity", "0", "Projectile gravity", + "Force override projectile gravity. Useful for debugging.", 1.0f); static CatVar proj_speed(CV_FLOAT, "aimbot_proj_speed", "0", "Projectile speed", "Force override projectile speed.\n" "Can be useful for playing with MvM upgrades or on x10 servers " "since there is no \"automatic\" projectile speed detection in " "cathook. Yet."); -static CatVar proj_gravity(CV_FLOAT, "aimbot_proj_gravity", "0", "Projectile gravity", - "Force override projectile gravity. Useful for debugging.", 1.0f); -static CatVar buildings(CV_SWITCH, "aimbot_buildings", "1", "Aim at buildings", "Should aimbot aim at buildings?"); -static CatVar only_can_shoot(CV_SWITCH, "aimbot_only_when_can_shoot", "1", "Active when can shoot", "Aimbot only activates when you can instantly shoot, sometimes making the autoshoot invisible for spectators"); -static CatEnum priority_mode_enum({ "SMART", "FOV", "DISTANCE", "HEALTH" }); -static CatVar priority_mode(priority_mode_enum, "aimbot_prioritymode", "0", "Priority mode", "Priority mode.\n" - "SMART: Basically Auto-Threat. Will be tweakable eventually. " - "FOV, DISTANCE, HEALTH are self-explainable. HEALTH picks the weakest enemy"); -static CatVar proj_visibility(CV_SWITCH, "aimbot_proj_vispred", "0", "Projectile visibility prediction", "If enabled, projectile aimbot will perform additional visibility checking and won't try to predict enemies behind walls"); -static CatVar proj_fov(CV_SWITCH, "aimbot_proj_fovpred", "0", "Projectile FOV mode", "If disabled, FOV restrictions apply to current target position"); +static CatVar huntsman_autoshoot(CV_FLOAT, "aimbot_huntsman_charge", "0.5", "Huntsman autoshoot", "Minimum charge for autoshooting with huntsman.\n" + "Set it to 0.01 if you want to shoot as soon as you start pulling the arrow", 0.01f, 1.0f); +static CatVar huntsman_full_auto(CV_SWITCH, "aimbot_full_auto_huntsman", "1", "Auto Huntsman", "Autoshoot will pull huntsman's string"); +// Debug vars +static CatVar aimbot_debug(CV_SWITCH, "aimbot_debug", "0", "Aimbot Debug", "Display simple debug info for aimbot"); +static CatVar engine_projpred(CV_SWITCH, "debug_aimbot_engine_pp", "0", "Engine ProjPred"); +// Followbot vars static CatVar auto_spin_up(CV_SWITCH, "aimbot_spin_up", "0", "Auto Spin Up", "Spin up minigun if you can see target, useful for followbots"); static CatVar auto_zoom(CV_SWITCH, "aimbot_auto_zoom", "0", "Auto Zoom", "Automatically zoom in if you can see target, useful for followbots"); -static CatVar engine_predict(CV_SWITCH, "aimbot_engine_pred", "0", "Engine Prediction", "Improves accuracy by preforming engine prediction\nKnown bugs: Crash on disconnect, breaks bhop"); -//Initialize vars for slow aim -static CatVar slowaim(CV_SWITCH, "aimbot_slow", "0", "Slow Aim", "Slowly moves your crosshair onto the targets face\nDoesn't work with Silent or Anti-aim"); -static CatVar slowaim_smoothing(CV_INT, "aimbot_slow_smooth", "10", "Slow Aim Smooth", "How slow the slow aim's aiming should be", 50); -static CatVar slowaim_autoshoot(CV_INT, "aimbot_slow_autoshoot", "10", "Slow Aim Threshhold", "Distance to autoshoot while smooth aiming", 25); -static CatVar aimbot_debug(CV_SWITCH, "aimbot_debug", "0", "Aimbot Debug", "Print some internal state info for aimbot"); +static CatVar fovcircle_opacity(CV_FLOAT, "aimbot_fov_draw_opacity", "0.7", "FOV Circle Opacity", "Defines opacity of FOV circle", 0.0f, 1.0f); +static CatVar rageonly(CV_SWITCH, "aimbot_rage_only", "0", "Ignore non-rage targets", "Use playerlist to set up rage targets"); + +static CatVar miss_chance(CV_FLOAT, "aimbot_miss_chance", "0", "Miss chance", "From 0 to 1. Aimbot will NOT aim in these % cases", 0.0f, 1.0f); +static CatVar auto_unzoom(CV_SWITCH, "aimbot_auto_unzoom", "0", "Auto Un-zoom", "Automatically unzoom"); + +// Current Entity +int target_eid { 0 }; +CachedEntity* target = 0; +CachedEntity* target_last = 0; +bool foundTarget = false; +// Projectile info +bool projectile_mode { false }; +float cur_proj_speed { 0.0f }; +float cur_proj_grav { 0.0f }; +// If slow aimbot allows autoshoot bool slowCanShoot = false; -/*//Salting vars that need to be saved due to them being time based -static CatVar slowaim_salting(CV_SWITCH, "aimbot_slow_salt", "1", "Slow Aim Smooth", "Makes the slowaim more random", 5); -float saltWait = 0; -int saltRandom = 0;*/ -static CatVar instant_rezoom_enabled(CV_SWITCH, "aimbot_instant_rezoom_enabled", "0", "Instant rezoom", "Allows you to instantly zoom after you shoot\nGreat for pre-charging charged shots\nOccasionally fails"); -bool instant_rezoom_shoot = false; +bool silent_huntsman { false }; -CachedEntity* CurrentTarget() { - if (state == EAimbotState::TARGET_FOUND || state == EAimbotState::AIMING) - return ENTITY(target_eid); - return nullptr; +// This array will store calculated projectile/hitscan predictions +// for current frame, to avoid performing them again +AimbotCalculatedData_s calculated_data_array[2048] {}; + +// The main "loop" of the aimbot. +void CreateMove() { + + // Check if aimbot is enabled + if (!enabled) return; + + if (auto_unzoom) { + if (g_pLocalPlayer->holding_sniper_rifle) { + if (g_pLocalPlayer->bZoomed) { + if (g_GlobalVars->curtime - g_pLocalPlayer->flZoomBegin > 5.0f) + g_pUserCmd->buttons |= IN_ATTACK2; + } + } + } + + // Refresh projectile info + int huntsman_ticks = 0; + projectile_mode = (GetProjectileData(g_pLocalPlayer->weapon(), cur_proj_speed, cur_proj_grav)); + if (proj_speed) + cur_proj_speed = (float)proj_speed; + if (proj_gravity) + cur_proj_grav = (float)proj_gravity; + + // Attemt to reduce huntsman_ticks by 1 untill it reaches 0 + if (huntsman_ticks) { + // Disable attack + g_pUserCmd->buttons |= IN_ATTACK; + // Returns 0 - Something higher than 0 + huntsman_ticks = max(0, huntsman_ticks - 1); + } + + // Save should aim info + // We do this as we need to pass whether the aimkey allows aiming to both the find target and aiming system. If we just call the func than toggle aimkey would break so we save it to a var to use it twice + bool aimkey_status = UpdateAimkey(); + + // Refresh our best target + CachedEntity* target = RetrieveBestTarget(aimkey_status); + + // Check target for dormancy and if there even is a target at all + if (CE_GOOD(target) && foundTarget) { + + IF_GAME (IsTF()) { + if (auto_zoom) { + if (g_pLocalPlayer->holding_sniper_rifle) { + if (not g_pLocalPlayer->bZoomed) { + g_pUserCmd->buttons |= IN_ATTACK2; + } + } + } + } + +#ifndef TEXTMODE + // Set target esp color to pink + hacks::shared::esp::SetEntityColor(target, colors::pink); +#endif + + // Check if player can aim and if aimkey allows aiming + // We also preform a CanShoot check here per the old canshoot method + if (ShouldAim() && aimkey_status && GetCanAim(1)) { + + // Check if player isnt using a huntsman + if (g_pLocalPlayer->weapon()->m_iClassID != CL_CLASS(CTFCompoundBow)) { + + // We check if we need to do a canshoot check as we might want to shoot but not aim, so do that check here + if (GetCanAim(2)) { + // Check the flNextPrimaryAttack netvar to tell when to aim + if (CanShoot()) Aim(target); + } else { + // If settings dont allow canShoot check, then just aim + Aim(target); + } + // Attemt to auto-shoot + if (CanAutoShoot()) g_pUserCmd->buttons |= IN_ATTACK; + + // If player is using huntsman, we use a different system for autoshooting + } else { + + // Grab time when charge began + float begincharge = CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flChargeBeginTime); + // Reset current charge count + float charge = 0; + // If bow is not charged, reset the charge time keeper + if (begincharge != 0) { + charge = g_GlobalVars->curtime - begincharge; + // Keep the charge time keeper kept at 1 second + if (charge > 1.0f) charge = 1.0f; + silent_huntsman = true; + } + // If current charge is equal to or more than the user limit allows, then release the huntsman + if (charge >= (float)huntsman_autoshoot) { + // Stop user attacking + g_pUserCmd->buttons &= ~IN_ATTACK; + // temporarily stop the anti-aim to allow the projectile to pass due to attack not being used + hacks::shared::antiaim::SetSafeSpace(3); + // If user shouldnt release hunstman, attack for user here + } else if (autoshoot && huntsman_full_auto) { + huntsman_ticks = 3; + g_pUserCmd->buttons |= IN_ATTACK; + } + // If player released the huntsman, aim here + if (!(g_pUserCmd->buttons & IN_ATTACK) && silent_huntsman) { + Aim(target); + silent_huntsman = false; + } + } + } + } + + // If settings allow and slowaim is disabled, Use silent angles + if (silent && !slowaim) g_pLocalPlayer->bUseSilentAngles = true; + return; +} + +// The first check to see if the player should aim in the first place +bool ShouldAim() { + // Checks should be in order: cheap -> expensive + + // Check for +attack if settings allow it + if (attack_only && !(g_pUserCmd->buttons & IN_ATTACK)) { + return false; + } + // Check for +use + if (g_pUserCmd->buttons & IN_USE) return false; + // Check if using action slot item + if (g_pLocalPlayer->using_action_slot_item) return false; + + IF_GAME (IsTF2()) { + // Check if Carrying A building + if (CE_BYTE(g_pLocalPlayer->entity, netvar.m_bCarryingObject)) return false; + // Check if deadringer out + if (CE_BYTE(g_pLocalPlayer->entity, netvar.m_bFeignDeathReady)) return false; + // If zoomed only is on, check if zoomed + if (zoomed_only && g_pLocalPlayer->holding_sniper_rifle) { + if (!g_pLocalPlayer->bZoomed && !(g_pUserCmd->buttons & IN_ATTACK)) return false; + } + // Check if player is taunting + if (HasCondition(g_pLocalPlayer->entity)) return false; + // Check if player is cloaked + if (IsPlayerInvisible(g_pLocalPlayer->entity)) return false; + // Disable aimbot with stickbomb launcher + if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFPipebombLauncher)) return false; + } + + IF_GAME (IsTF2()) { + switch (GetWeaponMode()) { + case weapon_hitscan: + break; + case weapon_melee: + break; + // Check if player is using a projectile based weapon without the setting enabled + case weapon_projectile: + if (!projectile_aimbot) return false; + break; + // Check if player doesnt have a weapon usable by aimbot + default: + return false; + }; + } + + IF_GAME (IsTF()) { + // Check if player is zooming + if (g_pLocalPlayer->bZoomed) { + if (!(g_pUserCmd->buttons & (IN_ATTACK | IN_ATTACK2))) { + if (!CanHeadshot()) return false; + } + } + + // Minigun spun up handler + if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFMinigun)) { + int weapon_state = CE_INT(g_pLocalPlayer->weapon(), netvar.iWeaponState); + // If user setting for autospin isnt true, then we check if minigun is already zoomed + if ((weapon_state == MinigunState_t::AC_STATE_IDLE || weapon_state == MinigunState_t::AC_STATE_STARTFIRING) && !auto_spin_up) { + return false; + } + if (auto_spin_up) { + g_pUserCmd->buttons |= IN_ATTACK2; + } + if (!(g_pUserCmd->buttons & (IN_ATTACK2 | IN_ATTACK))) { + return false; + } + } + + // Check if crithack allows attacking + if (!AllowAttacking()) + return false; + } + return true; +} + +// Function to find a suitable target +CachedEntity* RetrieveBestTarget(bool aimkey_state) { + + // If we have a previously chosen target, target lock is on, and the aimkey is allowed, then attemt to keep the previous target + if (target_lock && foundTarget && aimkey_state) { + if (CE_GOOD(target_last)) { + // Check if previous target is still good + if (IsTargetStateGood(target_last)) { + // If it is then return it again + return target_last; + } + } + } + + // We dont have a target currently so we must find one, reset statuses + foundTarget = false; + target_last = nullptr; + + // Book keeping vars + float target_highest_score, scr; + CachedEntity* ent; + CachedEntity* target_highest_ent = 0; + target_highest_score = -256; + // Loop that checks all ents whether it is a good target or not + for (int i = 0; i < HIGHEST_ENTITY; i++) { + ent = ENTITY(i); + // Check for null and dormant + if (CE_BAD(ent)) continue; + // Check whether the current ent is good enough to target + if (IsTargetStateGood(ent)) { + // Get a score for the entity + // Distance Priority, Uses this is melee is used + if (GetWeaponMode() == weaponmode::weapon_melee || (int)priority_mode == 2) { + scr = 4096.0f - calculated_data_array[i].aim_position.DistTo(g_pLocalPlayer->v_Eye); + } else { + switch ((int)priority_mode) { + case 0: // Smart Priority + scr = GetScoreForEntity(ent); + break; + case 1: // Fov Priority + scr = 360.0f - calculated_data_array[ent->m_IDX].fov; + break; + case 3: // Health Priority + scr = 450.0f - ent->m_iHealth; + break; + } + } + // Compare the top score to our current ents score + if (scr > target_highest_score) { + // Set foundTarget status to true + foundTarget = true; + // Save found target info to vars + target_highest_score = scr; + target_highest_ent = ent; + } + } + } + // Save the ent for future use with target lock + target_last = target_highest_ent; + // When our for loop finishes, return our ent + return target_highest_ent; +} + +// A second check to determine whether a target is good enough to be aimed at +bool IsTargetStateGood(CachedEntity* entity) { + + // Check for Players + if (entity->m_Type == ENTITY_PLAYER) { + // Check if target is The local player + if (entity == LOCAL_E) return false; + // Dont aim at dead player + if (!entity->m_bAlivePlayer) return false; + // Dont aim at teammates + if ((int)teammates != 2 && ((!entity->m_bEnemy && !teammates) || (entity->m_bEnemy && teammates))) return false; + // Check if player is too far away + if (EffectiveTargetingRange()) { + if (entity->m_flDistance > EffectiveTargetingRange()) return false; + } + if (rageonly) { + if (playerlist::AccessData(entity).state != playerlist::k_EState::RAGE) { + return false; + } + } + IF_GAME (IsTF()) { + // If settings allow waiting for charge, and current charge cant kill target, dont aim unless at 100% and the player wants to fire at 100% anyways + if (wait_for_charge && g_pLocalPlayer->holding_sniper_rifle) { + // Grab netvar for current charge damage and multiply by 3 for headshot + float cdmg = CE_FLOAT(LOCAL_W, netvar.flChargedDamage) * 3; + bool maxCharge = cdmg >= 450.0F; + + // Darwins damage correction, Darwins protects against 15% of damage + if (HasDarwins(entity)) + cdmg = (cdmg * .85) - 1; + // Vaccinator damage correction, Vac charge protects against 75% of damage + if (HasCondition(entity)) { + cdmg = (cdmg * .25) - 1; + // Passive bullet resist protects against 10% of damage + } else if (HasCondition(entity)) { + cdmg = (cdmg * .90) - 1; + } + // Invis damage correction, Invis spies get protection from 10% of damage + if (IsPlayerInvisible(entity)) + cdmg = (cdmg * .80) - 1; + + // Check if player will die from headshot or if target has more than 450 health and sniper has max chage + if ( !(entity->m_iHealth <= 150.0F || entity->m_iHealth <= cdmg || !g_pLocalPlayer->bZoomed || (maxCharge && entity->m_iHealth > 450.0F)) ) { + return false; + } + } + + // If settings allow, ignore taunting players + if (ignore_taunting && HasCondition(entity)) return false; + // Dont target invulnerable players, ex: uber, bonk + if (IsPlayerInvulnerable(entity)) return false; + // Checks for cloaked/deadringed players + if (ignore_cloak || ignore_deadringer) { + if (IsPlayerInvisible(entity)) { + // Determine whether cloaked player is using deadringer and checks user settings accordingly + // Item id for deadringer is 59 as of time of creation + if (HasWeapon(entity, 59)) { + if (ignore_deadringer) return false; + } else { + if (ignore_cloak) return false; + } + } + } + // If settings allow, dont target vaccinated players + if (g_pLocalPlayer->weapon_mode == weaponmode::weapon_hitscan || LOCAL_W->m_iClassID == CL_CLASS(CTFCompoundBow)) + if (ignore_vaccinator && HasCondition(entity)) return false; + } + // Dont target players marked as friendly + if (playerlist::IsFriendly(playerlist::AccessData(entity).state)) return false; + IF_GAME (IsTF()) { + // If settings allow, ignore hoovys + if (ignore_hoovy && IsHoovy(entity)) { + return false; + } + } + // Preform hitbox prediction + int hitbox = BestHitbox(entity); + AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; + cd.hitbox = hitbox; + + // If VisCheck fails, dont target player + if (!VischeckPredictedEntity(entity)) return false; + + // Check if player is within fov. Fov check can be preformed as it is a minimal fps drop and it even needs to be predicted beforehand by the vischeck anyways + if ((float)fov > 0.0f && cd.fov > (float)fov) return false; + + // Target passed the tests so return true + return true; + + // Check for buildings + } else if (entity->m_Type == ENTITY_BUILDING) { + // Check if building aimbot is enabled + if ( !(buildings_other || buildings_sentry) ) return false; + // Check if enemy building + if (!entity->m_bEnemy) return false; + // Check if building is within range + if (EffectiveTargetingRange()) { + if (entity->m_flDistance > (int)EffectiveTargetingRange()) return false; + } + + // If needed, Check if building type is allowed + if ( !(buildings_other && buildings_sentry) ) { + // Check if target is a sentrygun + if ( entity->m_iClassID == CL_CLASS(CObjectSentrygun) ) { + // If sentrys are not allowed, dont target + if (!buildings_sentry) return false; + } else { + // If target is not a sentry, check if other buildings are allowed + if (!buildings_other) return false; + } + } + + // Grab the prediction var + AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; + + // If VisCheck fails, dont target building + if (!VischeckPredictedEntity(entity)) return false; + + // Check if building is within fov + if ((float)fov > 0.0f && cd.fov > (float)fov) return false; + + // Target passed the tests so return true + return true; + + // Check for stickybombs + } else if (entity->m_iClassID == CL_CLASS(CTFGrenadePipebombProjectile)) { + // Check if sticky aimbot is enabled + if (!stickybot) return false; + + // Only hitscan weapons can break stickys so check for them. + if (!(GetWeaponMode() == weapon_hitscan || GetWeaponMode() == weapon_melee)) return false; + + // Check if target is within range + if (EffectiveTargetingRange()) { + if (entity->m_flDistance > (int)EffectiveTargetingRange()) return false; + } + + // Check if thrower is a teammate + if (!entity->m_bEnemy) return false; + + // Check if target is a pipe bomb + if (CE_INT(entity, netvar.iPipeType) != 1) return false; + + // Grab the prediction var + AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; + + // If VisCheck fails, dont target building + if (!VischeckPredictedEntity(entity)) return false; + + // Check if building is within fov + if ((float)fov > 0.0f && cd.fov > (float)fov) return false; + + // Target passed the tests so return true + return true; + + } else { + // If target is not player or building, return false + return false; + } + // An impossible error so just return false + return false; +} + +// A function to aim at a specific entitiy +void Aim(CachedEntity* entity) { + if (float(miss_chance) > 0.0f) { + if ((rand() % 100) < float(miss_chance) * 100.0f) { + return; + } + } + + // Dont aim at a bad entity + if (CE_BAD(entity)) return; + + // Create some vars + Vector angles, tr; + int hitbox; + + // Grab the targets vector, and vector it for the eye angles + tr = (PredictEntity(entity) - g_pLocalPlayer->v_Eye); + VectorAngles(tr, angles); + + // Clamp angles + fClampAngle(angles); + + // Slow the aiming to the aim vector if true + if (slowaim) slowAim(angles, g_pUserCmd->viewangles); + + // Set angles + g_pUserCmd->viewangles = angles; + + // Finish function + return; } -int ClosestHitbox(CachedEntity* target) { - PROF_SECTION(CM_aimbot_closesthitbox); +// A function to check whether player can autoshoot +bool CanAutoShoot() { + + // First check whether user settings allow autoshoot + if (autoshoot) { + + // A var for weapons not to use with autoshoot + static int forbiddenWeapons[] = { CL_CLASS(CTFCompoundBow), CL_CLASS(CTFKnife) }; + int weapon_class; + bool attack = true; + + // If your using a sniper rifle, are zoomed and cant headshot, then return false + IF_GAME (IsTF()) { + if (g_pLocalPlayer->clazz == tf_class::tf_sniper) { + if (g_pLocalPlayer->holding_sniper_rifle) { + if (zoomed_only && !CanHeadshot()) attack = false; + } + } + } + + // Check if zoomed, and zoom if not, then zoom + /*IF_GAME (IsTF()) { + if (g_pLocalPlayer->clazz == tf_class::tf_sniper) { + if (g_pLocalPlayer->holding_sniper_rifle) { + if (auto_zoom && !HasCondition(LOCAL_E)) { + g_pUserCmd->buttons |= IN_ATTACK2; + attack = false; + } + } + } + }*/ + + // Check if ambassador can headshot + IF_GAME (IsTF2()) { + if (IsAmbassador(g_pLocalPlayer->weapon())) { + // Check if ambasador can headshot + if (!AmbassadorCanHeadshot()) return false; + } + } + // Don't autoshoot with the knife or bow! + weapon_class = g_pLocalPlayer->weapon()->m_iClassID; + for (int i = 0; i < 2; i++) { + if (weapon_class == forbiddenWeapons[i]) { + attack = false; + break; + } + } + + //Autoshoot breaks Slow aimbot, so use a workaround to detect when it can + if (slowaim && !slowCanShoot) attack = false; + + // Return what + return attack; + } else + // Return false due to setting not allowing autoshoot + return false; +} + +// Grab a vector for a specific ent +const Vector& PredictEntity(CachedEntity* entity) { + // Pull out predicted data + AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; + Vector& result = cd.aim_position; + // If predicted vector has already been calculated this tick, then return it. + if (cd.predict_tick == tickcount) return result; + // If ent is a player, find a corresponding vector + if ((entity->m_Type == ENTITY_PLAYER)) { + // If using projectiles, predict a vector + if (projectile_mode) { + // Use prediction engine if user settings allow + if (engine_projpred) + result = ProjectilePrediction_Engine(entity, cd.hitbox, cur_proj_speed, cur_proj_grav, 0); + else + result = ProjectilePrediction(entity, cd.hitbox, cur_proj_speed, cur_proj_grav, PlayerGravityMod(entity)); + } else { + // If using extrapolation, then predict a vector + if (extrapolate) + result = SimpleLatencyPrediction(entity, cd.hitbox); + // else just grab strait from the hitbox + else + GetHitbox(entity, cd.hitbox, result); + } + // If ent is a building, find a corresponding vector + } else if (entity->m_Type == ENTITY_BUILDING) { + result = GetBuildingPosition(entity); + // If ent isnt a special type, just use origin + } else { + result = entity->m_vecOrigin; + } + // Reset the predicted tickcount for the ent + cd.predict_tick = tickcount; + // Pre-Calculate fov and store to array + cd.fov = GetFov(g_pLocalPlayer->v_OrigViewangles, g_pLocalPlayer->v_Eye, result); + // Return the found vector + return result; +} + +// A function to find the best hitbox for a target +int BestHitbox(CachedEntity* target) { + + // Switch based apon the hitbox mode set by the user + switch ((int)hitbox_mode) { + case 0: { // AUTO-HEAD priority + // The best hitbox var + int preferred = hitbox; + // Var to keep if we can bodyshot + bool headonly = false; + // Save the local players current weapon to a var + int ci = g_pLocalPlayer->weapon()->m_iClassID; + IF_GAME (IsTF()) { + // Set our default hitbox for pelvis + preferred = hitbox_t::pelvis; + // If user is using a sniper rifle, Set headonly to whether we can headshot or not, + if (g_pLocalPlayer->holding_sniper_rifle) { + headonly = CanHeadshot(); + // If player is using a compund bow, set headonly to true + } else if (ci == CL_CLASS(CTFCompoundBow)) { + headonly = true; + // If player is using an ambassador, set headonly to true + } else if (IsAmbassador(g_pLocalPlayer->weapon())) { + // We only want to aim for the head if the ambassador can headshot + headonly = AmbassadorCanHeadshot(); + // 18 health is a good number to use as thats the usual minimum damage it can do with a bodyshot, but damage could potentially be higher + if (target->m_iHealth <= 18 || IsPlayerCritBoosted(g_pLocalPlayer->entity)) headonly = false; + // If player is using a rocket based weapon, prefer the hip + } else if (ci == CL_CLASS(CTFRocketLauncher) || + ci == CL_CLASS(CTFRocketLauncher_AirStrike) || + ci == CL_CLASS(CTFRocketLauncher_DirectHit) || + ci == CL_CLASS(CTFRocketLauncher_Mortar)) { + preferred = hitbox_t::hip_L; + } + // If target is off the ground and local player is using projectile weapons other than the bow, use the higher hitbox, spine_3 + if (GetWeaponMode() == weaponmode::weapon_projectile) { + // Grab netvar for flags and save to a var + int flags = CE_INT(target, netvar.iFlags); + // Extract ground var from flags + bool ground = (flags & (1 << 0)); + if (!ground) { + if (g_pLocalPlayer->weapon()->m_iClassID != CL_CLASS(CTFCompoundBow)) { + preferred = hitbox_t::spine_3; + } + } + } + + // Bodyshot handling + if (g_pLocalPlayer->holding_sniper_rifle) { + + // Grab netvar for current charge damage + float cdmg = CE_FLOAT(LOCAL_W, netvar.flChargedDamage); + // Set our baseline bodyshot damage + float bdmg = 50; + // Darwins damage correction + if (HasDarwins(target)) { + // Darwins protects against 15% of damage + bdmg = (bdmg * .85) - 1; + cdmg = (cdmg * .85) - 1; + } + // Vaccinator damage correction + if (HasCondition(target)) { + // Vac charge protects against 75% of damage + bdmg = (bdmg * .25) - 1; + cdmg = (cdmg * .25) - 1; + } else if (HasCondition(target)) { + // Passive bullet resist protects against 10% of damage + bdmg = (bdmg * .90) - 1; + cdmg = (cdmg * .90) - 1; + } + // Invis damage correction + if (IsPlayerInvisible(target)) { + // Invis spies get protection from 10% of damage + bdmg = (bdmg * .80) - 1; + cdmg = (cdmg * .80) - 1; + } + // If can headshot and if bodyshot kill from charge damage, or if crit boosted and they have 150 health, or if player isnt zoomed, or if the enemy has less than 40, due to darwins, and only if they have less than 150 health will it try to bodyshot + if (CanHeadshot() && (cdmg >= target->m_iHealth || IsPlayerCritBoosted(g_pLocalPlayer->entity) || !g_pLocalPlayer->bZoomed || target->m_iHealth <= bdmg) && target->m_iHealth <= 150) { + // We dont need to hit the head as a bodyshot will kill + preferred = hitbox_t::spine_1; + headonly = false; + } + } + // In counter-strike source, headshots are what we want + } else IF_GAME (IsCSS()) { + headonly = true; + } + // If headonly is true, return the var here + if (headonly) { + IF_GAME (IsTF()) + return hitbox_t::head; + IF_GAME (IsCSS()) + return 12; + } + // If the prefered hitbox vis check passes, use it + if (target->hitboxes.VisibilityCheck(preferred)) return preferred; + // Else attempt to find a hitbox at all + for (int i = projectile_mode ? 1 : 0; i < target->hitboxes.GetNumHitboxes(); i++) { + if (target->hitboxes.VisibilityCheck(i)) return i; + } + } break; + case 1: { // AUTO-CLOSEST priority + // Return closest hitbox to crosshair + return ClosestHitbox(target); + } break; + case 2: { // STATIC priority + // Return a user chosen hitbox + return (int)hitbox; + } break; + } + // without a good hitbox, just return -1 in its place + return -1; +} + +// Function to find the closesnt hitbox to the crosshair for a given ent +int ClosestHitbox(CachedEntity* target) { // FIXME this will break multithreading if it will be ever implemented. When implementing it, these should be made non-static int closest; float closest_fov, fov; - //If you can see the spine, no need to check for another hitbox - if ((int)hitbox_mode == 0) { - if (target->hitboxes.VisibilityCheck(hitbox_t::spine_1)) return hitbox_t::spine_1; - } closest = -1; closest_fov = 256; for (int i = 0; i < target->hitboxes.GetNumHitboxes(); i++) { @@ -143,266 +769,32 @@ int ClosestHitbox(CachedEntity* target) { return closest; } -static EAimbotLocalState local_state_last; - -void CreateMove() { - - EAimbotLocalState local_state; - float target_highest_score, scr, begincharge, charge; - CachedEntity* ent; - EAimbotTargetState tg; - int huntsman_ticks = 0; - - target_highest = 0; - if (!enabled) { - state = EAimbotState::DISABLED; - return; - } else { - state = EAimbotState::ENABLED; - } - if (engine_predict) RunEnginePrediction(RAW_ENT(LOCAL_E), g_pUserCmd); - local_state = ShouldAim(); - - if (aimbot_debug) { - local_state_last = local_state; - } - - if (local_state != EAimbotLocalState::GOOD) { - state = EAimbotState::INACTIVE; - } else { - state = EAimbotState::ACTIVE; - } - - headonly = false; - - projectile_mode = (GetProjectileData(g_pLocalPlayer->weapon(), cur_proj_speed, cur_proj_grav)); - if (proj_speed) - cur_proj_speed = (float)proj_speed; - if (proj_gravity) - cur_proj_grav = (float)proj_gravity; - // TODO priority modes (FOV, Smart, Distance, etc) - target_highest_score = -256; - { - PROF_SECTION(CM_aimbot_finding_target); - for (int i = 0; i < HIGHEST_ENTITY; i++) { - ent = ENTITY(i); - if (CE_BAD(ent)) continue; - tg = TargetState(ent); - if (tg == EAimbotTargetState::GOOD) { - if (GetWeaponMode() == weaponmode::weapon_melee || (int)priority_mode == 2) { - scr = 4096.0f - calculated_data_array[i].aim_position.DistTo(g_pLocalPlayer->v_Eye); - if (scr > target_highest_score) { - target_highest_score = scr; - target_highest = ent; - } - } else { - switch ((int)priority_mode) { - case 0: { - scr = GetScoreForEntity(ent); - if (scr > target_highest_score) { - target_highest_score = scr; - target_highest = ent; - } - } break; - case 1: { - scr = 360.0f - calculated_data_array[ent->m_IDX].fov; - if (scr > target_highest_score) { - target_highest_score = scr; - target_highest = ent; - } - } break; - case 3: { - scr = 450.0f - ent->m_iHealth; - if (scr > target_highest_score) { - target_highest_score = scr; - target_highest = ent; - } - } - } - } - } else { - if (aimbot_debug) { - if (CE_GOOD(ent)) { - hacks::shared::esp::AddEntityString(ent, format("AIMBOT_STATE: ", static_cast(tg))); - } - } - //if (tg != 26) - // logging::Info("Shouldn't target ent %i %i", ent->m_IDX, tg); - } - } - } - if (huntsman_ticks) { - g_pUserCmd->buttons |= IN_ATTACK; - huntsman_ticks = max(0, huntsman_ticks - 1); - } - - if (CE_GOOD(target_highest)) { - state = EAimbotState::TARGET_FOUND; - hacks::shared::esp::SetEntityColor(target_highest, colors::pink); - if (local_state == EAimbotLocalState::GOOD) { - PROF_SECTION(CM_aimbot_aiming); - last_target = target_highest->m_IDX; - if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFCompoundBow)) { // There is no Huntsman in TF2C. - begincharge = CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flChargeBeginTime); - charge = 0; - if (begincharge != 0) { - charge = g_GlobalVars->curtime - begincharge; - if (charge > 1.0f) charge = 1.0f; - silent_huntsman = true; - } - if (charge >= (float)huntsman_autoshoot) { - g_pUserCmd->buttons &= ~IN_ATTACK; - hacks::shared::antiaim::SetSafeSpace(3); - } else if (autoshoot && huntsman_full_auto) { - huntsman_ticks = 3; - g_pUserCmd->buttons |= IN_ATTACK; - } - if (!(g_pUserCmd->buttons & IN_ATTACK) && silent_huntsman) { - Aim(target_highest); - silent_huntsman = false; - } - } else { - Aim(target_highest); - } - if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFMinigun)) - minigun_fix_ticks = 40; - } - } - if (minigun_fix_ticks > 0) { - minigun_fix_ticks--; - g_pUserCmd->buttons |= IN_ATTACK; - } - if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFMinigun) && - target_highest == 0 && - IDX_GOOD(last_target) && - minigun_fix_ticks && (local_state == EAimbotLocalState::GOOD)) { - Aim(ENTITY(last_target)); - } - if (silent) g_pLocalPlayer->bUseSilentAngles = true; - return; -} - -void Reset() { - last_target = -1; - projectile_mode = false; -} - - -const Vector& PredictEntity(CachedEntity* entity) { - AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; - Vector& result = cd.aim_position; - if (cd.predict_tick == tickcount) return result; - if ((entity->m_Type == ENTITY_PLAYER)) { - if (projectile_mode) { - result = ProjectilePrediction(entity, cd.hitbox, cur_proj_speed, cur_proj_grav, PlayerGravityMod(entity)); - } else { - if (lerp) - result = SimpleLatencyPrediction(entity, cd.hitbox); - else - GetHitbox(entity, cd.hitbox, result); - } - } else if (entity->m_Type == ENTITY_BUILDING) { - result = GetBuildingPosition(entity); - } else { - result = entity->m_vecOrigin; - } - cd.predict_tick = tickcount; - cd.fov = GetFov(g_pLocalPlayer->v_OrigViewangles, g_pLocalPlayer->v_Eye, result); - return result; -} - +// Function to get predicted visual checks bool VischeckPredictedEntity(CachedEntity* entity) { + // Retrieve predicted data AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; + // If vis check data is up-to-date with tick count then return it if (cd.vcheck_tick == tickcount) return cd.visible; + // Reset vis check tick and calculate new vis data cd.vcheck_tick = tickcount; - //if (entity->m_Type == ENTITY_PLAYER) - // cd.visible = IsVectorVisible(g_pLocalPlayer->v_Eye, PredictEntity(entity)); - //else - cd.visible = IsEntityVectorVisible(entity, PredictEntity(entity)); + cd.visible = IsEntityVectorVisible(entity, PredictEntity(entity)); + // Return found check return cd.visible; } -EAimbotTargetState TargetState(CachedEntity* entity) { - float bdmg; - weaponmode mode; - Vector resultAim; - int hitbox; - int team; - - if (entity->m_Type == ENTITY_PLAYER) { - if (entity == LOCAL_E) return EAimbotTargetState::LOCAL; - if (!entity->m_bAlivePlayer) return EAimbotTargetState::DEAD; - if (!entity->m_bEnemy && !teammates) return EAimbotTargetState::TEAMMATE; - if (EffectiveTargetingRange()) { - if (entity->m_flDistance > EffectiveTargetingRange()) return EAimbotTargetState::OUT_OF_RANGE; - } - IF_GAME (IsTF()) { - if (wait_for_charge && g_pLocalPlayer->holding_sniper_rifle) { - bdmg = CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flChargedDamage); - if (g_GlobalVars->curtime - g_pLocalPlayer->flZoomBegin <= 1.0f) bdmg = 50.0f; - if ((bdmg * 3) < (HasDarwins(entity) ? (entity->m_iHealth * 1.15) : entity->m_iHealth)) { - return EAimbotTargetState::NOT_ENOUGH_CHARGE; - } - } - if (ignore_taunting && HasCondition(entity)) return EAimbotTargetState::TAUNTING; - if (IsPlayerInvulnerable(entity)) return EAimbotTargetState::INVULNERABLE; - if (respect_cloak && IsPlayerInvisible(entity)) return EAimbotTargetState::INVISIBLE; - mode = GetWeaponMode(); - if (mode == weaponmode::weapon_hitscan || LOCAL_W->m_iClassID == CL_CLASS(CTFCompoundBow)) - if (respect_vaccinator && HasCondition(entity)) return EAimbotTargetState::VACCINATED; - } - if (playerlist::IsFriendly(playerlist::AccessData(entity).state)) return EAimbotTargetState::FRIENDLY; - IF_GAME (IsTF()) { - if (ignore_hoovy && IsHoovy(entity)) { - return EAimbotTargetState::HOOVY; - } - } - hitbox = BestHitbox(entity); - AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; - cd.hitbox = hitbox; - if (!VischeckPredictedEntity(entity)) return EAimbotTargetState::VCHECK_FAILED; - if ((float)fov > 0.0f && cd.fov > (float)fov) return EAimbotTargetState::FOV_CHECK_FAILED; - return EAimbotTargetState::GOOD; - } else if (entity->m_Type == ENTITY_BUILDING) { - if (!buildings) return EAimbotTargetState::BUILDING_AIMBOT_DISABLED; - team = CE_INT(entity, netvar.iTeamNum); - if (team == g_pLocalPlayer->team) return EAimbotTargetState::TEAMMATE; - if (EffectiveTargetingRange()) { - if (entity->m_flDistance > (int)EffectiveTargetingRange()) return EAimbotTargetState::OUT_OF_RANGE; - } - AimbotCalculatedData_s& cd = calculated_data_array[entity->m_IDX]; - if (!VischeckPredictedEntity(entity)) return EAimbotTargetState::VCHECK_FAILED; - if ((float)fov > 0.0f && cd.fov > (float)fov) return EAimbotTargetState::FOV_CHECK_FAILED; - return EAimbotTargetState::GOOD; - } else { - return EAimbotTargetState::INVALID_ENTITY; - } - return EAimbotTargetState::IMPOSSIBLE_ERROR; -} +// A helper function to find a user angle that isnt directly on the target angle, effectively slowing the aiming process void slowAim(Vector &inputAngle, Vector userAngle) { - //Initialize vars for slow aim + // Initialize vars for slow aim int slowfliptype; int slowdir; - float changey; - float changex; - - /*//Use rand to randomize the change speed - if (slowaim_salting) { - if ((g_GlobalVars->curtime - 0.15F) > saltWait) { - saltWait = g_GlobalVars->curtime; - saltRandom = rand() % 3; - } - }*/ - - //Angle clamping for when the aimbot chooses a too high of value - if (inputAngle.y > 180) inputAngle.y = inputAngle.y - 360; - if (inputAngle.y < -180) inputAngle.y = inputAngle.y + 360; + float changey = 0; + float changex = 0; - //Determine whether to move the mouse at all for the yaw + // Determine whether to move the mouse at all for the yaw if (userAngle.y != inputAngle.y) { - //Fliping The main axis to prevent 360s from happening when the bot trys to cross -180y and 180y + // Fliping The main axis to prevent 360s from happening when the bot trys to cross -180y and 180y slowfliptype = 0; if ( ((inputAngle.y < -90) && (userAngle.y > 90)) && (slowfliptype == 0) ) { slowfliptype = 1; @@ -415,17 +807,17 @@ void slowAim(Vector &inputAngle, Vector userAngle) { userAngle.y = userAngle.y - 90; } - //Math to calculate how much to move the mouse + // Math to calculate how much to move the mouse changey = (std::abs(userAngle.y - inputAngle.y)) / ((int)slowaim_smoothing) ; - //Use stronger shunting due to the flip + // Use stronger shunting due to the flip if (slowfliptype != 0) changey = ((( std::abs(userAngle.y - inputAngle.y) ) / ((int)slowaim_smoothing * (int)slowaim_smoothing)) / (int)slowaim_smoothing) ; - //Determine the direction to move in before reseting the flipped angles + // Determine the direction to move in before reseting the flipped angles slowdir = 0; if ((userAngle.y > inputAngle.y) && (slowdir == 0)) slowdir = 1; if ((userAngle.y < inputAngle.y) && (slowdir == 0)) slowdir = 2; - //Reset Flipped angles and fix directions + // Reset Flipped angles and fix directions if (slowfliptype == 1) { inputAngle.y = inputAngle.y + 90; userAngle.y = userAngle.y - 90; @@ -437,347 +829,206 @@ void slowAim(Vector &inputAngle, Vector userAngle) { slowdir = 1; } - /*//If salted, then randomize the speed here - if (slowaim_salting) { - if (saltRandom == 0) changey = changey - (changey/2); - if (saltRandom == 1) changey = changey - (changey/2.5); - if (saltRandom == 2) changey = changey + (changey/4); - if (saltRandom == 3) changey = changey + (changey/3); - }*/ - - //Move in the direction determined before the fliped angles + // Move in the direction determined before the fliped angles if (slowdir == 1) inputAngle.y = userAngle.y - changey; if (slowdir == 2) inputAngle.y = userAngle.y + changey; } - //Angle clamping for when the aimbot chooses a too high of value, fixes for when players are above your player - if (inputAngle.x > 89) inputAngle.x = inputAngle.x - 360; - - //Determine whether to move the mouse at all for the pitch + // Determine whether to move the mouse at all for the pitch if (userAngle.x != inputAngle.x) { changex = (std::abs(userAngle.x - inputAngle.x)) / ((int)slowaim_smoothing) ; - /*//If salted, then randomize the speed here - if (slowaim_salting) { - if (saltRandom == 0) changex = changex - (changex/2); - if (saltRandom == 1) changex = changex - (changex/2.5); - if (saltRandom == 2) changex = changex + (changex/4); - if (saltRandom == 3) changex = changex + (changex/3); - }*/ - - //Determine the direction to move in + // Determine the direction to move in if (userAngle.x > inputAngle.x) inputAngle.x = userAngle.x - changex; if (userAngle.x < inputAngle.x) inputAngle.x = userAngle.x + changex; } - //Check if can autoshoot with slowaim + // Check if can autoshoot with slowaim slowCanShoot = false; if (changey < (0.02*(int)slowaim_autoshoot) && changex < (0.02*(int)slowaim_autoshoot)) slowCanShoot = true; } -bool Aim(CachedEntity* entity) { - Vector angles, tr; - int hitbox, weapon_class; - bool attack; - static int forbiddenWeapons[] = { CL_CLASS(CTFCompoundBow), CL_CLASS(CTFKnife) }; - - state = EAimbotState::AIMING; - if (CE_BAD(entity)) return false; -/* if (entity->m_Type == ENTITY_PLAYER) { - GetHitbox(entity, hitbox, hit); - if (lerp) SimpleLatencyPrediction(entity, hitbox); - } else if (entity->m_Type == ENTITY_BUILDING) { - hit = GetBuildingPosition(entity); - } - if (projectile_mode) { - hit = ProjectilePrediction(entity, hitbox, cur_proj_speed, cur_proj_grav, PlayerGravityMod(entity)); - }*/ - - tr = (PredictEntity(entity) - g_pLocalPlayer->v_Eye); - VectorAngles(tr, angles); - - //Slow the aiming to the aimpoint if true - if (slowaim && !silent) slowAim(angles, g_pUserCmd->viewangles); - - //Set angles - fClampAngle(angles); - g_pUserCmd->viewangles = angles; - - if (silent) { - g_pLocalPlayer->bUseSilentAngles = true; - } - if (autoshoot) { - IF_GAME (IsTF()) { - if (g_pLocalPlayer->clazz == tf_class::tf_sniper) { - if (g_pLocalPlayer->holding_sniper_rifle) { - if (zoomed_only && !CanHeadshot()) return true; - } - } - } - - // Don't autoshoot with the knife! - weapon_class = g_pLocalPlayer->weapon()->m_iClassID; - attack = true; - for (int i = 0; i < 2; i++) { - if (weapon_class == forbiddenWeapons[i]) { - attack = false; - break; - } - } - //Autoshoot breaks Slow aimbot, so use a workaround to detect when it can - if (slowaim && !slowCanShoot) attack = false; - - if ( attack ) { - g_pUserCmd->buttons |= IN_ATTACK; - } - - //Tell reset conds to function - IF_GAME (IsTF()) { - if (instant_rezoom_enabled) { - if (attack && g_pLocalPlayer->bZoomed && !instant_rezoom_shoot) { - instant_rezoom_shoot = true; - } - } - } - } - return true; -} - -/*Broken Autoshoot delay code -//Ripped from AAAA timer -float autoshoot_timer_start = 0.0f; -float autoshoot_timer = 0.0f; - -void UpdateAutoShootTimer() { - const float& curtime = g_GlobalVars->curtime; - if (autoshoot_timer_start > curtime) autoshoot_timer_start = 0.0f; - if (!autoshoot_timer || !autoshoot_timer_start) { - autoshoot_timer = autoshoot_delay; - autoshoot_timer_start = curtime; - } else { - if (curtime - autoshoot_timer_start > autoshoot_timer) { - cmd->buttons |= IN_ATTACK; - autoshoot_timer_start = curtime; - autoshoot_timer = autoshoot_delay; - } - } -}*/ - +// A function that determins whether aimkey allows aiming bool UpdateAimkey() { static bool aimkey_flip = false; static bool pressed_last_tick = false; bool key_down; + bool allowAimkey = true; + // Check if aimkey is used if (aimkey && aimkey_mode) { + // Grab whether the aimkey is depressed key_down = g_IInputSystem->IsButtonDown((ButtonCode_t)(int)aimkey); - switch (static_cast((int)aimkey_mode)) { - case EAimKeyMode::PRESS_TO_ENABLE: + // Switch based on the user set aimkey mode + switch ((int)aimkey_mode) { + // Only while key is depressed, enable + case 1: if (!key_down) { - state = EAimbotState::INACTIVE; + allowAimkey = false; } break; - case EAimKeyMode::PRESS_TO_DISABLE: + // Only while key is not depressed, enable + case 2: if (key_down) { - state = EAimbotState::INACTIVE; + allowAimkey = false; } break; - case EAimKeyMode::PRESS_TO_TOGGLE: + // Aimkey acts like a toggle switch + case 3: if (!pressed_last_tick && key_down) aimkey_flip = !aimkey_flip; if (!aimkey_flip) { - state = EAimbotState::INACTIVE; + allowAimkey = false; } } pressed_last_tick = key_down; } - return state != EAimbotState::INACTIVE; + // Return whether the aimkey allows aiming + return allowAimkey; } +// A function called at 2 points in the create move function +// First time is when the aimbot Determines if it should aim and autoshoot +// Second time is for when the aimbot determines only when it should aim and always autoshoots +// Using either mode has problems with some weapons so we compramise by using a combo of the 2 +// The point of using this function for 2 uses is to not make duplicate funcs for essentialy the same thing +bool GetCanAim(int mode) { + + // User setting check + switch (mode) { + case 1: // The first check when the aimbot checks if it can aim or shoot + + // If user settings dont allow, Always aim at the point this is called + if (!only_can_shoot) return true; + // Always aim with melee weapons + if (GetWeaponMode() == weaponmode::weapon_melee) return true; + break; + + case 2: // Second check when the aimbot checks if it can aim, and will shoot regardless of the output here + + // dont check if should aim with melee weapons + if (GetWeaponMode() == weaponmode::weapon_melee) return false; + + // At the point this is called, we dont want to check for can shoot if user settings dont allow + if (!only_can_shoot) return false; + } + + // Weapons that should attack continuously + bool using_wep_on_list = + g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFPistol_Scout) || + g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFMinigun) || + g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFSyringeGun) || + g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFSMG) || + g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFRevolver) || + g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFFlameThrower); + + switch (mode) { + case 1: // The first check when the aimbot checks if it can aim or shoot + // If the player isnt using these weaps, then check for can shoot. If the weapon isnt on the list, then we need to check if the player should aim here and return the result + if (!using_wep_on_list) return CanShoot(); + break; + + case 2: // Second check when the aimbot checks if it can aim, and will shoot regardless of the output here + + // Return whether we are using one of the weapons on the list because we want to tell the aimbot that we should check for canshoot + return using_wep_on_list; + } + + // Mode wasnt input correctly, just return true and hope for the best + return true; +} + +// Func to find value of how far to target ents float EffectiveTargetingRange() { + // Melees use a close range, TODO add dynamic range for demoknight swords if (GetWeaponMode() == weapon_melee) { return 100.0f; + // Pyros only have so much untill their flames hit + } else if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFFlameThrower)) { + return 185.0f; } + // Else return user settings return (float)max_range; } - -float EffectiveShootingRange() { - return 0.0f; + +// A function used by gui elements to determine the current target +CachedEntity* CurrentTarget() { + // If a target is found return it + if (foundTarget) + return ENTITY(target_eid); + // Else return a nullpointer + return nullptr; +} + +// Used for when you join and leave maps to reset aimbot vars +void Reset() { + target_last = nullptr; + projectile_mode = false; } -EAimbotLocalState ShouldAim() { - PROF_SECTION(CM_aimbot_calc_localstate); +#ifndef TEXTMODE - bool do_minigun_checks; - int weapon_state; - // Checks should be in order: cheap -> expensive - if (attack_only && !(g_pUserCmd->buttons & IN_ATTACK)) { - return EAimbotLocalState::NOT_ATTACKING; - } - if (g_pUserCmd->buttons & IN_USE) return EAimbotLocalState::USE_BUTTON; - if (g_pLocalPlayer->using_action_slot_item) return EAimbotLocalState::ACTION_SLOT_ITEM; - if (!UpdateAimkey()) return EAimbotLocalState::AIMKEY_RELEASED; - IF_GAME (IsTF2()) { - if (CE_BYTE(g_pLocalPlayer->entity, netvar.m_bCarryingObject)) return EAimbotLocalState::CARRYING_BUILDING; - if (CE_BYTE(g_pLocalPlayer->entity, netvar.m_bFeignDeathReady)) return EAimbotLocalState::DEAD_RINGER_OUT; - if (zoomed_only && g_pLocalPlayer->holding_sniper_rifle) { - if (!g_pLocalPlayer->bZoomed && !(g_pUserCmd->buttons & IN_ATTACK)) return EAimbotLocalState::NOT_ZOOMED; - } - if (HasCondition(g_pLocalPlayer->entity)) return EAimbotLocalState::TAUNTING; - if (IsPlayerInvisible(g_pLocalPlayer->entity)) return EAimbotLocalState::CLOAKED; - if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFPipebombLauncher)) return EAimbotLocalState::DISABLED_FOR_THIS_WEAPON; - } - if (only_can_shoot) { - // Miniguns should shoot and aim continiously. TODO smg - if (g_pLocalPlayer->weapon()->m_iClassID != CL_CLASS(CTFMinigun)) { - // Melees are weird, they should aim continiously like miniguns too. - if (GetWeaponMode() != weaponmode::weapon_melee) { - // Finally, CanShoot() check. - if (!CanShoot()) return EAimbotLocalState::CANT_SHOOT; - } - } - } - IF_GAME (IsTF2()) { - switch (GetWeaponMode()) { - case weapon_hitscan: - case weapon_melee: - break; - case weapon_projectile: - if (!projectile_aimbot) return EAimbotLocalState::DISABLED_FOR_THIS_WEAPON; - break; - default: - return EAimbotLocalState::DISABLED_FOR_THIS_WEAPON; - }; - } - IF_GAME (IsTF()) { - if (g_pLocalPlayer->bZoomed) { - if (!(g_pUserCmd->buttons & (IN_ATTACK | IN_ATTACK2))) { - if (!CanHeadshot()) return EAimbotLocalState::SNIPER_RIFLE_DELAY; - } - } - } - IF_GAME (IsTF2()) { - if (!AmbassadorCanHeadshot()) return EAimbotLocalState::AMBASSADOR_COOLDOWN; - } - do_minigun_checks = true; -#ifdef IPC_ENABLED - if (hacks::shared::followbot::bot) { - CachedEntity* player = ENTITY(hacks::shared::followbot::following_idx); - if (CE_GOOD(player)) { - if (HasCondition(player)) { - do_minigun_checks = false; - } - } - } -#endif - IF_GAME (IsTF()) { - if (do_minigun_checks && g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFMinigun)) { - weapon_state = CE_INT(g_pLocalPlayer->weapon(), netvar.iWeaponState); - if ((weapon_state == MinigunState_t::AC_STATE_IDLE || weapon_state == MinigunState_t::AC_STATE_STARTFIRING) && !auto_spin_up) { - return EAimbotLocalState::MINIGUN_IDLE; - } - if (!(g_pUserCmd->buttons & (IN_ATTACK2 | IN_ATTACK))) { - return EAimbotLocalState::MINIGUN_BUTTON_RELEASED; - } - // This doesn't belong here - /*if (minigun_fix_ticks > 0) { - minigun_fix_ticks--; - cmd->buttons |= IN_ATTACK; - }*/ - } - if (!AllowAttacking()) - return EAimbotLocalState::CRIT_HACK_LOCKS_ATTACK; - } - return EAimbotLocalState::GOOD; -} - -void PaintTraverse() { - if (!aimbot_debug) return; +// Function called when we need to draw to screen +static CatVar fov_draw(CV_SWITCH, "aimbot_fov_draw", "0", "Draw Fov Ring", "Draws a ring to represent your current aimbot fov"); +void DrawText() { + // Dont draw to screen when aimbot is disabled if (!enabled) return; - AddSideString(format("AimbotState: ", static_cast(local_state_last))); -} + + // Fov ring to represent when a target will be shot + // Not perfect but does a good job of representing where its supposed to be + // Broken from kathook merge, TODO needs to be adapted for imgui + if (fov_draw) { + // It cant use fovs greater than 180, so we check for that + if (float(fov) > 0.0f && float(fov) < 180) { + // Dont show ring while player is dead + if (LOCAL_E->m_bAlivePlayer) { + rgba_t color = GUIColor(); + color.a = float(fovcircle_opacity); -int BestHitbox(CachedEntity* target) { - PROF_SECTION(CM_aimbot_besthitbox); + // Grab the screen resolution and save to some vars + int width, height; + g_IEngine->GetScreenSize(width, height); + + // Some math to find radius of the fov circle + float mon_fov = (float(width) / float(height) / (4.0f / 3.0f)); + float fov_real = RAD2DEG(2 * atanf(mon_fov * tanf(DEG2RAD(draw::fov / 2)))); - int preferred, ci, flags, bdmg; - float cdmg, bodmg; - bool ground; - preferred = hitbox; - switch ((int)hitbox_mode) { - case 0: { // AUTO-HEAD - ci = g_pLocalPlayer->weapon()->m_iClassID; - IF_GAME (IsTF()) { - preferred = hitbox_t::pelvis; - if (g_pLocalPlayer->holding_sniper_rifle) { - headonly = CanHeadshot(); - } else if (ci == CL_CLASS(CTFCompoundBow)) { - headonly = true; - } else if (IsAmbassador(g_pLocalPlayer->weapon())) { - headonly = true; - } else if (ci == CL_CLASS(CTFRocketLauncher) || - ci == CL_CLASS(CTFRocketLauncher_AirStrike) || - ci == CL_CLASS(CTFRocketLauncher_DirectHit) || - ci == CL_CLASS(CTFRocketLauncher_Mortar)) { - preferred = hitbox_t::hip_L; - } - flags = CE_INT(target, netvar.iFlags); - ground = (flags & (1 << 0)); - if (!ground) { - if (GetWeaponMode() == weaponmode::weapon_projectile) { - if (g_pLocalPlayer->weapon()->m_iClassID != CL_CLASS(CTFCompoundBow)) { - preferred = hitbox_t::spine_3; + float radius = tan(DEG2RAD(float(fov)) / 2) / tan(DEG2RAD(fov_real) / 2) * (width); + + // Draw a circle with our newfound circle + float px = 0; + float py = 0; + constexpr float steps = 120; + for (int i = 0; i < steps; i++) { + float ang = 2 * PI * (float(i) / steps); + float x = width / 2 + radius * cos(ang); + float y = height / 2 + radius * sin(ang); + if (!i) { + ang = 2 * PI * (float(steps - 1) / steps); + px = width / 2 + radius * cos(ang); + py = height / 2 + radius * sin(ang); } + drawgl::Line(px, py, x - px, y - py, color); + px = x; + py = y; } } - if (g_pLocalPlayer->holding_sniper_rifle) { - cdmg = CE_FLOAT(LOCAL_W, netvar.flChargedDamage); - bodmg = 50; - //Darwins damage correction - if (target->m_iMaxHealth == 150 && target->m_iClassID == tf_sniper) { - bodmg = (bodmg * .85) - 1; - cdmg = (cdmg * .85) - 1; - } - //Vaccinator damage correction - if (HasCondition(target)) { - bodmg = (bodmg * .25) - 1; - cdmg = (cdmg * .25) - 1; - } else if (HasCondition(target)) { - bodmg = (bodmg * .90) - 1; - cdmg = (cdmg * .90) - 1; - } - //Invis damage correction - if (IsPlayerInvisible(target)) { - bodmg = (bodmg * .80) - 1; - cdmg = (cdmg * .80) - 1; - } - //If can headshot and if bodyshot kill from charge damage, or if crit boosted and they have 150 health, or if player isnt zoomed, or if the enemy has less than 40, due to darwins, and only if they have less than 150 health will it try to bodyshot - if (CanHeadshot() && (cdmg >= target->m_iHealth || IsPlayerCritBoosted(g_pLocalPlayer->entity) || !g_pLocalPlayer->bZoomed || target->m_iHealth <= bodmg) && target->m_iHealth <= 150) { - preferred = ClosestHitbox(target); - headonly = false; - } + } + } + // Dont run the following unless debug is enabled + if (!aimbot_debug) return; + for (int i = 1; i < 32; i++) { + CachedEntity* ent = ENTITY(i); + if (CE_GOOD(ent)) { + Vector screen; + Vector oscreen; + if (draw::WorldToScreen(calculated_data_array[i].aim_position, screen) && draw::WorldToScreen(ent->m_vecOrigin, oscreen)) { + drawgl::FilledRect(screen.x - 2, screen.y - 2, 4, 4); + drawgl::Line(oscreen.x, oscreen.y, screen.x - oscreen.x, screen.y - oscreen.y); } - } else IF_GAME (IsCSS()) { - headonly = true; } - if (headonly) { - IF_GAME (IsTF()) - return hitbox_t::head; - IF_GAME (IsCSS()) - return 12; - } - if (target->hitboxes.VisibilityCheck(preferred)) return preferred; - for (int i = projectile_mode ? 1 : 0; i < target->hitboxes.GetNumHitboxes(); i++) { - if (target->hitboxes.VisibilityCheck(i)) return i; - } - } break; - case 1: { // AUTO-CLOSEST - return ClosestHitbox(target); - } break; - case 2: { // STATIC - return (int)hitbox; - } break; } - return -1; } +#endif + }}} - diff --git a/src/hacks/Aimbot.h b/src/hacks/Aimbot.h index 5a070579..84c8824e 100644 --- a/src/hacks/Aimbot.h +++ b/src/hacks/Aimbot.h @@ -15,98 +15,50 @@ class IClientEntity; namespace hacks { namespace shared { namespace aimbot { -enum class EAimbotState { - DISABLED, // Aimbot is disabled completely. - ENABLED, // Aimbot is enabled, but other checks weren't performed yet - INACTIVE, // Aimkey isn't down, minigun isn't spun up, you are dead, etc. - ACTIVE, // Aimbot is enabled and active, but target isn't found yet. - TARGET_FOUND, // Target is found, but you aren't aiming yet. - AIMING // Aimbot is messing with your UserCmd -}; - - -enum class EAimKeyMode { - DISABLED, - PRESS_TO_ENABLE, - PRESS_TO_DISABLE, - PRESS_TO_TOGGLE -}; - -enum class EAimbotLocalState { - // Aimbot can activate - GOOD = 0, - // Aimbot won't activate - AIMKEY_RELEASED, - TAUNTING, // Local player is taunting - CLOAKED, // Local player is cloaked, you can't shoot - DEAD_RINGER_OUT, // You can't shoot with DR out - USE_BUTTON, // You are holding use button - ACTION_SLOT_ITEM, // You are using cat_use_action_slot_item_server (Grappling Hook) - CARRYING_BUILDING, // You are carrying a building - NOT_ZOOMED, // Zoomed only is enabled and player isn't zoomed in (ignored if attacking) - CANT_SHOOT, - MINIGUN_IDLE, // Minigun is idle - MINIGUN_BUTTON_RELEASED, // Mouse not pressed - AMBASSADOR_COOLDOWN, - SNIPER_RIFLE_DELAY, - CRIT_HACK_LOCKS_ATTACK, - DISABLED_FOR_THIS_WEAPON, // You are holding Jarate/PDA/something like that - NOT_ATTACKING // Attack Only is enabled, but mouse1 isn't held -}; - -enum class EAimbotTargetState { - // Target is valid, aimbot can aim at it - GOOD = 0, - // Aimbot won't aim at the target - LOCAL, // Aimbot shouldn't aim at local player - TAUNTING, - FRIENDLY, // Managed by playerlist - HOOVY, - NOT_ENOUGH_CHARGE, - INVULNERABLE, - INVISIBLE, - VACCINATED, - DEAD, - TEAMMATE, - OUT_OF_RANGE, - HITBOX_ERROR, - VCHECK_FAILED, - FOV_CHECK_FAILED, - BUILDING_AIMBOT_DISABLED, - INVALID_ENTITY, - IMPOSSIBLE_ERROR -}; - +// Used to store aimbot data to prevent calculating it again struct AimbotCalculatedData_s { - unsigned long predict_tick { 0.0f }; + unsigned long predict_tick { 0 }; Vector aim_position { 0 }; unsigned long vcheck_tick { 0 }; bool visible { false }; float fov { 0 }; int hitbox { 0 }; }; - + +// Functions used to calculate aimbot data, and if already calculated use it const Vector& PredictEntity(CachedEntity* entity); bool VischeckPredictedEntity(CachedEntity* entity); + +// Variable used to tell when the aimbot has found a target +extern bool foundTarget; + +// Used by esp to set their color +extern int target_eid; + + +// Functions called by other functions for when certian game calls are run void CreateMove(); -void PaintTraverse(); +#ifndef TEXTMODE +void DrawText(); +#endif void Reset(); -extern EAimbotState state; -extern int target_eid; -extern bool instant_rezoom_shoot; - -float EffectiveTargetingRange(); -float EffectiveShootingRange(); - -bool UpdateAimkey(); +// Stuff to make storing functions easy CachedEntity* CurrentTarget(); -EAimbotTargetState TargetState(CachedEntity* entity); -bool Aim(CachedEntity* entity); -EAimbotLocalState ShouldAim(); +bool ShouldAim(); +CachedEntity* RetrieveBestTarget(bool aimkey_state); +bool IsTargetStateGood(CachedEntity* entity); +void Aim(CachedEntity* entity); +bool CanAutoShoot(); int BestHitbox(CachedEntity* target); +int ClosestHitbox(CachedEntity* target); +void slowAim(Vector &inputAngle, Vector userAngle); +bool UpdateAimkey(); +bool GetCanAim(int mode); +float EffectiveTargetingRange(); }}} #endif /* HAIMBOT_H_ */ + diff --git a/src/hacks/AntiAim.cpp b/src/hacks/AntiAim.cpp index 120670e6..0fb64933 100644 --- a/src/hacks/AntiAim.cpp +++ b/src/hacks/AntiAim.cpp @@ -16,7 +16,7 @@ CatVar enabled(CV_SWITCH, "aa_enabled", "0", "Anti-Aim", "Master AntiAim switch" CatVar yaw(CV_FLOAT, "aa_yaw", "0.0", "Yaw", "Static yaw (left/right)", 360.0); CatVar pitch(CV_FLOAT, "aa_pitch", "-89.0", "Pitch", "Static pitch (up/down)", -89.0, 89.0); CatEnum yaw_mode_enum({ "KEEP", "STATIC", "JITTER", "BIGRANDOM", "RANDOM", "SPIN", "OFFSETKEEP", "EDGE", "HECK" }); -CatEnum pitch_mode_enum({ "KEEP", "STATIC", "JITTER", "RANDOM", "FLIP", "FAKEFLIP", "FAKEUP", "FAKEDOWN", "UP", "DOWN", "HECK" }); +CatEnum pitch_mode_enum({ "KEEP", "STATIC", "JITTER", "RANDOM", "FLIP", "FAKEFLIP", "FAKEUP", "FAKEDOWN", "FAKECENTER", "UP", "DOWN", "HECK" }); CatVar yaw_mode(yaw_mode_enum, "aa_yaw_mode", "0", "Yaw mode", "Yaw mode"); CatVar pitch_mode(pitch_mode_enum, "aa_pitch_mode", "0", "Pitch mode", "Pitch mode"); CatVar roll(CV_FLOAT, "aa_roll", "0", "Roll", "Roll angle (viewangles.z)", -180, 180); @@ -345,12 +345,16 @@ void ProcessUserCmd(CUserCmd* cmd) { clamp = false; break; case 8: - p = -89.0f; + p = -3256.0f; + clamp = false; break; case 9: - p = 89.0f; + p = -89.0f; break; case 10: + p = 89.0f; + break; + case 11: FuckPitch(p); clamp = false; } diff --git a/src/hacks/AntiCheat.cpp b/src/hacks/AntiCheat.cpp new file mode 100644 index 00000000..4fa53787 --- /dev/null +++ b/src/hacks/AntiCheat.cpp @@ -0,0 +1,93 @@ +/* + * AntiCheat.cpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#include "AntiCheat.hpp" +#include "../common.h" + +#include "../hack.h" + +#include "ac/aimbot.hpp" +#include "ac/antiaim.hpp" +#include "ac/removecond.hpp" +#include "ac/bhop.hpp" + +namespace hacks { namespace shared { namespace anticheat { + +static CatVar enabled(CV_SWITCH, "ac_enabled", "0", "Enable AC"); +static CatVar accuse_chat(CV_SWITCH, "ac_chat", "0", "Accuse in chat"); + +void Accuse(int eid, const std::string& hack, const std::string& details) { + player_info_s info; + if (g_IEngine->GetPlayerInfo(eid, &info)) { + CachedEntity* ent = ENTITY(eid); + if (accuse_chat) { + hack::command_stack().push(format("say \"", info.name, " (", classname(CE_INT(ent, netvar.iClass)), ") suspected ", hack, ": ", details,"\"")); + } else { + PrintChat("\x07%06X%s\x01 (%s) suspected \x07%06X%s\x01: %s", colors::chat::team(ENTITY(eid)->m_iTeam), info.name, classname(CE_INT(ent, netvar.iClass)), 0xe05938, hack.c_str(), details.c_str()); + } + } +} + +static CatVar skip_local(CV_SWITCH, "ac_ignore_local", "1", "Ignore Local"); + +void CreateMove() { + if (!enabled) return; + for (int i = 1; i < 33; i++) { + if (skip_local && (i == g_IEngine->GetLocalPlayer())) continue; + CachedEntity* ent = ENTITY(i); + if (CE_GOOD(ent)) { + if ((CE_BYTE(ent, netvar.iLifeState) == 0)) { + ac::aimbot::Update(ent); + ac::antiaim::Update(ent); + ac::bhop::Update(ent); + } + } + ac::removecond::Update(ent); + } +} + +void ResetPlayer(int index) { + ac::aimbot::ResetPlayer(index); + ac::antiaim::ResetPlayer(index); + ac::bhop::ResetPlayer(index); + ac::removecond::ResetPlayer(index); +} + +void ResetEverything() { + ac::aimbot::ResetEverything(); + ac::antiaim::ResetEverything(); + ac::bhop::ResetEverything(); + ac::removecond::ResetEverything(); +} + +class ACListener : public IGameEventListener { +public: + virtual void FireGameEvent(KeyValues* event) { + if (!enabled) return; + std::string name(event->GetName()); + if (name == "player_activate") { + int uid = event->GetInt("userid"); + int entity = g_IEngine->GetPlayerForUserID(uid); + ResetPlayer(entity); + } else if (name == "player_disconnect") { + int uid = event->GetInt("userid"); + int entity = g_IEngine->GetPlayerForUserID(uid); + ResetPlayer(entity); + } + + ac::aimbot::Event(event); + } +}; + +ACListener listener; + +void Init() { + // FIXME free listener + g_IGameEventManager->AddListener(&listener, false); +} + +}}} diff --git a/src/hacks/AntiCheat.hpp b/src/hacks/AntiCheat.hpp new file mode 100644 index 00000000..46f02fc9 --- /dev/null +++ b/src/hacks/AntiCheat.hpp @@ -0,0 +1,25 @@ +/* + * AntiCheat.hpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + + +#pragma once + +#include "../beforecheaders.h" +#include +#include "../aftercheaders.h" + +namespace hacks { namespace shared { namespace anticheat { + +void Accuse(int eid, const std::string& hack, const std::string& details); + +void Init(); +void CreateMove(); + +void ResetPlayer(int index); +void ResetEverything(); + +}}} diff --git a/src/hacks/AntiDisguise.h b/src/hacks/AntiDisguise.h index f67bc0b3..8c8017a1 100644 --- a/src/hacks/AntiDisguise.h +++ b/src/hacks/AntiDisguise.h @@ -8,7 +8,7 @@ #ifndef HACKS_ANTIDISGUISE_H_ #define HACKS_ANTIDISGUISE_H_ -#include "IHack.h" +#include "../common.h" namespace hacks { namespace tf2 { namespace antidisguise { diff --git a/src/hacks/AutoBackstab.cpp b/src/hacks/AutoBackstab.cpp index a36858c9..ea55bce7 100644 --- a/src/hacks/AutoBackstab.cpp +++ b/src/hacks/AutoBackstab.cpp @@ -6,45 +6,33 @@ */ #include "../common.h" +#include "../copypasted/CSignature.h" namespace hacks { namespace tf2 { namespace autobackstab { static CatVar enabled(CV_SWITCH, "autobackstab", "0", "Auto Backstab", "Does not depend on triggerbot!"); -/*float GetAngle(CachedEntity* target) { - const Vector& A = target->m_vecOrigin; - const Vector& B = LOCAL_E->m_vecOrigin; - const float yaw = CE_FLOAT(target, netvar.m_angEyeAngles + 4); - const Vector diff = (A - B); - float yaw2 = acos(diff.x / diff.Length()) * 180.0f / PI; - if (diff.y < 0) yaw2 = -yaw2; - float anglediff = yaw - yaw2; - if (anglediff > 180) anglediff -= 360; - if (anglediff < -180) anglediff += 360; - //logging::Info("Angle: %.2f | %.2f | %.2f | %.2f", yaw, yaw2, anglediff, yaw - yaw2); - return anglediff; -}*/ - // TODO improve void CreateMove() { - // lmao thanks valve if (!enabled) return; if (g_pLocalPlayer->weapon()->m_iClassID != CL_CLASS(CTFKnife)) return; - if (CE_BYTE(g_pLocalPlayer->weapon(), netvar.m_bReadyToBackstab)) { - g_pUserCmd->buttons |= IN_ATTACK; - return; - } + trace_t trace; + IClientEntity* weapon = RAW_ENT(LOCAL_W); - /*if (g_pLocalPlayer->weapon()->m_iClassID != CL_CLASS(CTFKnife)) return; - for (int i = 1; i < g_IEntityList->GetHighestEntityIndex() && i < 32; i++) { - CachedEntity* ent = ENTITY(i); - if (CE_BAD(ent)) continue; - if (!ent->m_bEnemy) continue; - if (CE_BYTE(ent, netvar.iLifeState) != LIFE_ALIVE) continue; - if (IsPlayerInvulnerable(ent)) continue; - if (ent->m_flDistance > 75) continue; - if (fabs(GetAngle(ent)) < 100) g_pUserCmd->buttons |= IN_ATTACK; - }*/ + typedef bool(*IsBehindAndFacingTarget_t)(IClientEntity*, IClientEntity*); + static auto IsBehindAndFacingTarget_addr = gSignatures.GetClientSignature("55 89 E5 57 56 53 83 EC 5C 8B 45 08 8B 75 0C 89 04 24 E8 ? ? ? ? 85 C0 89 C3 74 0F 8B 00 89 1C 24 FF 90 E0 02 00 00 84 C0"); + static auto IsBehindAndFacingTarget = reinterpret_cast(IsBehindAndFacingTarget_addr); + + // 515 = DoSwingTrace + // FIXME offset + if (vfunc(weapon, 515)(weapon, &trace)) { + if (trace.m_pEnt && reinterpret_cast(trace.m_pEnt)->GetClientClass()->m_ClassID == RCC_PLAYER) { + if (NET_INT(trace.m_pEnt, netvar.iTeamNum) != g_pLocalPlayer->team) { + if (IsBehindAndFacingTarget(weapon, reinterpret_cast(trace.m_pEnt))) + g_pUserCmd->buttons |= IN_ATTACK; + } + } + } } }}} diff --git a/src/hacks/AutoHeal.cpp b/src/hacks/AutoHeal.cpp index 16c46a4d..6e6a95b6 100644 --- a/src/hacks/AutoHeal.cpp +++ b/src/hacks/AutoHeal.cpp @@ -305,9 +305,15 @@ void CreateMove() { CachedEntity* target = ENTITY(m_iCurrentHealingTarget); Vector out; GetHitbox(target, 7, out); + AimAt(g_pLocalPlayer->v_Eye, out, g_pUserCmd); if (silent) g_pLocalPlayer->bUseSilentAngles = true; if (!m_iNewTarget && (g_GlobalVars->tickcount % 300)) g_pUserCmd->buttons |= IN_ATTACK; + /*if (m_iNewTarget || !(g_GlobalVars->tickcount % 300)) { + if (silent) g_pLocalPlayer->bUseSilentAngles = true; + AimAt(g_pLocalPlayer->v_Eye, out, g_pUserCmd); + g_pUserCmd->buttons |= IN_ATTACK; + }*/ if (IsVaccinator() && CE_GOOD(target) && auto_vacc) { int opt = OptimalResistance(target, &pop); if (!pop && opt != -1) SetResistance(opt); diff --git a/src/hacks/AutoHeal.h b/src/hacks/AutoHeal.h index f49e70ac..dd0eceab 100644 --- a/src/hacks/AutoHeal.h +++ b/src/hacks/AutoHeal.h @@ -8,8 +8,6 @@ #ifndef HACKS_AUTOHEAL_H_ #define HACKS_AUTOHEAL_H_ -#include "IHack.h" - #include "../common.h" namespace hacks { namespace tf { namespace autoheal { diff --git a/src/hacks/AutoJoin.cpp b/src/hacks/AutoJoin.cpp new file mode 100644 index 00000000..9ba6db3c --- /dev/null +++ b/src/hacks/AutoJoin.cpp @@ -0,0 +1,88 @@ +/* + * AutoJoin.cpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#include "../common.h" +#include "../hack.h" +#include "../copypasted/CSignature.h" + +namespace hacks { namespace shared { namespace autojoin { + +/* + * Credits to Blackfire for helping me with auto-requeue! + */ + +CatEnum classes_enum({ "DISABLED", "SCOUT", "SNIPER", "SOLDIER", "DEMOMAN", "MEDIC", "HEAVY", "PYRO", "SPY", "ENGINEER" }); +CatVar autojoin_team(CV_SWITCH, "autojoin_team", "0", "AutoJoin", "Automatically joins a team"); +CatVar preferred_class(classes_enum, "autojoin_class", "0", "AutoJoin class", "You will pick a class automatically"); + +CatVar auto_queue(CV_SWITCH, "autoqueue", "0", "AutoQueue", "Automatically queue in casual matches"); + +const std::string classnames[] = { + "scout", "sniper", "soldier", "demoman", "medic", "heavyweapons", "pyro", "spy", "engineer" +}; + +CatCommand debug_startsearch("debug_startsearch", "DEBUG StartSearch", []() { + logging::Info("%d", g_TFGCClientSystem->RequestSelectWizardStep(4)); +}); +CatCommand debug_casual("debug_casual", "DEBUG Casual", []() { + g_IEngine->ExecuteClientCmd("OpenMatchmakingLobby casual"); + g_TFGCClientSystem->LoadSearchCriteria(); + //logging::Info("%d", g_TFGCClientSystem->RequestSelectWizardStep(6)); +}); + +CatCommand debug_readytosearch("debug_gcstate", "DEBUG GCState", []() { + logging::Info("%d", g_TFGCClientSystem->GetState()); +}); +CatCommand debug_abandon("debug_abandon", "DEBUG Abandon", []() { + g_TFGCClientSystem->SendExitMatchmaking(true); +}); +bool UnassignedTeam() { + return !g_pLocalPlayer->team or (g_pLocalPlayer->team == TEAM_SPEC); +} + +bool UnassignedClass() { + return g_pLocalPlayer->clazz != int(preferred_class); +} + +void UpdateSearch() { + if (!auto_queue) return; + if (g_IEngine->IsInGame()) return; + static auto last_check = std::chrono::system_clock::now(); + auto s = std::chrono::duration_cast(std::chrono::system_clock::now() - last_check).count(); + if (s < 4) return; + + if (g_TFGCClientSystem->GetState() == 6) { + logging::Info("Sending MM request"); + g_TFGCClientSystem->RequestSelectWizardStep(4); + } else if (g_TFGCClientSystem->GetState() == 5) { + g_IEngine->ExecuteClientCmd("OpenMatchmakingLobby casual"); + g_TFGCClientSystem->LoadSearchCriteria(); + //logging::Info("%d", g_TFGCClientSystem->RequestSelectWizardStep(6)); + } + + last_check = std::chrono::system_clock::now(); +} + +void Update() { + static auto last_check = std::chrono::system_clock::now(); + auto ms = std::chrono::duration_cast(std::chrono::system_clock::now() - last_check).count(); + + if (ms < 500) { + return; + } + + if (autojoin_team and UnassignedTeam()) { + hack::ExecuteCommand("jointeam auto"); + } else if (preferred_class and UnassignedClass()) { + if (int(preferred_class) < 10) + g_IEngine->ExecuteClientCmd(format("join_class ", classnames[int(preferred_class) - 1]).c_str()); + } + + last_check = std::chrono::system_clock::now(); +} + +}}} diff --git a/src/hacks/AutoJoin.hpp b/src/hacks/AutoJoin.hpp new file mode 100644 index 00000000..8bab3d30 --- /dev/null +++ b/src/hacks/AutoJoin.hpp @@ -0,0 +1,15 @@ +/* + * AutoJoin.hpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#pragma once + +namespace hacks { namespace shared { namespace autojoin { + +void Update(); +void UpdateSearch(); + +}}} diff --git a/src/hacks/AutoReflect.cpp b/src/hacks/AutoReflect.cpp index aeb7ec36..62c412d6 100644 --- a/src/hacks/AutoReflect.cpp +++ b/src/hacks/AutoReflect.cpp @@ -12,56 +12,135 @@ namespace hacks { namespace tf { namespace autoreflect { -CatVar enabled(CV_SWITCH, "reflect_enabled", "0", "AutoReflect", "Master AutoReflect switch"); +// Vars for user settings +CatVar enabled(CV_SWITCH, "reflect_enabled", "0", "Auto Reflect", "Master AutoReflect switch"); CatVar idle_only(CV_SWITCH, "reflect_only_idle", "0", "Only when not shooting", "Don't AutoReflect if you're holding M1"); +CatVar legit(CV_SWITCH, "reflect_legit", "0", "Legit Reflect", "Only Auto-airblasts projectiles that you can see, doesnt move your crosshair"); +CatVar dodgeball(CV_SWITCH, "reflect_dodgeball", "0", "Dodgeball Mode", "Allows auto-reflect to work in dodgeball servers"); +CatVar blastkey(CV_KEY, "reflect_key", "0", "Reflect Key", "Hold this key to activate auto-airblast"); CatVar stickies(CV_SWITCH, "reflect_stickybombs", "0", "Reflect stickies", "Reflect Stickybombs"); -CatVar max_distance(CV_INT, "reflect_distance", "200", "Distance", "Maximum distance to reflect at", true, 300.0f); +// TODO setup proj sorting +// TODO CatVar big_proj(CV_SWITCH, "reflect_big_projectile", "0", "Reflect big projectiles", "Reflect Rockets"); +// TODO CatVar small_proj(CV_SWITCH, "reflect_small_projectile", "0", "Reflect small projectiles", "Reflect Huntsman arrows, Crusaders bolts"); +// TODO CatVar misc_proj(CV_SWITCH, "reflect_misc_projectile", "0", "Reflect other", "Reflect jarate, milk"); + +// Function called by game for movement void CreateMove() { + // Check if user settings allow Auto Reflect if (!enabled) return; + if (blastkey && !blastkey.KeyDown()) return; + + // Check if player is using a flame thrower if (g_pLocalPlayer->weapon()->m_iClassID != CL_CLASS(CTFFlameThrower)) return; + + // Check for phlogistinator, which is item 594 + if (HasWeapon(LOCAL_E, 594)) return; + + // If user settings allow, return if local player is in attack if (idle_only && (g_pUserCmd->buttons & IN_ATTACK)) return; - CachedEntity* closest = 0; + // Create some book-keeping vars float closest_dist = 0.0f; + Vector closest_vec; + // Loop to find the closest entity for (int i = 0; i < HIGHEST_ENTITY; i++) { + + // Find an ent from the for loops current tick CachedEntity* ent = ENTITY(i); + + // Check if null or dormant if (CE_BAD(ent)) continue; + + // Check if ent should be reflected if (!ShouldReflect(ent)) continue; - //if (ent->Var(eoffsets.vVelocity).IsZero(1.0f)) continue; - float dist = ent->m_vecOrigin.DistToSqr(g_pLocalPlayer->v_Origin); - if (dist < closest_dist || !closest) { - closest = ent; + + // Some extrapolating due to reflect timing being latency based + // Grab latency + float latency = g_IEngine->GetNetChannelInfo()->GetLatency(FLOW_INCOMING) + g_IEngine->GetNetChannelInfo()->GetLatency(FLOW_OUTGOING); + // Create a vector variable to store our velocity + Vector velocity; + // Grab Velocity of projectile + velocity::EstimateAbsVelocity(RAW_ENT(ent), velocity); + // Predict a vector for where the projectile will be + Vector predicted_proj = ent->m_vecOrigin + (velocity * latency);; + + // Dont vischeck if ent is stickybomb or if dodgeball mode is enabled + if (!IsEntStickyBomb(ent) && !dodgeball) { + // Vis check the predicted vector + if (!IsVectorVisible(g_pLocalPlayer->v_Origin, predicted_proj)) continue; + } /*else { + // Stickys are weird, we use a different way to vis check them + // Vis checking stickys are wonky, I quit, just ignore the check >_> + //if (!VisCheckEntFromEnt(ent, LOCAL_E)) continue; + }*/ + + // Calculate distance + float dist = predicted_proj.DistToSqr(g_pLocalPlayer->v_Origin); + + // If legit mode is on, we check to see if reflecting will work if we dont aim at the projectile + if (legit) { + if (GetFov(g_pLocalPlayer->v_OrigViewangles, g_pLocalPlayer->v_Eye, predicted_proj) > 85.0f) continue; + } + + // Compare our info to the others and determine if its the best, if we dont have a projectile already, then we save it here + if (dist < closest_dist || closest_dist == 0.0f) { closest_dist = dist; + closest_vec = predicted_proj; } } - if (CE_BAD(closest)) return; - if (closest_dist == 0 || closest_dist > SQR((int)max_distance)) return; - Vector tr = (closest->m_vecOrigin - g_pLocalPlayer->v_Eye); - Vector angles; - VectorAngles(tr, angles); - fClampAngle(angles); - g_pUserCmd->viewangles = angles; - g_pLocalPlayer->bUseSilentAngles = true; + // Determine whether the closest projectile is whithin our parameters, preferably 185 units should be our limit, sqr is around the number below + if (closest_dist == 0 || closest_dist > 34400) return; + + // We dont want to aim if legit is true + if (!legit) { + // Aim at predicted projectile + AimAt(g_pLocalPlayer->v_Eye, closest_vec, g_pUserCmd); + // Use silent angles + g_pLocalPlayer->bUseSilentAngles = true; + } + + // Airblast g_pUserCmd->buttons |= IN_ATTACK2; + + // Function is finished, return return; } +// Function to determine whether an ent is good to reflect bool ShouldReflect(CachedEntity* ent) { - if (CE_BAD(ent)) return false; + // Check if the entity is a projectile if (ent->m_Type != ENTITY_PROJECTILE) return false; - if (CE_INT(ent, netvar.iTeamNum) == g_pLocalPlayer->team) return false; - // If projectile is already deflected, don't deflect it again. - if (CE_INT(ent, (ent->m_bGrenadeProjectile ? - /* NetVar for grenades */ netvar.Grenade_iDeflected : - /* For rockets */ netvar.Rocket_iDeflected))) return false; + + // We dont want to do these checks in dodgeball, it breakes if we do + if (!dodgeball) { + // Check if the projectile is your own teams + if (!ent->m_bEnemy) return false; + + // If projectile is already deflected, don't deflect it again. + if (CE_INT(ent, (ent->m_bGrenadeProjectile ? + /* NetVar for grenades */ netvar.Grenade_iDeflected : + /* For rockets */ netvar.Rocket_iDeflected))) return false; + } + + // Check if the projectile is a sticky bomb and if the user settings allow it to be reflected + if (IsEntStickyBomb(ent) && !stickies) return false; + + // Target passed the test, return true + return true; +} + +bool IsEntStickyBomb(CachedEntity* ent) { + // Check if the projectile is a sticky bomb if (ent->m_iClassID == CL_CLASS(CTFGrenadePipebombProjectile)) { if (CE_INT(ent, netvar.iPipeType) == 1) { - if (!stickies) return false; + // Ent passed and should be reflected + return true; } } - return true; + // Ent didnt pass the test so return false + return false; } }}} diff --git a/src/hacks/AutoReflect.h b/src/hacks/AutoReflect.h index baa767f2..f23544e5 100644 --- a/src/hacks/AutoReflect.h +++ b/src/hacks/AutoReflect.h @@ -8,7 +8,7 @@ #ifndef HACKS_AUTOREFLECT_H_ #define HACKS_AUTOREFLECT_H_ -#include "IHack.h" +#include "../common.h" namespace hacks { namespace tf { namespace autoreflect { @@ -19,6 +19,7 @@ extern CatVar max_distance; void CreateMove(); bool ShouldReflect(CachedEntity* ent); +bool IsEntStickyBomb(CachedEntity* ent); }}} diff --git a/src/hacks/AutoSticky.cpp b/src/hacks/AutoSticky.cpp index 4a8357df..e0a66006 100644 --- a/src/hacks/AutoSticky.cpp +++ b/src/hacks/AutoSticky.cpp @@ -12,82 +12,145 @@ namespace hacks { namespace tf { namespace autosticky { +// Vars for user settings CatVar enabled(CV_SWITCH, "sticky_enabled", "0", "AutoSticky", "Master AutoSticky switch"); CatVar buildings(CV_SWITCH, "sticky_buildings", "1", "Detonate buildings", "Stickies react to buildings"); -CatVar distance(CV_INT, "sticky_distance", "150", "Distance", "Maximum distance to detonate"); -CatVar visCheck(CV_SWITCH, "sticky_visable", "1", "Vis check", "Simple check to see if the sticky will hit someone"); -//CatVar legit(CV_SWITCH, "sticky_legit", "0", "Legit", "Stickys only detonate when you see them"); +CatVar legit(CV_SWITCH, "sticky_legit", "0", "Legit", "Stickys only detonate when you see them\nAlso ignores invis spies"); +// A storage array for ents std::vector bombs; std::vector targets; - + +// Function to tell when an ent is the local players own bomb bool IsBomb(CachedEntity* ent) { + // Check if ent is a stickybomb if (ent->m_iClassID != CL_CLASS(CTFGrenadePipebombProjectile)) return false; if (CE_INT(ent, netvar.iPipeType) != 1) return false; + + // Check if the stickybomb is the players own if ((CE_INT(ent, netvar.hThrower) & 0xFFF) != g_pLocalPlayer->entity->m_IDX) return false; + + // Check passed, return true return true; } +// Function to check ent if it is a good target bool IsTarget(CachedEntity* ent) { + // Check if target is The local player + if (ent == LOCAL_E) return false; + + // Check if target is an enemy if (!ent->m_bEnemy) return false; + + // Player specific if (ent->m_Type == ENTITY_PLAYER) { - if (CE_BYTE(ent, netvar.iLifeState)) return false; + // Dont detonate on dead players + if (!ent->m_bAlivePlayer) return false; + // Dont detonate on friendly players + if (playerlist::IsFriendly(playerlist::AccessData(ent).state)) return false; + + IF_GAME (IsTF()) { + // Dont target invulnerable players, ex: uber, bonk + if (IsPlayerInvulnerable(ent)) return false; + + // If settings allow, ignore taunting players + //if (ignore_taunting && HasCondition(ent)) return false; + + // If settings allow, dont target cloaked players + if (legit && IsPlayerInvisible(ent)) return false; + } + + // Target is good return true; + + // Building specific } else if (ent->m_Type == ENTITY_BUILDING) { return buildings; } + + // Target isnt a good type return false; } - -bool stickyVisable(CachedEntity* targetTrace, CachedEntity* bombTrace) { - trace_t trace; - trace::filter_default.SetSelf(RAW_ENT(bombTrace)); - Ray_t ray; - ray.Init(bombTrace->m_vecOrigin, RAW_ENT(targetTrace)->GetCollideable()->GetCollisionOrigin()); - { - PROF_SECTION(IEVV_TraceRay); - g_ITrace->TraceRay(ray, MASK_SHOT_HULL, &trace::filter_default, &trace); - } - //deboog1 = bombTrace.DistToSqr(trace->endpos); - if (trace.m_pEnt) { - if ((((IClientEntity*)trace.m_pEnt)) == RAW_ENT(targetTrace)) return true; - } - return false; -} - + +// Function called by game for movement void CreateMove() { + // Check user settings if auto-sticky is enabled if (!enabled) return; + + // Check if game is a tf game + //IF_GAME (!IsTF()) return; + + // Check if player is demoman if (g_pLocalPlayer->clazz != tf_demoman) return; + + // Check for sticky jumper, which is item 265, if true, return + if (HasWeapon(LOCAL_E, 265)) return; + + // Clear the arrays bombs.clear(); targets.clear(); + + // Cycle through the ents and search for valid ents for (int i = 0; i < HIGHEST_ENTITY; i++) { + // Assign the for loops tick number to an ent CachedEntity* ent = ENTITY(i); + // Check for dormancy and if valid if (CE_BAD(ent)) continue; + // Check if ent is a bomb or suitable target and push to respective arrays if (IsBomb(ent)) { bombs.push_back(ent); } else if (IsTarget(ent)) { targets.push_back(ent); } } + + // Loop once for every bomb in the array for (auto bomb : bombs) { + // Loop through every target for a given bomb for (auto target : targets) { - if (bomb->m_vecOrigin.DistToSqr(target->m_vecOrigin) < ((float)distance * (float)distance)) { - if (visCheck) { - if (stickyVisable(target, bomb)) { - logging::Info("Det"); - g_pUserCmd->buttons |= IN_ATTACK2; - /*if (legit) { - if (stickyVisable(g_pLocalPlayer->entity, bomb)) g_pUserCmd->buttons |= IN_ATTACK2; - } else g_pUserCmd->buttons |= IN_ATTACK2; - */ - } - } else g_pUserCmd->buttons |= IN_ATTACK2; - - return; + // Check distance to the target to see if the sticky will hit + if (bomb->m_vecOrigin.DistToSqr(target->m_vecOrigin) < 16900) { + // Vis check the target from the bomb + if (VisCheckEntFromEnt(bomb, target)) { + // Check user settings if legit mode is off, if legit mode is off then detonate + if (!legit) { + // Check for scottish, id 130, if true then aim at bomb + if (HasWeapon(LOCAL_E, 130)) { + // Aim at bomb + AimAt(g_pLocalPlayer->v_Eye, bomb->m_vecOrigin, g_pUserCmd); + // Use silent + g_pLocalPlayer->bUseSilentAngles = true; + } + + // Detonate + g_pUserCmd->buttons |= IN_ATTACK2; + + // Return as its a waste to check anymore, we detonated and all the rest of the stickys are gone + return; + + // Since legit mode is on, check if the sticky can see the local player + } else if (VisCheckEntFromEnt(bomb, LOCAL_E)) { + // Check for scottish, id 130, if true then aim at bomb + if (HasWeapon(LOCAL_E, 130)) { + // Aim at bomb + AimAt(g_pLocalPlayer->v_Eye, bomb->m_vecOrigin, g_pUserCmd); + // Use silent + g_pLocalPlayer->bUseSilentAngles = true; + } + + // Detonate + g_pUserCmd->buttons |= IN_ATTACK2; + + // Return as its a waste to check anymore, we detonated and all the rest of the stickys are gone + return; + } + } } } } + // End of function, just return return; } }}} + diff --git a/src/hacks/AutoSticky.h b/src/hacks/AutoSticky.h index 141a503c..b3a60562 100644 --- a/src/hacks/AutoSticky.h +++ b/src/hacks/AutoSticky.h @@ -8,7 +8,7 @@ #ifndef HACKS_AUTOSTICKY_H_ #define HACKS_AUTOSTICKY_H_ -#include "IHack.h" +#include "../common.h" namespace hacks { namespace tf { namespace autosticky { diff --git a/src/hacks/AutoTaunt.cpp b/src/hacks/AutoTaunt.cpp new file mode 100644 index 00000000..ac0001f3 --- /dev/null +++ b/src/hacks/AutoTaunt.cpp @@ -0,0 +1,38 @@ +/* + * AutoTaunt.cpp + * + * Created on: Jul 27, 2017 + * Author: nullifiedcat + */ + +#include "../common.h" +#include "../init.hpp" +#include "../hack.h" + +namespace hacks { namespace tf { namespace autotaunt { + +CatVar enabled(CV_SWITCH, "autotaunt", "0", "AutoTaunt", "Automatically taunt after killing an enemy, use with walkbots I guess"); +CatVar chance(CV_FLOAT, "autotaunt_chance", "8", "AutoTaunt chance", "Chance of taunting after kill. 0 to 100.", 0.0f, 100.0f); + +class AutoTauntListener : public IGameEventListener2 { +public: + virtual void FireGameEvent(IGameEvent* event) { + if (!enabled) { + return; + } + if (g_IEngine->GetPlayerForUserID(event->GetInt("attacker")) == g_IEngine->GetLocalPlayer()) { + if (RandomFloat(0, 100) <= float(chance)) { + hack::ExecuteCommand("taunt"); + } + } + } +}; + +AutoTauntListener listener; + +// TODO remove event listener when uninjecting? +InitRoutine init([]() { + g_IEventManager2->AddListener(&listener, "player_death", false); +}); + +}}} diff --git a/src/hacks/AutoTaunt.hpp b/src/hacks/AutoTaunt.hpp new file mode 100644 index 00000000..b8aad8c6 --- /dev/null +++ b/src/hacks/AutoTaunt.hpp @@ -0,0 +1,20 @@ +/* + * AutoTaunt.hpp + * + * Created on: Jul 27, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class CatVar; +class InitRoutine; + +namespace hacks { namespace tf { namespace autotaunt { + +extern CatVar enabled; +extern CatVar chance; + +extern InitRoutine init; + +}}} diff --git a/src/hacks/Bunnyhop.cpp b/src/hacks/Bunnyhop.cpp index c8ab0b5e..92ffc498 100644 --- a/src/hacks/Bunnyhop.cpp +++ b/src/hacks/Bunnyhop.cpp @@ -12,31 +12,42 @@ namespace hacks { namespace shared { namespace bunnyhop { +// Var for user settings CatVar enabled(CV_SWITCH, "bhop_enabled", "0", "Bunnyhop", "Enable Bunnyhop. All extra features like autojump and perfect jump limit were temporary removed."); -int iTicksFlying { 0 }; -int iTicksLastJump { 0 }; - +int iTicksLastJump = 0; + +// Function called by game for movement void CreateMove() { + // Check user settings if bhop is enabled if (!enabled) return; - //if (HasCondition(g_pLocalPlayer->entity, TFCond_GrapplingHook)) return; + if (!g_pUserCmd) return; + + // Check if there is usercommands + if (!g_pUserCmd->command_number) return; + + // Check if local player is airborne, if true then return + //if (CE_INT(g_pLocalPlayer->entity, netvar.movetype) == MOVETYPE_FLY) return; + + // Grab netvar for flags from the local player int flags = CE_INT(g_pLocalPlayer->entity, netvar.iFlags); - if (CE_INT(g_pLocalPlayer->entity, netvar.movetype) == MOVETYPE_FLY) return; - + // var for "if on ground" from the flags netvar bool ground = (flags & (1 << 0)); + // Var for if the player is pressing jump bool jump = (g_pUserCmd->buttons & IN_JUMP); - if (ground) { - iTicksFlying = 0; - } else { - iTicksFlying++; + // Check if player is not on the ground and player is holding their jump key + if (!ground && jump) { + // If the ticks since last jump are greater or equal to 7, then force the player to stop jumping + // The bot disables jump untill player hits the ground or lets go of jump + if (iTicksLastJump++ >= 9) g_pUserCmd->buttons = g_pUserCmd->buttons &~ IN_JUMP; } - if (!ground && jump) { - if (iTicksLastJump++ >= 5) g_pUserCmd->buttons = g_pUserCmd->buttons &~ IN_JUMP; - } + // If the players jump cmd has been used, then we reset our var if (!jump) iTicksLastJump = 0; + + // Finish the function with return return; } diff --git a/src/hacks/Bunnyhop.h b/src/hacks/Bunnyhop.h index 5bda05a7..984ebd37 100644 --- a/src/hacks/Bunnyhop.h +++ b/src/hacks/Bunnyhop.h @@ -8,9 +8,7 @@ #ifndef HBUNNYHOP_H_ #define HBUNNYHOP_H_ -#include "IHack.h" - -class ConVar; +#include "../common.h" namespace hacks { namespace shared { namespace bunnyhop { diff --git a/src/hacks/ESP.cpp b/src/hacks/ESP.cpp index 54eb37da..38f8eef7 100644 --- a/src/hacks/ESP.cpp +++ b/src/hacks/ESP.cpp @@ -13,6 +13,8 @@ namespace hacks { namespace shared { namespace esp { CatVar show_weapon(CV_SWITCH, "esp_weapon", "1", "Show weapon name", "Show which weapon does the enemy use"); +CatEnum tracers_enum({ "OFF", "CENTER", "BOTTOM" }); +CatVar tracers(tracers_enum, "esp_tracers", "0", "Tracers", "SDraws a line from the player to a position on your screen"); CatVar local_esp(CV_SWITCH, "esp_local", "1", "ESP Local Player", "Shows local player ESP in thirdperson"); CatVar buildings(CV_SWITCH, "esp_buildings", "1", "Building ESP", "Show buildings"); CatVar enabled(CV_SWITCH, "esp_enabled", "0", "ESP", "Master ESP switch"); @@ -26,6 +28,7 @@ CatVar item_health_packs(CV_SWITCH, "esp_item_health", "1", "Health packs", "Sho CatVar item_powerups(CV_SWITCH, "esp_item_powerups", "1", "Powerups", "Show powerups"); CatVar item_money(CV_SWITCH, "esp_money", "1", "MvM money", "Show MvM money"); CatVar item_money_red(CV_SWITCH, "esp_money_red", "1", "Red MvM money", "Show red MvM money"); +CatVar item_spellbooks(CV_SWITCH, "esp_spellbooks", "1", "Spellbooks", "Spell Books"); CatVar entity_id(CV_SWITCH, "esp_entity_id", "1", "Entity ID", "Used with Entity ESP. Shows entityID"); CatVar tank(CV_SWITCH, "esp_show_tank", "1", "Show tank", "Show tank"); CatVar box_esp(CV_SWITCH, "esp_box", "1", "Box", "Draw 2D box with healthbar. fancy."); @@ -48,53 +51,103 @@ CatVar entity_model(CV_SWITCH, "esp_model_name", "0", "Model name ESP", "Model n CatVar item_weapon_spawners(CV_SWITCH, "esp_weapon_spawners", "1", "Show weapon spawners", "TF2C deathmatch weapon spawners"); CatVar item_adrenaline(CV_SWITCH, "esp_item_adrenaline", "0", "Show Adrenaline", "TF2C adrenaline pills"); +std::mutex threadsafe_mutex; + std::array data; void ResetEntityStrings() { for (auto& i : data) { i.string_count = 0; - i.color = 0; + i.color = colors::empty; i.needs_paint = false; } } -void SetEntityColor(CachedEntity* entity, int color) { +void SetEntityColor(CachedEntity* entity, const rgba_t& color) { data[entity->m_IDX].color = color; } -void AddEntityString(CachedEntity* entity, const std::string& string, int color) { +void AddEntityString(CachedEntity* entity, const std::string& string, const rgba_t& color) { ESPData& entity_data = data[entity->m_IDX]; + if (entity_data.string_count >= 15) return; entity_data.strings[entity_data.string_count].data = string; entity_data.strings[entity_data.string_count].color = color; entity_data.string_count++; entity_data.needs_paint = true; } + std::vector entities_need_repaint {}; +std::mutex entities_need_repaint_mutex {}; + +static CatVar box_corner_size(CV_INT, "esp_box_corner_size", "10", "Corner Size"); + +void BoxCorners(int minx, int miny, int maxx, int maxy, const rgba_t& color, bool transparent) { + const rgba_t& black = transparent ? colors::Transparent(colors::black) : colors::black; + const int size = box_corner_size; + // Black corners + + // Top Left + drawgl::FilledRect(minx, miny, size, 3, black); + drawgl::FilledRect(minx, miny + 3, 3, size - 3, black); + + // Top Right + drawgl::FilledRect(maxx - size + 1, miny, size, 3, black); + drawgl::FilledRect(maxx - 3 + 1, miny + 3, 3, size - 3, black); + + // Bottom Left + drawgl::FilledRect(minx, maxy - 3, size, 3, black); + drawgl::FilledRect(minx, maxy - size, 3, size - 3, black); + + // Bottom Right + drawgl::FilledRect(maxx - size + 1, maxy - 3, size, 3, black); + drawgl::FilledRect(maxx - 2, maxy - size, 3, size - 3, black); + + // Colored corners + // Top Left + drawgl::Line(minx + 1, miny + 1, size - 2, 0, color); + drawgl::Line(minx + 1, miny + 1, 0, size - 2, color); + // Top Right + drawgl::Line(maxx - 1, miny + 1, -(size - 2), 0, color); + drawgl::Line(maxx - 1, miny + 1, 0, size - 2, color); + // Bottom Left + drawgl::Line(minx + 1, maxy - 2, size - 2, 0, color); + drawgl::Line(minx + 1, maxy - 2, 0, -(size - 2), color); + // Bottom Right + drawgl::Line(maxx - 1, maxy - 2, -(size - 2), 0, color); + drawgl::Line(maxx - 1, maxy - 2, 0, -(size - 2), color); +} + void CreateMove() { + if (!enabled) return; + std::lock_guard esp_lock(threadsafe_mutex); int limit; static int max_clients = g_IEngine->GetMaxClients(); - CachedEntity* ent; ResetEntityStrings(); entities_need_repaint.clear(); limit = HIGHEST_ENTITY; if (!buildings && !proj_esp && !item_esp) limit = min(max_clients, HIGHEST_ENTITY); - for (int i = 0; i < limit; i++) { - ent = ENTITY(i); - ProcessEntity(ent); - if (data[i].string_count) { - SetEntityColor(ent, colors::EntityF(ent)); - if (show_distance) { - AddEntityString(ent, format((int)(ENTITY(i)->m_flDistance / 64 * 1.22f), 'm')); + { + PROF_SECTION(CM_ESP_EntityLoop); + for (int i = 0; i < limit; i++) { + CachedEntity* ent = ENTITY(i); + ProcessEntity(ent); + if (data[i].string_count) { + SetEntityColor(ent, colors::EntityF(ent)); + if (show_distance) { + AddEntityString(ent, format((int)(ENTITY(i)->m_flDistance / 64 * 1.22f), 'm')); + } } + if (data[ent->m_IDX].needs_paint) entities_need_repaint.push_back(ent->m_IDX); } - if (data[ent->m_IDX].needs_paint) entities_need_repaint.push_back(ent->m_IDX); } } void Draw() { + std::lock_guard esp_lock(threadsafe_mutex); + if (!enabled) return; for (auto& i : entities_need_repaint) { ProcessEntityPT(ENTITY(i)); } @@ -102,50 +155,43 @@ void Draw() { static CatEnum esp_box_text_position_enum({"TOP RIGHT", "BOTTOM RIGHT", "CENTER", "ABOVE", "BELOW" }); static CatVar esp_box_text_position(esp_box_text_position_enum, "esp_box_text_position", "0", "Text position", "Defines text position"); -static CatVar esp_3d_box_health(CV_SWITCH, "esp_3d_box_health", "1", "3D box health color", "Adds a health bar to 3d esp box"); -static CatVar esp_3d_box_thick(CV_SWITCH, "esp_3d_box_thick", "1", "Thick 3D box", "Makes the 3d box thicker\nMost times, easier to see"); -static CatVar esp_3d_box_expand_rate(CV_FLOAT, "esp_3d_box_expand_size", "10", "3D Box Expand Size", "Expand 3D box by X units", 50.0f); -static CatVar esp_3d_box_expand(CV_SWITCH, "esp_3d_box_expand", "1", "Expand 3D box", "Makes the 3d bigger"); -static CatEnum esp_3d_box_smoothing_enum({"None", "Origin offset", "Bone update (NOT IMPL)"}); -static CatVar esp_3d_box_smoothing(esp_3d_box_smoothing_enum, "esp_3d_box_smoothing", "1", "3D box smoothing", "3D box smoothing method"); -static CatVar esp_3d_box_nodraw(CV_SWITCH, "esp_3d_box_nodraw", "0", "Invisible 3D box", "Don't draw 3d box"); -static CatVar esp_3d_box_healthbar(CV_SWITCH, "esp_3d_box_healthbar", "1", "Health bar", "Adds a health bar to the esp"); +static CatVar box_nodraw(CV_SWITCH, "esp_box_nodraw", "0", "Invisible 2D Box", "Don't draw 2D box"); +static CatVar box_expand(CV_INT, "esp_box_expand", "0", "Expand 2D Box", "Expand 2D box by N units"); +static CatVar box_corners(CV_SWITCH, "esp_box_corners", "1", "Box Corners"); +static CatVar powerup_esp(CV_SWITCH, "esp_powerups", "1", "Powerup ESP"); + +const Vector dims_player[] = { { -16, -16, -4 }, { 16, 16, 72 } }; + +void _FASTCALL DrawBox(CachedEntity* ent, const rgba_t& clr, bool healthbar, int health, int healthmax) { + PROF_SECTION(PT_esp_drawbox); + Vector so, omin, omax, smin, smax; + float height, width; + bool cloak; + int min_x, min_y, max_x, max_y, hbh; + rgba_t hp, border; + + if (CE_BAD(ent)) return; + + const Vector& origin = RAW_ENT(ent)->GetCollideable()->GetCollisionOrigin(); + Vector mins = RAW_ENT(ent)->GetCollideable()->OBBMins() + origin; + Vector maxs = RAW_ENT(ent)->GetCollideable()->OBBMaxs() + origin; + + cloak = (ent->m_iClassID == RCC_PLAYER) && IsPlayerInvisible(ent); + + //if (!a) return; + //logging::Info("%f %f", so.x, so.y); + data.at(ent->m_IDX).esp_origin.Zero(); -void Draw3DBox(CachedEntity* ent, int clr, bool healthbar, int health, int healthmax) { - PROF_SECTION(PT_esp_draw3dbox); - Vector mins, maxs; Vector points_r[8]; Vector points[8]; - bool set, success, cloak; + bool set, success; float x, y, z; - int hbh, max_x, max_y, min_x, min_y; - CachedHitbox* hb; set = false; success = true; - for (int i = 0; i < ent->hitboxes.GetNumHitboxes(); i++) { - hb = ent->hitboxes.GetHitbox(i); - if (!hb) return; - if (!set || hb->min.x < mins.x) mins.x = hb->min.x; - if (!set || hb->min.y < mins.y) mins.y = hb->min.y; - if (!set || hb->min.z < mins.z) mins.z = hb->min.z; - if (!set || hb->max.x > maxs.x) maxs.x = hb->max.x; - if (!set || hb->max.y > maxs.y) maxs.y = hb->max.y; - if (!set || hb->max.z > maxs.z) maxs.z = hb->max.z; - set = true; - } - - // This is weird, smoothing only makes it worse on local servers - if ((int)esp_3d_box_smoothing == 1) { - mins += (RAW_ENT(ent)->GetAbsOrigin() - ent->m_vecOrigin); - maxs += (RAW_ENT(ent)->GetAbsOrigin() - ent->m_vecOrigin); - } - - //static const Vector expand_vector(8.5, 8.5, 8.5); - - if (esp_3d_box_expand) { - const float& exp = (float)esp_3d_box_expand_rate; + if (box_expand) { + const float& exp = (float)box_expand; maxs.x += exp; maxs.y += exp; maxs.z += exp; @@ -180,146 +226,60 @@ void Draw3DBox(CachedEntity* ent, int clr, bool healthbar, int health, int healt if (points[i].x < min_x) min_x = points[i].x; if (points[i].y < min_y) min_y = points[i].y; } - data.at(ent->m_IDX).esp_origin.Zero(); - switch ((int)esp_box_text_position) { - case 0: { // TOP RIGHT - data.at(ent->m_IDX).esp_origin = Vector(max_x + 1, min_y, 0); - } break; - case 1: { // BOTTOM RIGHT - data.at(ent->m_IDX).esp_origin = Vector(max_x + 1, max_y - data.at(ent->m_IDX).string_count * ((int)fonts::esp_height - 3), 0); - } break; - case 2: { // CENTER - } break; - case 3: { // ABOVE - data.at(ent->m_IDX).esp_origin = Vector(min_x + 1, min_y - data.at(ent->m_IDX).string_count * ((int)fonts::esp_height - 3), 0); - } break; - case 4: { // BELOW - data.at(ent->m_IDX).esp_origin = Vector(min_x + 1, max_y, 0); - } - } - //draw::String(fonts::ESP, points[0].x, points[0].y, clr, 1, "MIN"); - //draw::String(fonts::ESP, points[6].x, points[6].y, clr, 1, "MAX"); - constexpr int indices[][2] = { - { 0, 1 }, { 0, 3 }, { 1, 2 }, { 2, 3 }, - { 4, 5 }, { 4, 7 }, { 5, 6 }, { 6, 7 }, - { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } - }; - if (esp_3d_box_health) clr = colors::Health(health, healthmax); - cloak = ent->m_Type == ENTITY_PLAYER && IsPlayerInvisible(ent); - if (cloak) clr = colors::Transparent(clr, 0.2); - if (esp_3d_box_healthbar) { - draw::OutlineRect(min_x - 6, min_y, 6, max_y - min_y, colors::black); - hbh = (max_y - min_y - 2) * min((float)health / (float)healthmax, 1.0f); - draw::DrawRect(min_x - 5, max_y - 1 - hbh, 4, hbh, colors::Health(health, healthmax)); - } - if (!esp_3d_box_nodraw) { - for (int i = 0; i < 12; i++) { - // I'll let compiler optimize this. - const Vector& p1 = points[indices[i][0]]; - const Vector& p2 = points[indices[i][1]]; - draw::DrawLine(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y, clr); - if (esp_3d_box_thick) { - draw::DrawLine(p1.x + 1, p1.y, p2.x - p1.x, p2.y - p1.y, clr); - draw::DrawLine(p1.x, p1.y + 1, p2.x - p1.x, p2.y - p1.y, clr); - draw::DrawLine(p1.x + 1, p1.y + 1, p2.x - p1.x, p2.y - p1.y, clr); - } - } - } -} - -static CatVar box_nodraw(CV_SWITCH, "esp_box_nodraw", "0", "Invisible 2D Box", "Don't draw 2D box"); -static CatVar box_expand(CV_INT, "esp_box_expand", "0", "Expand 2D Box", "Expand 2D box by N units"); - -void _FASTCALL DrawBox(CachedEntity* ent, int clr, float widthFactor, float addHeight, bool healthbar, int health, int healthmax) { - PROF_SECTION(PT_esp_drawbox); - Vector min, max, origin, so, omin, omax, smin, smax; - float height, width, trf; - bool cloak; - int min_x, min_y, max_x, max_y, border, hp, hbh; - unsigned char alpha; - - if (CE_BAD(ent)) return; - - cloak = ent->m_iClassID == RCC_PLAYER && IsPlayerInvisible(ent); - RAW_ENT(ent)->GetRenderBounds(min, max); - origin = RAW_ENT(ent)->GetAbsOrigin(); - draw::WorldToScreen(origin, so); - //if (!a) return; - //logging::Info("%f %f", so.x, so.y); - omin = origin + Vector(0, 0, min.z); - omax = origin + Vector(0, 0, max.z + addHeight); - bool a = draw::WorldToScreen(omin, smin); - a = a && draw::WorldToScreen(omax, smax); - if (!a) return; - height = abs(smax.y - smin.y); - //logging::Info("height: %f", height); - width = height / widthFactor; - //bool a = draw::WorldToScreen(omin, smin); - //a = a && draw::WorldToScreen(omax, smax); - //if (!a) return; - //draw::DrawString(min(smin.x, smax.x), min(smin.y, smax.y), clr, false, "min"); - //draw::DrawString(max(smin.x, smax.x), max(smin.y, smax.y), clr, false, "max"); - //draw::DrawString((int)so.x, (int)so.y, draw::white, false, "origin"); - data.at(ent->m_IDX).esp_origin.Zero(); - max_x = so.x + width / 2 + 1; - min_y = so.y - height; - max_y = so.y; - min_x = so.x - width / 2; - - if (box_expand) { + /*if (box_expand) { const float& exp = (float)box_expand; max_x += exp; max_y += exp; min_x -= exp; min_y -= exp; - } + }*/ switch ((int)esp_box_text_position) { case 0: { // TOP RIGHT - data.at(ent->m_IDX).esp_origin = Vector(max_x, min_y, 0); + data.at(ent->m_IDX).esp_origin = Vector(max_x + 2, min_y, 0); } break; case 1: { // BOTTOM RIGHT - data.at(ent->m_IDX).esp_origin = Vector(max_x, max_y - data.at(ent->m_IDX).string_count * ((int)fonts::esp_height - 3), 0); + data.at(ent->m_IDX).esp_origin = Vector(max_x + 2, max_y - data.at(ent->m_IDX).string_count * ((int)fonts::ftgl_ESP->height), 0); } break; case 2: { // CENTER } break; case 3: { // ABOVE - data.at(ent->m_IDX).esp_origin = Vector(min_x + 1, min_y - data.at(ent->m_IDX).string_count * ((int)fonts::esp_height - 3), 0); + data.at(ent->m_IDX).esp_origin = Vector(min_x, min_y - data.at(ent->m_IDX).string_count * ((int)fonts::ftgl_ESP->height), 0); } break; case 4: { // BELOW - data.at(ent->m_IDX).esp_origin = Vector(min_x + 1, max_y, 0); + data.at(ent->m_IDX).esp_origin = Vector(min_x, max_y, 0); } } - alpha = clr >> 24; - trf = (float)((float)alpha / 255.0f); - border = cloak ? colors::Create(160, 160, 160, alpha) : colors::Transparent(colors::black, trf); + border = cloak ? colors::FromRGBA8(160, 160, 160, clr.a * 255.0f) : colors::Transparent(colors::black, clr.a); if (!box_nodraw) { - draw::OutlineRect(min_x, min_y, max_x - min_x, max_y - min_y, border); - draw::OutlineRect(min_x + 1, min_y + 1, max_x - min_x - 2, max_y - min_y - 2, clr); - draw::OutlineRect(min_x + 2, min_y + 2, max_x - min_x - 4, max_y - min_y - 4, border); + if (box_corners) + BoxCorners(min_x, min_y, max_x, max_y, clr, (clr.a != 1.0f)); + else { + drawgl::Rect(min_x, min_y, max_x - min_x, max_y - min_y, border); + drawgl::Rect(min_x + 1, min_y + 1, max_x - min_x - 2, max_y - min_y - 2, clr); + drawgl::Rect(min_x + 2, min_y + 2, max_x - min_x - 4, max_y - min_y - 4, border); + } } if (healthbar) { - hp = colors::Transparent(colors::Health(health, healthmax), trf); + hp = colors::Transparent(colors::Health(health, healthmax), clr.a); hbh = (max_y - min_y - 2) * min((float)health / (float)healthmax, 1.0f); - draw::OutlineRect(min_x - 6, min_y, 7, max_y - min_y, border); - draw::DrawRect(min_x - 5, max_y - hbh - 1, 5, hbh, hp); + drawgl::Rect(min_x - 7, min_y, 7, max_y - min_y, border); + drawgl::FilledRect(min_x - 6, max_y - hbh - 1, 5, hbh, hp); } } void _FASTCALL ProcessEntity(CachedEntity* ent) { - const model_t* model; + if (!enabled) return; + if (CE_BAD(ent)) return; + int string_count_backup, level, pclass, *weapon_list, handle, eid; bool shown; player_info_s info; powerup_type power; CachedEntity* weapon; const char* weapon_name; - - if (!enabled) return; - if (CE_BAD(ent)) return; - ESPData& espdata = data[ent->m_IDX]; if (entity_info) { @@ -328,7 +288,7 @@ void _FASTCALL ProcessEntity(CachedEntity* ent) { AddEntityString(ent, std::to_string(ent->m_IDX)); } if (entity_model) { - model = RAW_ENT(ent)->GetModel(); + const model_t* model = RAW_ENT(ent)->GetModel(); if (model) AddEntityString(ent, std::string(g_IModelInfo->GetModelName(model))); } } @@ -411,6 +371,12 @@ void _FASTCALL ProcessEntity(CachedEntity* ent) { } else if (item_weapon_spawners && ent->m_ItemType >= ITEM_TF2C_W_FIRST && ent->m_ItemType <= ITEM_TF2C_W_LAST) { AddEntityString(ent, format(tf2c_weapon_names[ent->m_ItemType - ITEM_TF2C_W_FIRST], " SPAWNER")); if (CE_BYTE(ent, netvar.bRespawning)) AddEntityString(ent, "-- RESPAWNING --"); + } else if (item_spellbooks && (ent->m_ItemType == ITEM_SPELL || ent->m_ItemType == ITEM_SPELL_RARE)) { + if (ent->m_ItemType == ITEM_SPELL) { + AddEntityString(ent, "Spell", colors::green); + } else { + AddEntityString(ent, "Rare Spell", colors::FromRGBA8(139, 31, 221, 255)); + } } } else if (ent->m_Type == ENTITY_BUILDING && buildings) { if (!ent->m_bEnemy && !teammates) return; @@ -432,18 +398,19 @@ void _FASTCALL ProcessEntity(CachedEntity* ent) { ent->m_IDX == g_IEngine->GetLocalPlayer()) return; pclass = CE_INT(ent, netvar.iClass); if (!g_IEngine->GetPlayerInfo(ent->m_IDX, &info)) return; - power = GetPowerupOnPlayer(ent); // If target is enemy, always show powerups, if player is teammate, show powerups // only if bTeammatePowerup or bTeammates is true if (legit && ent->m_iTeam != g_pLocalPlayer->team && playerlist::IsDefault(info.friendsID)) { if (IsPlayerInvisible(ent)) return; + if (vischeck && !ent->IsVisible()) return; /*if (ent->m_lLastSeen > (unsigned)v_iLegitSeenTicks->GetInt()) { return; }*/ } - if (power >= 0) { - // FIXME Disabled powerup ESP. - //AddEntityString(ent, format("HAS ", powerups[power])); + if (powerup_esp) { + power = GetPowerupOnPlayer(ent); + if (power != not_powerup) + AddEntityString(ent, format("^ ", powerups[power], " ^")); } if (ent->m_bEnemy || teammates || !playerlist::IsDefault(info.friendsID)) { if (show_name) @@ -485,35 +452,40 @@ void _FASTCALL ProcessEntity(CachedEntity* ent) { } } if (show_conditions) { + const auto& clr = colors::EntityF(ent); if (IsPlayerInvisible(ent)) { - AddEntityString(ent, "INVISIBLE"); + AddEntityString(ent, "*CLOAKED*", colors::FromRGBA8(220.0f, 220.0f, 220.0f, 255.0f)); } if (IsPlayerInvulnerable(ent)) { - AddEntityString(ent, "INVULNERABLE"); + AddEntityString(ent, "*INVULNERABLE*"); } if (HasCondition(ent)) { - AddEntityString(ent, "VACCINATOR ACTIVE"); - } - if (HasCondition(ent)) { - AddEntityString(ent, "VACCINATOR PASSIVE"); + AddEntityString(ent, "*VACCINATOR*"); + } else if (HasCondition(ent)) { + AddEntityString(ent, "*PASSIVE RESIST*"); } if (IsPlayerCritBoosted(ent)) { - AddEntityString(ent, "CRIT BOOSTED"); + AddEntityString(ent, "*CRITS*", colors::orange); } if (HasCondition(ent)) { - AddEntityString(ent, "*ZOOMING*"); + AddEntityString(ent, "*ZOOMING*", colors::FromRGBA8(220.0f, 220.0f, 220.0f, 255.0f)); + } else if (HasCondition(ent)) { + AddEntityString(ent, "*SLOWED*", colors::FromRGBA8(220.0f, 220.0f, 220.0f, 255.0f)); + } + if (HasCondition(ent)) { + AddEntityString(ent, "*JARATED*", colors::yellow); } - if (HasCondition(ent)) { - AddEntityString(ent, "*SLOWED*"); - }; } } if (IsHoovy(ent)) AddEntityString(ent, "Hoovy"); - weapon = ENTITY(CE_INT(ent, netvar.hActiveWeapon) & 0xFFF); - if (CE_GOOD(weapon)) { - if (show_weapon) { - weapon_name = vfunc(RAW_ENT(weapon), 398, 0)(RAW_ENT(weapon)); - if (weapon_name) AddEntityString(ent, std::string(weapon_name)); + int widx = CE_INT(ent, netvar.hActiveWeapon) & 0xFFF; + if (IDX_GOOD(widx)) { + weapon = ENTITY(widx); + if (CE_GOOD(weapon)) { + if (show_weapon) { + weapon_name = vfunc(RAW_ENT(weapon), 398, 0)(RAW_ENT(weapon)); + if (weapon_name) AddEntityString(ent, std::string(weapon_name)); + } } } espdata.needs_paint = true; @@ -521,18 +493,124 @@ void _FASTCALL ProcessEntity(CachedEntity* ent) { return; } } - -static CatVar esp_3d_box(CV_SWITCH, "esp_3d_box", "0", "3D box"); static CatVar box_healthbar(CV_SWITCH, "esp_box_healthbar", "1", "Box Healthbar"); +static CatVar draw_bones(CV_SWITCH, "esp_bones", "0", "Draw Bone ID's"); + +const std::string bonenames_leg_r[] = { "bip_foot_R", "bip_knee_R", "bip_hip_R" }; +const std::string bonenames_leg_l[] = { "bip_foot_L", "bip_knee_L", "bip_hip_L" }; +const std::string bonenames_bottom[] = { "bip_hip_R", "bip_pelvis", "bip_hip_L" }; +const std::string bonenames_spine[] = { "bip_pelvis", "bip_spine_0", "bip_spine_1", "bip_spine_2", "bip_spine_3", "bip_neck", "bip_head" }; +const std::string bonenames_arm_r[] = { "bip_upperArm_R", "bip_lowerArm_R", "bip_hand_R" }; +const std::string bonenames_arm_l[] = { "bip_upperArm_L", "bip_lowerArm_L", "bip_hand_L" }; +const std::string bonenames_up[] = { "bip_upperArm_R", "bip_spine_3", "bip_upperArm_L" }; + +struct bonelist_s { + bool setup { false }; + bool success { false }; + int leg_r[3] { 0 }; + int leg_l[3] { 0 }; + int bottom[3] { 0 }; + int spine[7] { 0 }; + int arm_r[3] { 0 }; + int arm_l[3] { 0 }; + int up[3] { 0 }; + + void Setup(const studiohdr_t* hdr) { + if (!hdr) { + setup = true; + return; + } + std::unordered_map bones {}; + for (int i = 0; i < hdr->numbones; i++) { + bones[std::string(hdr->pBone(i)->pszName())] = i; + } + try { + for (int i = 0; i < 3; i++) leg_r[i] = bones.at(bonenames_leg_r[i]); + for (int i = 0; i < 3; i++) leg_l[i] = bones.at(bonenames_leg_l[i]); + for (int i = 0; i < 3; i++) bottom[i] = bones.at(bonenames_bottom[i]); + for (int i = 0; i < 7; i++) spine[i] = bones.at(bonenames_spine[i]); + for (int i = 0; i < 3; i++) arm_r[i] = bones.at(bonenames_arm_r[i]); + for (int i = 0; i < 3; i++) arm_l[i] = bones.at(bonenames_arm_l[i]); + for (int i = 0; i < 3; i++) up[i] = bones.at(bonenames_up[i]); + success = true; + } catch (std::exception& ex) { + logging::Info("Bone list exception: %s", ex.what()); + } + setup = true; + } + + void DrawBoneList(const matrix3x4_t* bones, int* in, int size, const rgba_t& color, const Vector& displacement) { + Vector last_screen; + Vector current_screen; + for (int i = 0; i < size; i++) { + Vector position(bones[in[i]][0][3], bones[in[i]][1][3], bones[in[i]][2][3]); + position += displacement; + if (!draw::WorldToScreen(position, current_screen)) { + return; + } + if (i > 0) { + drawgl::Line(last_screen.x, last_screen.y, current_screen.x - last_screen.x, current_screen.y - last_screen.y, color); + } + last_screen = current_screen; + } + } + + void Draw(CachedEntity* ent, const rgba_t& color) { + const model_t* model = RAW_ENT(ent)->GetModel(); + if (not model) { + return; + } + + studiohdr_t* hdr = g_IModelInfo->GetStudiomodel(model); + + if (!setup) { + Setup(hdr); + } + if (!success) return; + + //ent->m_bBonesSetup = false; + Vector displacement = RAW_ENT(ent)->GetAbsOrigin() - ent->m_vecOrigin; + const auto& bones = ent->hitboxes.GetBones(); + DrawBoneList(bones, leg_r, 3, color, displacement); + DrawBoneList(bones, leg_l, 3, color, displacement); + DrawBoneList(bones, bottom, 3, color, displacement); + DrawBoneList(bones, spine, 7, color, displacement); + DrawBoneList(bones, arm_r, 3, color, displacement); + DrawBoneList(bones, arm_l, 3, color, displacement); + DrawBoneList(bones, up, 3, color, displacement); + /*for (int i = 0; i < hdr->numbones; i++) { + const auto& bone = ent->GetBones()[i]; + Vector pos(bone[0][3], bone[1][3], bone[2][3]); + //pos += orig; + Vector screen; + if (draw::WorldToScreen(pos, screen)) { + if (hdr->pBone(i)->pszName()) { + draw::FString(fonts::ESP, screen.x, screen.y, fg, 2, "%s [%d]", hdr->pBone(i)->pszName(), i); + } else + draw::FString(fonts::ESP, screen.x, screen.y, fg, 2, "%d", i); + } + }*/ + } +}; + +std::unordered_map bonelist_map {}; /* * According to profiler, this function is the most time-consuming (and gets called up to 200K times a second) */ +CatEnum emoji_esp({ "None", "Joy", "Thinking" }); +CatVar joy_esp(CV_SWITCH, "esp_emoji", "0", "Emoji ESP"); +CatVar joy_esp_size(CV_FLOAT, "esp_emoji_size", "32", "Emoji ESP Size"); +CatVar emoji_esp_scaling(CV_SWITCH, "esp_emoji_scaling", "1", "Emoji ESP Scaling"); +CatVar emoji_min_size(CV_INT, "esp_emoji_min_size", "20", "Emoji ESP min size", "Minimum size for an emoji when you use auto scaling"); +textures::AtlasTexture joy_texture(64 * 4, textures::atlas_height - 64 * 4, 64, 64); +textures::AtlasTexture thinking_texture(64 * 5, textures::atlas_height - 64 * 4, 64, 64); + void _FASTCALL ProcessEntityPT(CachedEntity* ent) { PROF_SECTION(PT_esp_process_entity); - int fg, color; + rgba_t fg, color; bool transparent, cloak, origin_is_zero; Vector screen, origin_screen, draw_point; @@ -543,25 +621,89 @@ void _FASTCALL ProcessEntityPT(CachedEntity* ent) { //if (!(local_esp && g_IInput->CAM_IsThirdPerson()) && // ent->m_IDX == g_IEngine->GetLocalPlayer()) return; - const ESPData& ent_data = data[ent->m_IDX]; + ESPData& ent_data = data[ent->m_IDX]; fg = ent_data.color; + if (!fg || fg.a == 0.0f) fg = ent_data.color = colors::EntityF(ent); if (!draw::EntityCenterToScreen(ent, screen) && !draw::WorldToScreen(ent->m_vecOrigin, origin_screen)) return; + ent_data.esp_origin.Zero(); + + if (vischeck && !ent->IsVisible()) transparent = true; + + if (draw_bones && ent->m_Type == ENTITY_PLAYER) { + const model_t* model = RAW_ENT(ent)->GetModel(); + if (model) { + auto hdr = g_IModelInfo->GetStudiomodel(model); + bonelist_map[hdr].Draw(ent, fg); + //const Vector& orig = RAW_ENT(ent)->GetAbsOrigin(); + /*ent->m_bBonesSetup = false; + ent->GetBones(); + for (int i = 0; i < hdr->numbones; i++) { + const auto& bone = ent->GetBones()[i]; + Vector pos(bone[0][3], bone[1][3], bone[2][3]); + //pos += orig; + Vector screen; + if (draw::WorldToScreen(pos, screen)) { + if (hdr->pBone(i)->pszName()) { + draw::FString(fonts::ESP, screen.x, screen.y, fg, 2, "%s [%d]", hdr->pBone(i)->pszName(), i); + } else + draw::FString(fonts::ESP, screen.x, screen.y, fg, 2, "%d", i); + } + }*/ + } + } + + if (tracers && ent->m_Type == ENTITY_PLAYER) { + + // Grab the screen resolution and save to some vars + int width, height; + g_IEngine->GetScreenSize(width, height); + + // Center values on screen + width = width / 2; + // Only center height if we are using center mode + if ((int)tracers == 1) height = height / 2; + + // Get world to screen + Vector scn; + draw::WorldToScreen(ent->m_vecOrigin, scn); + + // Draw a line + drawgl::Line(scn.x, scn.y, width - scn.x, height - scn.y, fg); + } + + if (ent->m_Type == ENTITY_PLAYER) { + if (joy_esp) { + auto hb = ent->hitboxes.GetHitbox(0); + Vector hbm, hbx; + if (draw::WorldToScreen(hb->min, hbm) && draw::WorldToScreen(hb->max, hbx)) { + Vector head_scr; + if (draw::WorldToScreen(hb->center, head_scr)) { + float size = emoji_esp_scaling ? fabs(hbm.y - hbx.y) : float(joy_esp_size); + if (emoji_esp_scaling && (size < float(emoji_min_size))) { + size = float(emoji_min_size); + } + textures::AtlasTexture* tx = nullptr; + if (int(joy_esp) == 1) tx = &joy_texture; + if (int(joy_esp) == 2) tx = &thinking_texture; + if (tx) + tx->Draw(head_scr.x - size / 2, head_scr.y - size / 2, size, size); + } + } + } + } + if (box_esp) { switch (ent->m_Type) { case ENTITY_PLAYER: { - cloak = IsPlayerInvisible(ent); + //cloak = IsPlayerInvisible(ent); //if (!ent->m_bEnemy && !teammates && playerlist::IsDefault(ent)) break; //if (!ent->m_bAlivePlayer) break; if (vischeck && !ent->IsVisible()) transparent = true; if (!fg) fg = colors::EntityF(ent); if (transparent) fg = colors::Transparent(fg); - if (esp_3d_box) { - Draw3DBox(ent, fg, true, CE_INT(ent, netvar.iHealth), ent->m_iMaxHealth); - } else { - DrawBox(ent, fg, 3.0f, -15.0f, static_cast(box_healthbar), CE_INT(ent, netvar.iHealth), ent->m_iMaxHealth); - } + DrawBox(ent, fg, static_cast(box_healthbar), CE_INT(ent, netvar.iHealth), ent->m_iMaxHealth); break; } case ENTITY_BUILDING: { @@ -569,19 +711,15 @@ void _FASTCALL ProcessEntityPT(CachedEntity* ent) { if (!transparent && vischeck && !ent->IsVisible()) transparent = true; if (!fg) fg = colors::EntityF(ent); if (transparent) fg = colors::Transparent(fg); - if (esp_3d_box) { - Draw3DBox(ent, fg, true, CE_INT(ent, netvar.iBuildingHealth), CE_INT(ent, netvar.iBuildingMaxHealth)); - } else { - DrawBox(ent, fg, 1.0f, 0.0f, static_cast(box_healthbar), CE_INT(ent, netvar.iBuildingHealth), CE_INT(ent, netvar.iBuildingMaxHealth)); - } + DrawBox(ent, fg, static_cast(box_healthbar), CE_INT(ent, netvar.iBuildingHealth), CE_INT(ent, netvar.iBuildingMaxHealth)); break; } } } - + origin_is_zero = !box_esp || ent_data.esp_origin.IsZero(1.0f); + if (origin_is_zero) ent_data.esp_origin = screen; if (ent_data.string_count) { PROF_SECTION(PT_esp_drawstrings); - origin_is_zero = !box_esp || ent_data.esp_origin.IsZero(1.0f); if (vischeck && !ent->IsVisible()) transparent = true; draw_point = origin_is_zero ? screen : ent_data.esp_origin; for (int j = 0; j < ent_data.string_count; j++) { @@ -589,16 +727,16 @@ void _FASTCALL ProcessEntityPT(CachedEntity* ent) { color = string.color ? string.color : ent_data.color; if (transparent) color = colors::Transparent(color); if (!origin_is_zero) { - draw::String(fonts::ESP, draw_point.x, draw_point.y, color, 2, string.data); - draw_point.y += (int)fonts::esp_height - 3; + FTGL_Draw(string.data, draw_point.x, draw_point.y, fonts::ftgl_ESP, color); + draw_point.y += (int)fonts::ftgl_ESP->height - 1; } else { - auto l = draw::GetStringLength(fonts::ESP, string.data); - draw::String(fonts::ESP, draw_point.x - l.first / 2, draw_point.y, color, 2, string.data); - draw_point.y += (int)fonts::esp_height - 3; + int size_x; + FTGL_StringLength(string.data, fonts::ftgl_ESP, &size_x); + FTGL_Draw(string.data, draw_point.x - size_x / 2, draw_point.y, fonts::ftgl_ESP, color); + draw_point.y += (int)fonts::ftgl_ESP->height - 1; } } } - } }}} diff --git a/src/hacks/ESP.h b/src/hacks/ESP.h index 3e08bcb9..fc0e9f66 100644 --- a/src/hacks/ESP.h +++ b/src/hacks/ESP.h @@ -58,27 +58,28 @@ extern CatVar item_adrenaline; class ESPString { public: std::string data { "" }; - int color { 0 }; + rgba_t color { colors::empty }; }; class ESPData { public: - int color { 0 }; + rgba_t color { colors::empty }; int string_count { 0 }; std::array strings {}; Vector esp_origin { 0, 0, 0 }; + Vector last_origin { 0, 0, 0 }; bool needs_paint { false }; }; extern std::array data; void ResetEntityStrings(); -void AddEntityString(CachedEntity* entity, const std::string& string, int color = 0x0); -void SetEntityColor(CachedEntity* entity, int color); +void AddEntityString(CachedEntity* entity, const std::string& string, const rgba_t& color = colors::empty); +void SetEntityColor(CachedEntity* entity, const rgba_t& color); void CreateMove(); void Draw(); -void __attribute__((fastcall)) DrawBox(CachedEntity* ent, int clr, float widthFactor, float addHeight, bool healthbar, int health, int healthmax); +void __attribute__((fastcall)) DrawBox(CachedEntity* ent, const rgba_t& clr, bool healthbar, int health, int healthmax); void __attribute__((fastcall)) ProcessEntity(CachedEntity* ent); void __attribute__((fastcall)) ProcessEntityPT(CachedEntity* ent); diff --git a/src/hacks/FollowBot.cpp b/src/hacks/FollowBot.cpp index 460ea1fe..878f0b32 100644 --- a/src/hacks/FollowBot.cpp +++ b/src/hacks/FollowBot.cpp @@ -12,123 +12,498 @@ #ifdef IPC_ENABLED namespace hacks { namespace shared { namespace followbot { + + +/* Big Followbot TODO list +1. Fix crash when setting followbot_idx var and remove the fix var in its place +*/ -unsigned follow_steamid { 0 }; -Vector last_direction; -float lost_time { 0 }; -float idle_time { 0 }; -int following_idx { 0 }; + +// User settings +CatVar bot(CV_SWITCH, "fb_bot", "0", "Master Followbot Switch", "Set to 1 in followbots' configs"); +CatVar follow_distance(CV_FLOAT, "fb_distance", "175", "Follow Distance", "How close the bots should stay to the target"); +CatVar follow_activation(CV_FLOAT, "fb_activation", "175", "Activation Distance", "How close a player should be until the followbot will pick them as a target"); +CatVar mimic_slot(CV_SWITCH, "fb_mimic_slot", "0", "Mimic selected weapon", "If enabled, this bot will select same weapon slot as the owner"); +CatVar always_medigun(CV_SWITCH, "fb_always_medigun", "0", "Always use Medigun", "Medics will always use Medigun"); +CatVar crumb_draw(CV_SWITCH, "fb_crumb_draw", "1", "Draw Crumbs", "Draws the path made for the followbot"); +CatVar roaming(CV_SWITCH, "fb_roaming", "0", "Roaming", "Allows the bot to find a different target if it cant find one using the steam id"); +CatVar sync_taunt(CV_SWITCH, "fb_sync_taunt", "0", "Mimic taunts", "Bots will taunt if target is taunting"); +// Var to store the current steamid to follow +unsigned follow_steamid { 1 }; + +// Vars that decides how the followbot will act and move +EFollowType current_follow_type = EFollowType::ENTITY; +CachedEntity* target_last = 0; +int following_idx = 0; +bool allow_moving = true; + +// Arrays to store selected ents std::set selection {}; std::set selection_secondary {}; -//Cats vars for old followbot +// Vars for vector followbot float destination_point_time { 0.0f }; Vector destination_point {}; -bool destination_reached { false }; -bool allow_moving { true }; - -//Initalize vars for BreadCrumb followbot -//An array for storing the breadcrumbs -static CatVar crumbFollowDistance(CV_FLOAT, "fb_follow_distance", "150", "Followbot Distance", "How close the bots should stay to you"); -Vector breadcrumbs [55]; -float crumbWaitPrune = 0; -float crumbWaitVis = 0; + +// Var that control jumping and the followbot +float idle_time = 0; + +// Vars for breadcrumb followbot + +// An array for storing the breadcrumbs +static Vector breadcrumbs [64]; +// Int for storing length of array +constexpr int MAX_CRUMBS = 64; +// Array Bookkeeping vars int crumbBottom = 0; int crumbTop = 0; int crumbArrayLength = 0; -bool crumbAbleToMove = false; +// Used for states for the followbot +float crumb_prune_timeout = 0; bool crumbStopped = true; bool crumbFindNew = false; bool crumbForceMove = false; -//A function to start the crumb followbot up -void CrumbStart() { - //A check to make sure using the fb tool repeatedly doesnt clear the cache of crumbs - if (crumbStopped || !crumbAbleToMove) { - crumbTop = 0; - crumbBottom = 0; - crumbArrayLength = 0; - crumbWaitPrune = g_GlobalVars->curtime; - crumbWaitVis = g_GlobalVars->curtime; - crumbFindNew = true; - crumbStopped = false; - crumbAbleToMove = true; - logging::Info("Crumb Start"); - } -} - -//A function to place a crumb into the array -void CrumbTopAdd(Vector crumbToAdd) { - //Once the crumbs have hit the limit of the array, loop around and over write unused spots - if (crumbTop == 55) { - crumbTop = 0; - } else { - //Else, bump the top number market of the array - crumbTop = crumbTop + 1; - } - - //Put the newly determined crumb into the array and add to the length - crumbArrayLength = crumbArrayLength + 1; - breadcrumbs[crumbTop] = crumbToAdd; - logging::Info("Crumb Top add"); - - //The array can only hold so many crumbs, once it goes over its cap, stop the bot to prevent un-needed movement - if (crumbArrayLength > 55) { - crumbStopped = true; - logging::Info("Crumb Overload!\nDumping array"); - } -} - -//A function to free a crumb from the array -void CrumbBottomAdd() { - //Once the crumbs have hit the limit of the array, loop around and over write unused spots - if (crumbBottom == 55) { - crumbBottom = 0; - } else { - //Else, bump the top number market of the array - crumbBottom = crumbBottom + 1; - } - - //Subtract from the length to make room for more crumbs - crumbArrayLength = crumbArrayLength - 1; - logging::Info("Crumb Bottom add"); - - //A check to detect if too many crumbs have been removed. Without crumbs the bot will just use random variables in the array. - //To prevent un-nessasary movement, just clear the array and wait for player - if (crumbArrayLength < 0) { - crumbStopped = true; - logging::Info("Crumb Over-Prune!\nDumping array"); - } -} - -//A function to calculate distance from a entity, to the floor -float crumbDistanceToFloor(CachedEntity* ent) { - if (ent->m_Type == ENTITY_PLAYER) { - if (CE_INT(ent, netvar.iFlags) & FL_ONGROUND) return 0; +// Function called after create move +void AfterCreateMove() { + + // Primary Selection handling and selection clearing + auto it = selection.begin(); + while (it != selection.end()) { + int idx = *it; + CachedEntity* entity = ENTITY(idx); + if (CE_BAD(entity)) { + selection.erase(it++); + } else { +#ifndef TEXTMODE + hacks::shared::esp::AddEntityString(entity, "[SELECTED]", colors::orange); + if (fmod(g_GlobalVars->curtime, 2.0f) < 1.0f) { + hacks::shared::esp::SetEntityColor(entity, colors::yellow); + } +#endif + ++it; + } } - Vector& origin = ent->m_vecOrigin; - float v1 = DistanceToGround(origin + Vector(10.0f, 10.0f, 0.0f)); - float v2 = DistanceToGround(origin + Vector(-10.0f, 10.0f, 0.0f)); - float v3 = DistanceToGround(origin + Vector(10.0f, -10.0f, 0.0f)); - float v4 = DistanceToGround(origin + Vector(-10.0f, -10.0f, 0.0f)); - return MIN(v1, MIN(v2, MIN(v3, v4))); + + // Secondary Selection handling + it = selection_secondary.begin(); + while (it != selection_secondary.end()) { + int idx = *it; + CachedEntity* entity = ENTITY(idx); + if (CE_BAD(entity)) { + selection_secondary.erase(it++); + } else { +#ifndef TEXTMODE + hacks::shared::esp::AddEntityString(entity, "[SELECTED (SECONDARY)]", colors::orange); + if (fmod(g_GlobalVars->curtime, 2.0f) < 1.0f) { + hacks::shared::esp::SetEntityColor(entity, colors::yellow); + } +#endif + ++it; + } + } + + // Processing Selection is done, attemt to walk + DoWalking(); } -bool IsBot(CachedEntity* entity) { - if (!ipc::peer) return false; - if (entity->m_Type == ENTITY_PLAYER) { - if (ipc::peer) { - for (unsigned i = 1; i < cat_ipc::max_peers; i++) { - if (!ipc::peer->memory->peer_data[i].free && ipc::peer->memory->peer_user_data[i].friendid == entity->player_info.friendsID) { - return true; +// Function for followbots to use for following, weapon selection, etc... +void DoWalking() { + + if (!bot) return; + + + + // Get our best target, preferably from a steamid + + //following_idx = 0; + CachedEntity* best_target = nullptr; + CachedEntity* target_priority = nullptr; + + // Get ent from steamid + for (int i = 1; i < HIGHEST_ENTITY; i++) { + + CachedEntity* ent = ENTITY(i); + + if (CE_BAD(ent)) continue; + if (ent == LOCAL_E) continue; + if (ent->m_Type != ENTITY_PLAYER) continue; + if (!ent->m_bAlivePlayer) continue; + if (ent->m_bEnemy) continue; + if (g_pLocalPlayer->v_Origin.DistTo(ent->m_vecOrigin) > 3400.0F) continue; + + if (ent->player_info.friendsID == follow_steamid) { + target_priority = ent; + break; + } + } + + // Check Steam id target + if (CE_GOOD(target_priority)) { + // If last target isnt the priority, vis check it + if (target_last != target_priority) { + if (target_priority->IsVisible()) { + target_last = target_priority; + best_target = target_priority; + crumbStopped = true; + } + } else { + best_target = target_priority; + } + } + + // If we cant use steam id target, try someone else + if (roaming && CE_BAD(best_target)) { + + // Check last target if good + if (CE_GOOD(target_last)) { + if (g_pLocalPlayer->v_Origin.DistTo(target_last->m_vecOrigin) < 3400.0F && target_last->m_bAlivePlayer && !crumbStopped) { + best_target = target_last; + } + } + + // Without good target we must find a new one + if (CE_BAD(best_target) || g_GlobalVars->curtime - 2.5F > crumb_prune_timeout) { + + float target_highest_score = -256; + CachedEntity* ent; + target_last = nullptr; + crumbStopped = true; + + for (int i = 0; i < HIGHEST_ENTITY; i++) { + ent = ENTITY(i); + + if (CE_BAD(ent)) continue; + if (ent == LOCAL_E) continue; + if (!ent->m_bAlivePlayer) continue; + + if (ent->m_bEnemy) continue; + if (g_pLocalPlayer->v_Origin.DistTo(ent->m_vecOrigin) > 3400.0F) continue; + // Check activation distance + if (g_pLocalPlayer->v_Origin.DistTo(ent->m_vecOrigin) > (float)follow_activation) continue; + if (!ent->IsVisible()) continue; + + // Distance Priority works in our case + float scr = 4096.0f - g_pLocalPlayer->v_Origin.DistTo(ent->m_vecOrigin); + if (scr > target_highest_score) { + target_highest_score = scr; + target_last = ent; + best_target = ent; } } } } - return false; + + CachedEntity* found_entity = best_target; + // TODO, setting following_idx causes a crash for an unknown reason, probs to do with autoheal. + // I created a different var to take its place and prevent the crash but i need to fix the crash with the externed var. + // For now this works and it will stay like this untill I find a way to fix it + int following_idx2 = 0; + if (CE_GOOD(found_entity)) { + following_idx2 = found_entity->m_IDX; +#ifndef TEXTMODE + hacks::shared::esp::AddEntityString(found_entity, "[FOLLOWING]", colors::green); + hacks::shared::esp::SetEntityColor(found_entity, colors::green); +#endif + } else { + crumbStopped = true; + return; + } + + + + + + // Slot Changer/Mimicer + + // Set a static var for last slot check + static float last_slot_check = 0.0f; + + // If curtime is less than the last time we checked the slot, then reset our check timer + if (g_GlobalVars->curtime < last_slot_check) last_slot_check = 0.0f; + + // If we have a follow target, user settings tell us that we should mess with the slot, the local player is alive, and our target is alive + if (following_idx2 && (always_medigun || mimic_slot) && (g_GlobalVars->curtime - last_slot_check > 1.0f) && !g_pLocalPlayer->life_state && !CE_BYTE(found_entity, netvar.iLifeState)) { + + // We are checking our slot so reset the timer + last_slot_check = g_GlobalVars->curtime; + + // Get the follow targets active weapon + int owner_weapon_eid = (CE_INT(found_entity, netvar.hActiveWeapon) & 0xFFF); + IClientEntity* owner_weapon = g_IEntityList->GetClientEntity(owner_weapon_eid); + + // If both the follow targets and the local players weapons arnt null or dormant + if (owner_weapon && CE_GOOD(g_pLocalPlayer->weapon())) { + + // IsBaseCombatWeapon() + if (vfunc(RAW_ENT(g_pLocalPlayer->weapon()), 190, 0)(RAW_ENT(g_pLocalPlayer->weapon())) && + vfunc(owner_weapon, 190, 0)(owner_weapon)) { + + // Get the players slot numbers and store in some vars + int my_slot = vfunc(RAW_ENT(g_pLocalPlayer->weapon()), 395, 0)(RAW_ENT(g_pLocalPlayer->weapon())); + int owner_slot = vfunc(owner_weapon, 395, 0)(owner_weapon); + + // If the local player is a medic and user settings allow, then keep the medigun out + if (g_pLocalPlayer->clazz == tf_medic && always_medigun) { + if (my_slot != 1) { + g_IEngine->ExecuteClientCmd("slot2"); + } + + // Else we attemt to keep our weapon mimiced with our follow target + } else { + if (my_slot != owner_slot) { + g_IEngine->ExecuteClientCmd(format("slot", owner_slot + 1).c_str()); + } + } + } + } + } + + + + + + // Main followbot code + + + // Switch to different types of following mechanisms depending on the type we need to go to + switch (current_follow_type) { + case EFollowType::VECTOR: // If were using a vector to follow, we just go directly to it + + // If destination_point_time is more than curtime than we reset it to zero + if (destination_point_time > g_GlobalVars->curtime) destination_point_time = 0.0f; + + // If we havent reached our destination and the destination point timeout isnt more than 5 seconds, then we continue to walk to the destination point + if (g_GlobalVars->curtime - destination_point_time < 5.0f) { + + // Walk to the point + followbot::WalkTo(destination_point); + + // If we have reached the destination point then we want to disable the vector followbot + if (g_pLocalPlayer->v_Origin.DistTo(destination_point) < 50.0f) { + current_follow_type = EFollowType::ENTITY; + } + } + // Break from the switch + break; + + case EFollowType::ENTITY: // If were using a player to follow, we use the breadcrumb followbot + + if (CE_GOOD(found_entity)) { + // If the bot is lost but it finds the player again, start the followbot again. + if (crumbStopped) { + crumbForceMove = true; + CrumbReset(); + } + } else { + // If the entity we have isnt good, we stop the crumb followbot + crumbStopped = true; + } + + // Breadcrumb followbot + if (!crumbStopped) { + + // Generate new breadcrumbs made by the player only if they are close to the ground. If the bot is told to generate a starting point, it does that as well. + if ((found_entity->m_vecOrigin.DistTo(breadcrumbs[crumbTop]) > 40.0F || crumbFindNew) && DistanceToGround(found_entity) < 40) { + + // Add to the crumb. + CrumbTopAdd(found_entity->m_vecOrigin); + + // If the bot was forced to select a point, we tell it that we no longer need a new one and clear the bottom crumb to use the newest one + if (crumbFindNew) { + crumbFindNew = false; + CrumbBottomAdd(); + } + + } + + // Prune used crumbs from the stack to make way for new ones when you get close to them. + if (g_pLocalPlayer->v_Origin.DistTo(breadcrumbs[crumbBottom]) < 40.0F ) { + + // Debug Logging + logging::Info("Pruning"); + + // When the bot is forced to move to the player, since they have reached their destination we reset the var + crumbForceMove = false; + + // Check 15 times for close crumbs to prune, this allows simple miss steps to be smoothed out as well as make room for new crumbs + for (int i = 0; i < 15; i++) { + + // When one is close or too high, just bump the array and reset the stuck timer + if (g_pLocalPlayer->v_Origin.DistTo(breadcrumbs[crumbBottom]) < 60.0F && crumbArrayLength > 1) { + CrumbBottomAdd(); + + // When pruning is finished. Break the loop + } else { + crumb_prune_timeout = g_GlobalVars->curtime; + logging::Info("Finish Prune"); + break; + } + } + // Reset stuck timer + crumb_prune_timeout = g_GlobalVars->curtime; + } + + // When player to follow is too far away. the bot cant see the player or the bot is forced to the player, then follow breadcrumbs if movement is allowed + if ((g_pLocalPlayer->v_Origin.DistTo(found_entity->m_vecOrigin) > (float)follow_distance || crumbForceMove) && crumbArrayLength >= 1 && allow_moving) { + followbot::WalkTo(breadcrumbs[crumbBottom]); + + // If a crumb hasnt been pruned in a while, it probably cant travel to it so reset and wait for the player to collect it. + if (g_GlobalVars->curtime - 2.5F > crumb_prune_timeout) { + crumbStopped = true; + logging::Info("Cannot goto next crumb!\nCrumb Lost!"); + } + + // If the bot is next to the player then we clear our crumbs as theres no need to follow previously generated ones. + } else if (g_pLocalPlayer->v_Origin.DistTo(found_entity->m_vecOrigin) < 100.0F && found_entity->IsVisible()) { + CrumbReset(); + crumbForceMove = false; + } + } + } + + + + + + // If we have a follow target, then we attempt to mimic their conditions + if (following_idx2) { + + // If follow target is too far away and the local player is zoomed, then unzoom + if (found_entity->m_vecOrigin.DistTo(LOCAL_E->m_vecOrigin) > 325.0f) { + if (g_pLocalPlayer->bZoomed) g_pUserCmd->buttons |= IN_ATTACK2; + } + + // If found target is heavy and the local player is too, + if (CE_INT(found_entity, netvar.iClass) == tf_heavy && g_pLocalPlayer->clazz == tf_heavy) { + + // If found target is spun up, then spin up too + if (HasCondition(found_entity)) { + g_pUserCmd->buttons |= IN_ATTACK2; + } + } + + // If found target is zoomed + if (HasCondition(found_entity)) { + + // If the local player isnt zoomed and its class is sniper, then zoom in to mimic the followed target + if (!g_pLocalPlayer->bZoomed && g_pLocalPlayer->clazz == tf_sniper) { + g_pUserCmd->buttons |= IN_ATTACK2; + } + } + + // If user settings allow, we attemt to mimic taunting player + if (sync_taunt) { + + // Check if target is taunting + if (HasCondition(found_entity)) { + + // Check if local player isnt taunting + if (!HasCondition(LOCAL_E)) { + g_IEngine->ExecuteClientCmd("taunt"); + } + } + } + + /* + //Check if target is crouching + if () { + + // Check if local player isnt taunting + if (!g_pUserCmd->buttons & IN_DUCK) { + g_pUserCmd->buttons |= IN_DUCK; + } + }*/ + } } +// Used on a bot to select a target to follow +CatCommand follow("fb_follow", "Follows you (or player with SteamID specified)", [](const CCommand& args) { + + // Set our target steam id to the argument put into the command + follow_steamid = strtol(args.Arg(1), nullptr, 10); + + // Tell the followbot to follow entities + current_follow_type = EFollowType::ENTITY; + // Allow the followbot to move + allow_moving = true; +}); + +// Used by the main player to send an ipc request to the bots to follow +CatCommand follow_me("fb_follow_me", "Makes all bots follow you", []() { + + // Check if the ipc server is connected + if (ipc::peer) { + // Get our steam id + unsigned id = g_ISteamUser->GetSteamID().GetAccountID(); + // Send our id through the ipc server + ipc::peer->SendMessage((const char*)&id, 0, ipc::commands::set_follow_steamid, 0, 0); + } +}); + +// User command for cat_fb_tool +CatCommand tool("fb_tool", "Followbot multitool", [](const CCommand& args) { + + // Check if ipc server is connected + if (!ipc::peer) return; + + // If argument is "select" + if (!strcmp(args.Arg(1), "select")) { + logging::Info("FB TOOL -> SELECT"); + + // Check if the shift key is depressed + if (g_IInputSystem->IsButtonDown(ButtonCode_t::KEY_LSHIFT)) { + + // Shift cleans selection.. + selection.clear(); + selection_secondary.clear(); + logging::Info("Selection cleared!"); + + // If the shift key isnt depressed + } else { + + // Make a var and try to get an ent of what we are looking at + int eindex = 0; + WhatIAmLookingAt(&eindex, nullptr); + logging::Info("Selecting entity..."); + + // If the entity isnt null, Add the entity to the selection + if (eindex) { + SelectEntity(eindex); + } + } + + // If argument is "move" + } else if (!strcmp(args.Arg(1), "move")) { + logging::Info("FB TOOL -> MOVE"); + + // Create a vector and attemt to get an end vector from it + Vector destination; + WhatIAmLookingAt(nullptr, &destination); + + // Send the vector through the ipc server and tell the bots to move to it + float array[3] = { destination.x, destination.y, destination.z }; + ipc::peer->SendMessage((const char*)array, MakeMask(), ipc::commands::move_to_vector, nullptr, 0); + + // If argument is "stay" + } else if (!strcmp(args.Arg(1), "stay")) { + logging::Info("FB TOOL -> STAY"); + + // Send a message through the ipc server to notify the bots to stop moving + ipc::peer->SendMessage(nullptr, MakeMask(), ipc::commands::stop_moving, nullptr, 0); + + // If argument is "follow" + } else if (!strcmp(args.Arg(1), "follow")) { + logging::Info("FB TOOL -> FOLLOW"); + + // Send a message through the ipc server to notify the bots to start moving + ipc::peer->SendMessage(nullptr, MakeMask(), ipc::commands::start_moving, nullptr, 0); + } +}); + +// Helper Functions for bot selection + void SelectEntity(int idx) { logging::Info("Selecting entity %i", idx); CachedEntity* entity = ENTITY(idx); @@ -142,43 +517,23 @@ void SelectEntity(int idx) { logging::Info("Selected!"); } } - -void AddMessageHandlers(ipc::peer_t* peer) { - peer->SetCommandHandler(ipc::commands::set_follow_steamid, [](cat_ipc::command_s& command, void* payload) { - logging::Info("IPC Message: now following %ld", *(unsigned*)&command.cmd_data); - hacks::shared::followbot::follow_steamid = *(unsigned*)&command.cmd_data; - //Tell followbot to follow - crumbForceMove = true; - CrumbStart(); - }); - peer->SetCommandHandler(ipc::commands::move_to_vector, [](cat_ipc::command_s& command, void* payload) { - float* data = (float*)&command.cmd_data; - logging::Info("IPC Message: moving to %.2f %.2f %.2f", data[0], data[1], data[2]); - destination_point = Vector(data[0], data[1], data[2]); - destination_point_time = g_GlobalVars->curtime; - destination_reached = false; - //prevent followbot from following - crumbAbleToMove = false; - crumbStopped = true; - }); - peer->SetCommandHandler(ipc::commands::start_moving, [](cat_ipc::command_s& command, void* payload) { - allow_moving = true; - //Tell followbot to follow - crumbAbleToMove = true; - }); - peer->SetCommandHandler(ipc::commands::stop_moving, [](cat_ipc::command_s& command, void* payload) { - allow_moving = false; - crumbStopped = true; - }); -} - -CatCommand follow_me("fb_follow_me", "Makes all bots follow you", []() { - if (ipc::peer) { - unsigned id = g_ISteamUser->GetSteamID().GetAccountID(); - ipc::peer->SendMessage((const char*)&id, 0, ipc::commands::set_follow_steamid, 0, 0); + +// A Function to tell whether an entity input into it is a bot +bool IsBot(CachedEntity* entity) { + if (!ipc::peer) return false; + if (entity->m_Type == ENTITY_PLAYER) { + if (ipc::peer) { + for (unsigned i = 1; i < cat_ipc::max_peers; i++) { + if (!ipc::peer->memory->peer_data[i].free && ipc::peer->memory->peer_user_data[i].friendid == entity->player_info.friendsID) { + return true; + } + } + } } -}); - + return false; +} + +// :thinking: unsigned MakeMask() { unsigned result = 0; if (!ipc::peer) return 0; @@ -194,54 +549,75 @@ unsigned MakeMask() { } return result; } + +// Ipc message handlers. When an ipc event comes from an ipc server, its called below +void AddMessageHandlers(ipc::peer_t* peer) { + + // When the ipc server gives us a steam id to follow, we run the following + peer->SetCommandHandler(ipc::commands::set_follow_steamid, [](cat_ipc::command_s& command, void* payload) { + // Log in console the steam id that were following + logging::Info("IPC Message: now following %ld", *(unsigned*)&command.cmd_data); + // Set our steam id that we want to follow + hacks::shared::followbot::follow_steamid = *(unsigned*)&command.cmd_data; + // Tell the followbot to follow entities + current_follow_type = EFollowType::ENTITY; + }); + + // When the ipc server gives us a vector to follow, we run the following + peer->SetCommandHandler(ipc::commands::move_to_vector, [](cat_ipc::command_s& command, void* payload) { + // Create a var to recieve the payload with + float* data = (float*)&command.cmd_data; + // Log in console the vector that we will attemt to goto + logging::Info("IPC Message: moving to %.2f %.2f %.2f", data[0], data[1], data[2]); + // Set our dest info with the payload data + destination_point = Vector(data[0], data[1], data[2]); + destination_point_time = g_GlobalVars->curtime; + // Notify the followbot to follow vectors + current_follow_type = EFollowType::VECTOR; + }); + + // When the ipc server tells us to start moving, we run the following + peer->SetCommandHandler(ipc::commands::start_moving, [](cat_ipc::command_s& command, void* payload) { + allow_moving = true; + }); + + // When the ipc server tells us to stop moving, we run the following + peer->SetCommandHandler(ipc::commands::stop_moving, [](cat_ipc::command_s& command, void* payload) { + allow_moving = false; + }); +} -CatCommand tool("fb_tool", "Followbot multitool", [](const CCommand& args) { - if (!ipc::peer) return; - if (args.ArgC() == 1) { - // TODO open a gui or something... - } else { - if (!strcmp(args.Arg(1), "select")) { - logging::Info("FB TOOL -> SELECT"); - if (g_IInputSystem->IsButtonDown(ButtonCode_t::KEY_LSHIFT)) { - // Shift cleans selection.. - selection.clear(); - selection_secondary.clear(); - logging::Info("Selection cleared!"); - } else { - logging::Info("Selecting entity..."); - int eindex = 0; - WhatIAmLookingAt(&eindex, nullptr); - if (eindex) { - SelectEntity(eindex); - } - } - } else if (!strcmp(args.Arg(1), "move")) { - logging::Info("FB TOOL -> MOVE"); - Vector destination; - WhatIAmLookingAt(nullptr, &destination); - float array[3] = { destination.x, destination.y, destination.z }; - ipc::peer->SendMessage((const char*)array, MakeMask(), ipc::commands::move_to_vector, nullptr, 0); - } else if (!strcmp(args.Arg(1), "stay")) { - logging::Info("FB TOOL -> STAY"); - ipc::peer->SendMessage(nullptr, MakeMask(), ipc::commands::stop_moving, nullptr, 0); - } else if (!strcmp(args.Arg(1), "follow")) { - logging::Info("FB TOOL -> FOLLOW"); - ipc::peer->SendMessage(nullptr, MakeMask(), ipc::commands::start_moving, nullptr, 0); +// Function for when you want to goto a vector +void WalkTo(const Vector& vector) { + + // Check if the local player is not moving + if (CE_VECTOR(LOCAL_E, netvar.vVelocity).IsZero(1.0f)) { + // Set idle time if we havent already + if (!idle_time) idle_time = g_GlobalVars->curtime; + + // If the time idle is over 2 seconds + if (g_GlobalVars->curtime - idle_time > 2.0f) { + // If the player isnt zoomed, then jump + if (!g_pLocalPlayer->bZoomed) + g_pUserCmd->buttons |= IN_JUMP; + + // Since the vector is close enough we reset our idle timer + } else { + idle_time = 0; } } -}); - -CatCommand follow("fb_follow", "Follows you (or player with SteamID specified)", [](const CCommand& args) { - follow_steamid = strtol(args.Arg(1), nullptr, 10); -}); -CatVar bot(CV_SWITCH, "fb_bot", "0", "This player is a bot", "Set to 1 in followbots' configs"); -CatVar mimic_slot(CV_SWITCH, "fb_mimic_slot", "1", "Mimic selected weapon", "If enabled, this bot will select same weapon slot as the owner"); -CatVar always_medigun(CV_SWITCH, "fb_always_medigun", "1", "Always use Medigun", "Medics will always use Medigun"); -//CatVar sync_taunt(CV_SWITCH, "fb_sync_taunt", "1", "Synchronize taunts", "Bots will taunt if owner is taunting"); + + // Calculate how to get to a vector + auto result = ::ComputeMove(LOCAL_E->m_vecOrigin, vector); + // Push our move to usercmd + g_pUserCmd->forwardmove = result.first; + g_pUserCmd->sidemove = result.second; +} // I've spent 2 days on writing this method. // I couldn't succeed. // Just removed everything and put movement fix code from createmove here. +// Helper function for WalkTo std::pair ComputeMove(const Vector& a, const Vector& b) { Vector diff = (b - a); if (diff.Length() == 0) return { 0, 0 }; @@ -254,247 +630,204 @@ std::pair ComputeMove(const Vector& a, const Vector& b) { float yaw = DEG2RAD(ang.y - g_pUserCmd->viewangles.y); return { cos(yaw) * 450, -sin(yaw) * 450 }; } + + +// Crumb Followbot Helper functions + +// A function to reset the crumb followbot +void CrumbReset() { + + // We just reset the bookkeeping vars for the array, no need to clear the array as everything will be re-written anyways + crumbTop = 0; + crumbBottom = 0; + crumbArrayLength = 0; + crumb_prune_timeout = g_GlobalVars->curtime; + crumbFindNew = true; + crumbStopped = false; + logging::Info("Crumb Reset"); -// I've removed that too early. -void PrintDebug() { -/* - const Vector& a = LOCAL_E->m_vecOrigin; - const Vector& b = last_direction; - - Vector diff = (b - a); - if (diff.Length() == 0) return; - AddSideString(format("dx: ", diff.x)); - AddSideString(format("dy: ", diff.y)); - //float v_cos = diff.x / diff.Length(); - //float rad = acos(v_cos); - //if (diff.y < 0) rad = 2 * PI - rad; - //AddSideString(format("angle: ", rad / PI, " PI")); - float yan = g_Settings.last_angles.y; - float yaw = DEG2RAD(yan); - AddSideString(format("yaw: ", yaw / PI, " PI")); - //float rad_diff = yaw - rad; - //AddSideString(format("diff: ", rad_diff / PI, " PI")); - - auto move = ComputeMove(a, b); - AddSideString(format("forward: ", move.first)); - AddSideString(format("side: ", move.second));*/ } -void WalkTo(const Vector& vector) { - if (CE_VECTOR(LOCAL_E, netvar.vVelocity).IsZero(1.0f)) { - if (!idle_time) idle_time = g_GlobalVars->curtime; - if (LOCAL_E->m_vecOrigin.DistTo(vector) > 150.0f) { - if (g_GlobalVars->curtime - idle_time > 2.0f) { - if (!g_pLocalPlayer->bZoomed) - g_pUserCmd->buttons |= IN_JUMP; - } - } else { - idle_time = 0; - } - } - auto result = ComputeMove(LOCAL_E->m_vecOrigin, vector); - - g_pUserCmd->forwardmove = result.first; - g_pUserCmd->sidemove = result.second; +// A function to place a crumb into the array +void CrumbTopAdd(Vector crumbToAdd) { + + // Once the crumbs have hit the limit of the array, loop around and over write unused spots + if (crumbTop == MAX_CRUMBS) { + crumbTop = 0; + } else { + // Else, bump the top number market of the array + crumbTop++; + } + + // Put the newly determined crumb into the array and add to the length + crumbArrayLength++; + breadcrumbs[crumbTop] = crumbToAdd; + logging::Info("Crumb Top add"); + + // The array can only hold so many crumbs, once it goes over its cap, stop the bot to prevent un-needed movement + if (crumbArrayLength > MAX_CRUMBS) { + CrumbReset(); + crumbStopped = true; + logging::Info("Crumb Overload!\nDumping array"); + } } -void AfterCreateMove() { - auto it = selection.begin(); - while (it != selection.end()) { - int idx = *it; - CachedEntity* entity = ENTITY(idx); - if (CE_BAD(entity)) { - selection.erase(it++); - } else { - hacks::shared::esp::AddEntityString(entity, "[SELECTED]", colors::orange); - if (fmod(g_GlobalVars->curtime, 2.0f) < 1.0f) { - hacks::shared::esp::SetEntityColor(entity, colors::yellow); - } - ++it; - } - } - it = selection_secondary.begin(); - while (it != selection_secondary.end()) { - int idx = *it; - CachedEntity* entity = ENTITY(idx); - if (CE_BAD(entity)) { - selection_secondary.erase(it++); - } else { - hacks::shared::esp::AddEntityString(entity, "[SELECTED (SECONDARY)]", colors::orange); - if (fmod(g_GlobalVars->curtime, 2.0f) < 1.0f) { - hacks::shared::esp::SetEntityColor(entity, colors::yellow); - } - ++it; - } - } - DoWalking(); +// A function to free a crumb from the array +void CrumbBottomAdd() { + + // Once the crumbs have hit the limit of the array, loop around and over write unused spots + if (crumbBottom == MAX_CRUMBS) { + crumbBottom = 0; + } else { + // Else, bump the top number market of the array + crumbBottom++; + } + + // Subtract from the length to make room for more crumbs + crumbArrayLength--; + logging::Info("Crumb Bottom add"); + + // A check to detect if too many crumbs have been removed. Without crumbs the bot will just use random variables in the array. + // To prevent un-nessasary movement, just clear the array and wait for player + if (crumbArrayLength < 0) { + CrumbReset(); + crumbStopped = true; + logging::Info("Crumb Over-Prune!\nDumping array"); + } } - -void DoWalking() { +#ifndef TEXTMODE +// Function called when we need to draw onto the screen +void Draw() { + + // Dont draw if bot isnt true if (!bot) return; - following_idx = 0; - for (int i = 1; i < 32 && i < HIGHEST_ENTITY; i++) { - CachedEntity* ent = ENTITY(i); - if (CE_BAD(ent)) continue; - if (ent->player_info.friendsID == follow_steamid) { - following_idx = i; + + // If user settings allow, draw our breadcrumbs + if (crumb_draw) + DrawFollowbot(); +} + +// A Function for when we want to draw out the crumbs in the array onto the screen +void DrawFollowbot() { + + // Usefull debug info to know + AddSideString(format("Array Length: ", crumbArrayLength)); + AddSideString(format("Top Crumb: ", crumbTop)); + AddSideString(format("Bottom Crumb: ", crumbBottom)); + AddSideString(format("Crumb Stopped: ", crumbStopped)); + AddSideString(format("Curtime: ", g_GlobalVars->curtime)); + AddSideString(format("Timeout: ", crumb_prune_timeout)); + + + // Disabled as the enum was misbehaving for an unknown reason + + /*switch (current_follow_type) { + case EFollowType::VECTOR: // If our follow type is a vector, then we just draw a rect on the vector + + // Create a vector for the screen, run world to screen to bring the world vector into the screen vector, then draw a rect at the point + Vector scn; + draw::WorldToScreen(destination_point, scn); + drawgl::FilledRect(scn.x - 3, scn.y - 3, 6, 6); + // Return as we are finished + break; + + case EFollowType::ENTITY: // If our follow type is entity, then we draw out the crumbs here + logging::Info("Drawcrumb1"); + // Check if we have enough crumbs to draw a line between + if (crumbArrayLength < 2) { + + // If not, we check if we have 1 point and draw on it + if (crumbArrayLength == 1) { + + // Get the entity vector to screen and draw a rect on it + Vector scn; + draw::WorldToScreen(breadcrumbs[crumbBottom], scn); + drawgl::FilledRect(scn.x - 3, scn.y - 3, 6, 6); + } + + // Return as we have nothing else to do break; } - } - CachedEntity* found_entity = ENTITY(following_idx); - static float last_slot_check = 0.0f; - if (g_GlobalVars->curtime < last_slot_check) last_slot_check = 0.0f; + // Create book keeping vars to draw with + Vector scnSrt, scnEnd; + int tmpCrumb1, tmpCrumb2; - if (following_idx && (always_medigun || mimic_slot) && (g_GlobalVars->curtime - last_slot_check > 1.0f) && !g_pLocalPlayer->life_state && !CE_BYTE(found_entity, netvar.iLifeState)) { - int owner_weapon_eid = (CE_INT(found_entity, netvar.hActiveWeapon) & 0xFFF); - IClientEntity* owner_weapon = g_IEntityList->GetClientEntity(owner_weapon_eid); - if (owner_weapon && CE_GOOD(g_pLocalPlayer->weapon())) { - // IsBaseCombatWeapon() - if (vfunc(RAW_ENT(g_pLocalPlayer->weapon()), 190, 0)(RAW_ENT(g_pLocalPlayer->weapon())) && - vfunc(owner_weapon, 190, 0)(owner_weapon)) { - int my_slot = vfunc(RAW_ENT(g_pLocalPlayer->weapon()), 395, 0)(RAW_ENT(g_pLocalPlayer->weapon())); - int owner_slot = vfunc(owner_weapon, 395, 0)(owner_weapon); - if (g_pLocalPlayer->clazz == tf_medic && always_medigun) { - if (my_slot != 1) { - g_IEngine->ExecuteClientCmd("slot2"); - } - } else { - if (my_slot != owner_slot) { - g_IEngine->ExecuteClientCmd(format("slot", owner_slot + 1).c_str()); - } - } - } - // FIXME proper classes - // FIXME IsBaseCombatWeapon + // For loop to draw through the crumbs + for (int i = 0; i < crumbArrayLength; i++) { + + // We need 2 crumbs to draw a line, so we get the number in the array for 2 crumbs + tmpCrumb1 = crumbBottom + i; + tmpCrumb2 = crumbBottom + i + 1; + + // Correction for array numbers when one goes over our limit + if (tmpCrumb1 >= MAX_CRUMBS) + tmpCrumb1 - MAX_CRUMBS; + if (tmpCrumb2 >= MAX_CRUMBS) + tmpCrumb1 - MAX_CRUMBS; + + // Take our 2 crumbs and get a position on the screen + draw::WorldToScreen(breadcrumbs[tmpCrumb1], scnSrt); + draw::WorldToScreen(breadcrumbs[tmpCrumb2], scnEnd); + + // Draw a line from one crumb to the other + drawgl::Line(scnSrt.x, scnSrt.y, scnEnd.x - scnSrt.x, scnEnd.y - scnSrt.y, colors::white); + + // If this is our first iteration, draw a box on 1 + if (i == 1) + drawgl::FilledRect(scnSrt.x - 3, scnSrt.y - 3, 6, 6); } - last_slot_check = g_GlobalVars->curtime; - } + break; + }*/ - //Nullified Cats Followbot code used for followbot tool - //Keeping this for the followbot move and stay commands - //TODO remove player follow from this or change it to be a backup for the crumb follow bot - if (!crumbAbleToMove) { - if (destination_point_time > g_GlobalVars->curtime) destination_point_time = 0.0f; - - if (!destination_reached && (g_GlobalVars->curtime - destination_point_time < 5.0f)) { - WalkTo(destination_point); - last_direction = destination_point; - if (g_pLocalPlayer->v_Origin.DistTo(destination_point) < 50.0f) destination_reached = true; - } else if (following_idx) { - if (allow_moving) { - if (!found_entity->IsVisible()) { - if (!lost_time) { - lost_time = g_GlobalVars->curtime; - } - if (g_GlobalVars->curtime - lost_time < 2.0f) { - WalkTo(last_direction); - } - } else { - lost_time = 0; - if (found_entity->m_vecOrigin.DistTo(LOCAL_E->m_vecOrigin) > 150.0f) { - WalkTo(found_entity->m_vecOrigin); - } - last_direction = found_entity->m_vecOrigin; - } - } - } - } - - //Breadcrumb followbot - if (allow_moving && crumbAbleToMove && !crumbStopped) { - //Generate new breadcrumbs made by the player only if they are close to the ground. If the bot is told to generate a starting point, it does that as well. - if ((found_entity->m_vecOrigin.DistTo(breadcrumbs[crumbTop]) > 40.0F || crumbFindNew) && crumbDistanceToFloor(found_entity) < 25) { - //Add to the crumb. - CrumbTopAdd(found_entity->m_vecOrigin); - - //If the bot was forced to select a point, add a buffer crumb and bump to the newly selected point and use it - if (crumbFindNew) { - crumbFindNew = false; - CrumbTopAdd(found_entity->m_vecOrigin); - CrumbBottomAdd(); - } - } - - //Prune used crumbs from the stack to make way for new ones when you get close to them. - if (g_pLocalPlayer->v_Origin.DistTo(breadcrumbs[crumbBottom]) < 40.0F) { - //Debug Logging - logging::Info("Pruning"); - - //When the bot is forced to move to the player, since they have reached their destination we reset the var - crumbForceMove = false; - - //Check 15 times for close crumbs to prune, this allows simple miss steps to be smoothed out as well as make room for new crumbs - for (int i = 0; i < 15; i++) { - //When one is close or too high, just bump the array and reset the stuck timer - if (g_pLocalPlayer->v_Origin.DistTo(breadcrumbs[crumbBottom]) < 60.0F) { - CrumbBottomAdd(); - - //When pruning is finished. Break the loop - } else { - crumbWaitPrune = g_GlobalVars->curtime; - logging::Info("Finish Prune"); - break; - } - } - //Reset stuck timer - crumbWaitPrune = g_GlobalVars->curtime; - } - - //When the player is not visible to the bot, within 5 seconds of it not being visible we stop the bot and wait for the player to collect it - if (!found_entity->IsVisible()) { - if (g_GlobalVars->curtime - 5.0F > crumbWaitVis && g_GlobalVars->curtime - 2.5F > crumbWaitPrune) { - //crumbStopped = true; - logging::Info("Crumb Lost!"); - } - - //If the player is visible, then reset our lost timer. - } else crumbWaitVis = g_GlobalVars->curtime; - - - //When player to follow is too far away. the bot cant see the player or the bot is forced to the player, then follow breadcrumbs - if ((g_pLocalPlayer->v_Origin.DistTo(found_entity->m_vecOrigin) > (float)crumbFollowDistance || crumbForceMove) && crumbArrayLength >= 1 ) { - WalkTo(breadcrumbs[crumbBottom]); - - //If a crumb hasnt been pruned in a while, it probably cant travel to it so reset and wait for the player to collect it. - if (g_GlobalVars->curtime - 2.5F > crumbWaitPrune) { - crumbStopped = true; - logging::Info("Cannot goto next crumb!\nCrumb Lost!"); - } - - //If the bot is next to the player then we clear our crumbs as theres no need to follow previously generated ones. - } else if (g_pLocalPlayer->v_Origin.DistTo(found_entity->m_vecOrigin) < 100.0F && found_entity->IsVisible()) { - crumbForceMove = false; - crumbStopped = true; - CrumbStart(); - } - - //If the bot is lost but it finds the player again, start the followbot again. - } else if (crumbStopped && allow_moving && crumbAbleToMove && found_entity->IsVisible() && (g_pLocalPlayer->v_Origin.DistTo(found_entity->m_vecOrigin) < 3000.0F)) { - crumbForceMove = true; - CrumbStart(); - logging::Info("Crumb found player!"); - } - - if (following_idx) { - if (found_entity->m_vecOrigin.DistTo(LOCAL_E->m_vecOrigin) > 150.0f) { - if (LOCAL_E->m_vecOrigin.DistTo(found_entity->m_vecOrigin) > 350.0f) { - if (g_pLocalPlayer->bZoomed) g_pUserCmd->buttons |= IN_ATTACK2; - } - } - if (CE_INT(found_entity, netvar.iClass) == tf_heavy && g_pLocalPlayer->clazz == tf_heavy) { - if (HasCondition(found_entity)) { - g_pUserCmd->buttons |= IN_ATTACK2; - } - } - if (HasCondition(found_entity)) { - if (!g_pLocalPlayer->bZoomed && g_pLocalPlayer->clazz == tf_sniper) { - g_pUserCmd->buttons |= IN_ATTACK2; - } + + // Not using switch due to switch not working correctly + if (crumbArrayLength < 2) { + + // If not, we check if we have 1 point and draw on it + if (crumbArrayLength == 1) { + + // Get the entity vector to screen and draw a rect on it + Vector scn; + draw::WorldToScreen(breadcrumbs[crumbBottom], scn); + drawgl::FilledRect(scn.x - 3, scn.y - 3, 6, 6); } + + // Return as we have nothing else to do + return; } -} + // Create book keeping vars to draw with + Vector scnSrt, scnEnd; + int tmpCrumb1, tmpCrumb2; + + // For loop to draw through the crumbs + for (int i = 0; i < crumbArrayLength; i++) { + + // We need 2 crumbs to draw a line, so we get the number in the array for 2 crumbs + tmpCrumb1 = crumbBottom + i; + tmpCrumb2 = crumbBottom + i + 1; + + // Correction for array numbers when one goes over our limit + if (tmpCrumb1 >= MAX_CRUMBS) + tmpCrumb1 - MAX_CRUMBS; + if (tmpCrumb2 >= MAX_CRUMBS) + tmpCrumb2 - MAX_CRUMBS; + + // Take our 2 crumbs and get a position on the screen + draw::WorldToScreen(breadcrumbs[tmpCrumb1], scnSrt); + draw::WorldToScreen(breadcrumbs[tmpCrumb2], scnEnd); + + // Draw a line from one crumb to the other + drawgl::Line(scnSrt.x, scnSrt.y, scnEnd.x - scnSrt.x, scnEnd.y - scnSrt.y, colors::white); + + // If this is our first iteration, draw a box on 1 + if (i == 0) + drawgl::FilledRect(scnSrt.x - 3, scnSrt.y - 3, 6, 6); + } + return; +} +#endif }}} #endif diff --git a/src/hacks/FollowBot.h b/src/hacks/FollowBot.h index a97cdfd8..2e60a5f2 100644 --- a/src/hacks/FollowBot.h +++ b/src/hacks/FollowBot.h @@ -18,19 +18,34 @@ class CachedEntity; namespace hacks { namespace shared { namespace followbot { -extern CatCommand move_to_crosshair; -extern CatCommand follow; -extern CatCommand follow_entity; +enum class EFollowType { + VECTOR, // When we need to goto a vector + ENTITY // when we dont have a specific steamid, but we still want to follow an entity +}; + +//extern CatCommand move_to_crosshair; +//extern CatCommand follow; +//extern CatCommand follow_entity; extern CatVar bot; extern unsigned follow_steamid; extern int following_idx; bool IsBot(CachedEntity* entity); -void DoWalking(); -void PrintDebug(); void AddMessageHandlers(ipc::peer_t* peer); void AfterCreateMove(); +#ifndef TEXTMODE +void Draw(); +#endif +void CrumbReset(); +void CrumbTopAdd(Vector crumbToAdd); +void CrumbBottomAdd(); +void DoWalking(); +void DrawFollowbot(); +std::pair ComputeMove(const Vector& a, const Vector& b); +void WalkTo(const Vector& vector); +unsigned MakeMask(); +void SelectEntity(int idx); }}} diff --git a/src/hacks/HealArrows.cpp b/src/hacks/HealArrows.cpp new file mode 100644 index 00000000..94ee9b52 --- /dev/null +++ b/src/hacks/HealArrows.cpp @@ -0,0 +1,95 @@ +/* + * HealArrows.cpp + * + * Created on: Jun 1, 2017 + * Author: nullifiedcat + */ + +#include "../common.h" + +namespace hacks { namespace tf2 { namespace healarrow { + +static CatVar healarrow_charge(CV_FLOAT, "healarrow_charge", "0.25", "Healarrow Charge"); +static CatVar healarrow_timeout(CV_FLOAT, "healarrow_timeout", "2", "Healarrow Timeout"); +static CatVar healarrow(CV_SWITCH, "healarrow", "0", "Heal Arrow"); +static CatVar healarrow_callout(CV_SWITCH, "healarrow_callout", "0", "Call Out", "Send a message to chat when you heal someone with an arrow"); +static CatVar healarrow_callout_message(CV_STRING, "healarrow_callout_text", "Hey %%, I've just healed you for $$ HP! Your health is now ##.", "Call Out Text", "Formatting:\n%% - player name\n$$ - healing amount\n## - new health\n@@ - old health"); + +float healarrow_time = 0.0f; + +class HealArrowListener : public IGameEventListener { +public: + virtual void FireGameEvent(KeyValues* event) { + if (!healarrow) return; + if (!healarrow_callout) return; + if (CE_BAD(LOCAL_W)) return; + if (LOCAL_W->m_iClassID != CL_CLASS(CTFCompoundBow)) return; + std::string name(event->GetName()); + if (name == "player_hurt") { + int attacker = event->GetInt("attacker"); + int victim = event->GetInt("userid"); + int eid = g_IEngine->GetPlayerForUserID(attacker); + int vid = g_IEngine->GetPlayerForUserID(victim); + if (eid == g_IEngine->GetLocalPlayer()) { + int damageamount = event->GetInt("damageamount"); + if (damageamount < 0) { + player_info_s pinfo; + if (g_IEngine->GetPlayerInfo(vid, &pinfo)) { + std::string msg(healarrow_callout_message.GetString()); + ReplaceString(msg, "$$", std::to_string(-damageamount)); + int health = event->GetInt("health"); + ReplaceString(msg, "##", std::to_string(health)); + ReplaceString(msg, "@@", std::to_string(health + damageamount)); + ReplaceString(msg, "%%", pinfo.name); + chat_stack::Say(msg); + } + } + } + } + } +}; + +HealArrowListener listener; + +void Init() { + g_IGameEventManager->AddListener(&listener, false); +} + +void CreateMove() { + if (CE_BAD(LOCAL_W)) return; + if (healarrow) { + if (g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFCompoundBow)) { + if (healarrow_time > g_GlobalVars->curtime) healarrow_time = 0.0f; + float begincharge = CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flChargeBeginTime); + float charge = 0; + if (begincharge != 0) { + charge = g_GlobalVars->curtime - begincharge; + if (charge > 1.0f) charge = 1.0f; + } + if (g_pUserCmd->command_number && ((g_GlobalVars->curtime - healarrow_time) > float(healarrow_timeout)) && (charge > (float)healarrow_charge) && (g_pUserCmd->buttons & IN_ATTACK)) { + command_number_mod[g_pUserCmd->command_number] = g_pUserCmd->command_number + 450; + g_pUserCmd->buttons &= ~IN_ATTACK; + healarrow_time = g_GlobalVars->curtime; + logging::Info("healarrow"); + } + } + } +} + +void Draw() { +#ifndef TEXTMODE + if (healarrow) { + if ((g_GlobalVars->curtime - healarrow_time) < float(healarrow_timeout)) { + AddCenterString(format("Heal arrow charge: ", int(min(100.0f, (g_GlobalVars->curtime - healarrow_time) / float(healarrow_timeout)) * 100.0f), '%'), colors::yellow); +// AddCenterString(format("Heal arrow time: ", healarrow_time)); + } else { + AddCenterString("Heal arrow ready", colors::green); + } + } +#else + logging::Info("[WTF] THIS SHOULD NEVER BE CALLED!!! CALL THE POLICE!!!"); +#endif +} + +}}} + diff --git a/src/hacks/HealArrows.hpp b/src/hacks/HealArrows.hpp new file mode 100644 index 00000000..9e8bfd02 --- /dev/null +++ b/src/hacks/HealArrows.hpp @@ -0,0 +1,16 @@ +/* + * HealArrows.hpp + * + * Created on: Jun 1, 2017 + * Author: nullifiedcat + */ + +#pragma once + +namespace hacks { namespace tf2 { namespace healarrow { + +void CreateMove(); +void Draw(); +void Init(); + +}}} diff --git a/src/hacks/IHack.h b/src/hacks/IHack.h deleted file mode 100644 index 422257d9..00000000 --- a/src/hacks/IHack.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * IHack.h - * - * Created on: Oct 5, 2016 - * Author: nullifiedcat - */ - -#ifndef IHACK_H_ -#define IHACK_H_ - -#include "../beforecheaders.h" -#include -#include "../aftercheaders.h" - -class CUserCmd; -class ConVar; -class CatVar; -class ConCommand; -class CCommand; -class CachedEntity; - -#define DECLARE_HACK_SINGLETON(x) \ -extern x* g_ph##x; - -#define DEFINE_HACK_SINGLETON(x) \ -x* g_ph##x = 0; - -class IHack { -public: - inline virtual ~IHack() {}; - // Deprecated - /* - inline virtual void PaintTraverse(void*, unsigned int, bool, bool) {}; - inline virtual bool CreateMove(void*, float, CUserCmd*) { return true; }; - inline virtual void LevelInit(const char*) {}; - inline virtual void LevelShutdown() {}; - */ - inline virtual void Draw() {}; - inline virtual void ProcessUserCmd(CUserCmd*) {}; - inline virtual void OnLevelInit() {}; - inline virtual void OnLevelShutdown() {}; -}; - -#endif /* IHACK_H_ */ diff --git a/src/hacks/KillSay.cpp b/src/hacks/KillSay.cpp index 71cb0397..8ec75c48 100644 --- a/src/hacks/KillSay.cpp +++ b/src/hacks/KillSay.cpp @@ -8,13 +8,12 @@ #include "KillSay.h" #include "../common.h" #include "../sdk.h" -#include namespace hacks { namespace shared { namespace killsay { static CatEnum killsay_enum({"NONE", "CUSTOM", "DEFAULT", "NCC - OFFENSIVE", "NCC - MLG"}); static CatVar killsay_mode(killsay_enum, "killsay", "0", "Killsay", "Defines source of killsay lines. CUSTOM killsay file must be set in cat_killsay_file and loaded with cat_killsay_reload (Use console!)"); -static CatVar filename(CV_STRING, "killsay_file", "killsays.txt", "Killsay file (~/.cathook/)", "Killsay file name. Should be located in ~/.cathook folder."); +static CatVar filename(CV_STRING, "killsay_file", "killsays.txt", "Killsay file", "Killsay file name. Should be located in cathook data folder"); static CatCommand reload("killsay_reload", "Reload killsays", Reload); const std::string tf_classes_killsay[] = { @@ -83,6 +82,9 @@ void Reload() { void Init() { g_IEventManager2->AddListener(&getListener(), (const char*)"player_death", false); + filename.InstallChangeCallback([](IConVar* var, const char* pszOV, float flOV) { + file.TryLoad(std::string(filename.GetString())); + }); } void Shutdown() { diff --git a/src/hacks/LagExploit.cpp b/src/hacks/LagExploit.cpp index 44dfe963..36065d68 100644 --- a/src/hacks/LagExploit.cpp +++ b/src/hacks/LagExploit.cpp @@ -12,7 +12,7 @@ namespace hacks { namespace shared { namespace lagexploit { CatVar toggle(CV_SWITCH, "removecond_toggle", "0", "Toggle Lag Exploit", "Toggle lag exploit (RemoveCond)"); CatVar key(CV_KEY, "removecond_key", "0", "RemoveCond Key"); CatVar lagMasterSwitch(CV_SWITCH, "removecond_master", "1", "Master Lag Exploit Switch", "Master switch for the lag exploit\nDisabling this disables everything else that uses remove conds"); -CatVar lagValue(CV_INT, "removecond_value", "450", "RemoveCond Value", "Value of user cmds to spam with"); +CatVar lagValue(CV_INT, "removecond_value", "900", "RemoveCond Value", "Value of user cmds to spam with"); CatCommand do_lagexploit("removecond", "RemoveCond (for use in scripts)", []() { AddExploitTicks(6); @@ -23,6 +23,7 @@ CatVar clear_taunt(CV_SWITCH, "removecond_taunt", "0", "Remove Taunting"); CatVar clear_bleeding(CV_SWITCH, "removecond_bleeding", "0", "Remove Bleeding"); CatVar clear_stun(CV_SWITCH, "removecond_stun", "0", "Remove Stun"); CatVar instant_uncloak(CV_SWITCH, "instant_decloak", "0", "Insta Decloak", "Decloaks you on attack"); +CatVar instant_rezoom(CV_SWITCH, "instant_rezoom", "0", "Instant rezoom", "Allows you to instantly zoom after you shoot\nGreat for precharging charged shots before you can fire again\nOccasionally fails"); CatCommand reset_command_number("debug_reset_cmd_number", "", []() { *(int*)((unsigned)g_IBaseClientState + offsets::lastoutgoingcommand()) = 1; @@ -35,38 +36,14 @@ int exticks = 0; void AddExploitTicks(int ticks) { exticks = max(ticks, exticks); } - + +// Instant re-zoom storage vars +bool insRezoomDepressed = false; +bool insRezoomMain = false; float instant_rezoom_tick = 0; bool instant_rezoom_timer_active = false; int instant_rezoom_timer_step = 0; -//Instant zoom -void InstantZoom() { - if (!instant_rezoom_timer_active) { - //Setup - instant_rezoom_timer_active = true; - instant_rezoom_timer_step = 0; - instant_rezoom_tick = 12; - } else if (instant_rezoom_tick > 0 && instant_rezoom_timer_step == 0){ - instant_rezoom_tick--; - } else if (instant_rezoom_timer_step == 0) { - //Remove zoom cond - AddExploitTicks(6); - instant_rezoom_tick = 75; - instant_rezoom_timer_step = 1; - } else if (instant_rezoom_tick > 35 && instant_rezoom_timer_step == 1) { - instant_rezoom_tick--; - } else if (!g_pLocalPlayer->bZoomed && instant_rezoom_tick > 0) { - //Re-Zoom - instant_rezoom_timer_step == 2; - instant_rezoom_tick--; - if (!g_pLocalPlayer->bZoomed) g_pUserCmd->buttons |= IN_ATTACK2; - } else { - //Stop the function - instant_rezoom_timer_active = false; - hacks::shared::aimbot::instant_rezoom_shoot = false; - } -} bool ExploitActive() { if (toggle) return true; @@ -79,33 +56,146 @@ bool ExploitActive() { return false; } +static CatVar mini_lag_exploit(CV_INT, "lagexploit_mini", "0", "Mini Lag Exploit"); +static CatVar instant_weapon_switch(CV_SWITCH, "instant_weapon_switch", "0", "Instant weapon switch"); +static CatVar infinite_packs(CV_SWITCH, "infinite_packs", "0", "Infinite Pickups", "Activate removecond when standing on pickups while having not full HP/Ammo"); + void CreateMove() { + if (CE_BAD(LOCAL_E)) return; if (exticks > 0) exticks--; - //Var from aimbot.cpp to tell when a shot is made - if (hacks::shared::aimbot::instant_rezoom_shoot) InstantZoom(); + + // Pasted from kathook + static int lastweapon = 0; + if (instant_weapon_switch && lastweapon != g_pUserCmd->weaponselect) { + AddExploitTicks(1); + } + lastweapon = g_pUserCmd->weaponselect; + static bool flag = false; if (!exticks) { if (instant_uncloak && HasCondition(LOCAL_E)) { - if (g_pUserCmd->buttons & IN_ATTACK) AddExploitTicks(1); + if (g_pUserCmd->buttons & (IN_ATTACK)) { +// if (!flag) { + AddExploitTicks(1); + logging::Info("Uncloaking"); + flag = true; +// } + } else { + flag = false; + } } + if (clear_fire && HasCondition(LOCAL_E)) AddExploitTicks(3); if (clear_bleeding && HasCondition(LOCAL_E)) AddExploitTicks(3); if (clear_taunt && HasCondition(LOCAL_E)) AddExploitTicks(3); if (clear_stun && HasCondition(LOCAL_E)) AddExploitTicks(3); - } -} -void GetUserCmd(CUserCmd* cmd, int sequence_number) { - if (!ExploitActive()) return; + // Check if user settings allow Instant re-zoom + if (instant_rezoom) { + // Is +attack is being used, set a holder var and wait untill it is depressed + if (g_pUserCmd->buttons & IN_ATTACK && g_pLocalPlayer->bZoomed && !insRezoomMain) { + insRezoomDepressed = true; + // If +attack is not used while the holder var tells us it was depressed, then start running instant re-zoom + } else if (!(g_pUserCmd->buttons & IN_ATTACK) && g_pLocalPlayer->bZoomed && insRezoomDepressed) { + insRezoomDepressed = false; + insRezoomMain = true; + // Some instant recoom logic, its based on timers due to the way the lag exploit acts apon it. + // If it would have been done better, I would do so but this works fine as is... + } else if (insRezoomMain) { + if (!instant_rezoom_timer_active) { + //Setup + instant_rezoom_timer_active = true; + instant_rezoom_timer_step = 0; + instant_rezoom_tick = 12; + } else if (instant_rezoom_tick > 0 && instant_rezoom_timer_step == 0){ + instant_rezoom_tick--; + } else if (instant_rezoom_timer_step == 0) { + //Remove zoom cond + AddExploitTicks(3); + instant_rezoom_tick = 76; + instant_rezoom_timer_step = 1; + } else if (instant_rezoom_tick > 38 && instant_rezoom_timer_step == 1) { + instant_rezoom_tick--; + } else if (!g_pLocalPlayer->bZoomed && instant_rezoom_tick > 0) { + //Re-Zoom + instant_rezoom_timer_step == 2; + instant_rezoom_tick--; + if (!g_pLocalPlayer->bZoomed) g_pUserCmd->buttons |= IN_ATTACK2; + } else { + //Stop the function + instant_rezoom_timer_active = false; + insRezoomMain = false; + } + } + } + + // Infinite pickups (health and ammo) + if (infinite_packs && CE_GOOD(LOCAL_E)) { + ICollideable* p = RAW_ENT(LOCAL_E)->GetCollideable(); + const Vector& max1 = p->OBBMaxs() + RAW_ENT(LOCAL_E)->GetAbsOrigin(); + const Vector& min1 = p->OBBMins() + RAW_ENT(LOCAL_E)->GetAbsOrigin(); + for (int i = 1; i < entity_cache::max; i++) { + CachedEntity* e = ENTITY(i); + // CE_BAD is used to prevent removeconding on empty spaces where the item hasn't respawned + // Class check to ensure entity is pickup item + if (CE_BAD(e) || e->m_iClassID != CL_CLASS(CBaseAnimating)) { + continue; + } + + ICollideable* c = RAW_ENT(e)->GetCollideable(); + + // Bounds check + const Vector& max2 = c->OBBMaxs() + e->m_vecOrigin + Vector(8, 8, 8); + const Vector& min2 = c->OBBMins() + e->m_vecOrigin - Vector(8, 8, 8); + if ( + (min1.x <= max2.x && max1.x >= min2.x) && + (min1.y <= max2.y && max1.y >= min2.y) && + (min1.z <= max2.z && max1.z >= min2.z) ) { + //logging::Info("Collision with %d", i); + + // Lag for health + if (LOCAL_E->m_iHealth < LOCAL_E->m_iMaxHealth && (e->m_ItemType == ITEM_HEALTH_SMALL || e->m_ItemType == ITEM_HEALTH_MEDIUM || e->m_ItemType == ITEM_HEALTH_LARGE) ) { + AddExploitTicks(3); + } + // Lag for ammo / metal + // TODO: Alternative to - LOCAL_E->m_iAmmo < LOCAL_E->m_iMaxAmmo + // That is pseudocode but checking each weapon for ammo + engie for metal would be ideal + if ((e->m_ItemType == ITEM_AMMO_SMALL || e->m_ItemType == ITEM_AMMO_MEDIUM || e->m_ItemType == ITEM_AMMO_LARGE) ) { + AddExploitTicks(3); + } + } + } + } + } + // More paste from kathook + if (g_pUserCmd->buttons & (IN_ATTACK | IN_ATTACK2)) { + flag = true; + } else { + flag = false; + } + + // Previously was in GetUserCmd + // Thanks Blackfire for helping me improve removecond! + + if (!g_pUserCmd) return; + if (!g_pUserCmd->command_number) return; if (!lagMasterSwitch) return; - if (!cmd) return; - if (!cmd->command_number) return; - cmd->command_number += (int)lagValue; - *(int*)((unsigned)g_IBaseClientState + offsets::lastoutgoingcommand()) += (int)lagValue; - //*(INetChannel**)((unsigned)g_IBaseClientState + offsets::m_NetChannel()); + int amount = int(lagValue); + if (!ExploitActive()) { + amount = int(mini_lag_exploit); + } + + + if (!amount) return; + // Modifying command_number and lastoutgoingcommand turned out to be useless + + //cmd->command_number += amount; + //*(int*)((unsigned)g_IBaseClientState + offsets::lastoutgoingcommand()) += amount; + INetChannel* ch = (INetChannel*)g_IEngine->GetNetChannelInfo(); int& m_nOutSequenceNr = *(int*)((unsigned)ch + offsets::m_nOutSequenceNr()); - m_nOutSequenceNr += (int)lagValue; + m_nOutSequenceNr += amount; + } }}} diff --git a/src/hacks/LagExploit.hpp b/src/hacks/LagExploit.hpp index c3297a2f..2aef6837 100644 --- a/src/hacks/LagExploit.hpp +++ b/src/hacks/LagExploit.hpp @@ -17,7 +17,6 @@ namespace hacks { namespace shared { namespace lagexploit { void CreateMove(); void AddExploitTicks(int ticks); bool ExploitActive(); -void GetUserCmd(CUserCmd*, int); }}} diff --git a/src/hacks/Misc.cpp b/src/hacks/Misc.cpp index 3b22d04a..83c48d73 100644 --- a/src/hacks/Misc.cpp +++ b/src/hacks/Misc.cpp @@ -12,7 +12,6 @@ #include #include #include -#include #include #include "../beforecheaders.h" @@ -133,6 +132,19 @@ int StartSceneEvent_hooked(IClientEntity* _this, int sceneInfo, int choreoScene, float last_bucket = 0; +static CatCommand test_chat_print("debug_print_chat", "machine broke", [](const CCommand& args) { + CHudBaseChat* chat = (CHudBaseChat*)g_CHUD->FindElement("CHudChat"); + if (chat) { + std::unique_ptr str(strfmt("\x07%06X[CAT]\x01 %s", 0x4D7942, args.ArgS())); + chat->Printf(str.get()); + } else { + logging::Info("Chat is null!"); + } +}); + + +static CatVar tauntslide_tf2(CV_SWITCH, "tauntslide_tf2", "0", "Tauntslide", "Allows free movement while taunting with movable taunts\nOnly works in tf2\nWIP"); + void CreateMove() { static bool flswitch = false; static IClientEntity *localplayer, *weapon, *last_weapon = nullptr; @@ -143,6 +155,41 @@ void CreateMove() { static bool changed = false; static ConVar *pNoPush = g_ICvar->FindVar("tf_avoidteammates_pushaway"); + //Tauntslide needs improvement for movement but it mostly works + IF_GAME (IsTF2()) { + //Only work if the catvar enables it + if (tauntslide_tf2) { + //Check to prevent crashing + if (CE_GOOD(LOCAL_E)) { + //If the local player is taunting + if (HasCondition(LOCAL_E)) { + float forward = 0; + float side = 0; + + //get directions + if (g_pUserCmd->buttons & IN_FORWARD) forward += 450; + if (g_pUserCmd->buttons & IN_BACK) forward -= 450; + if (g_pUserCmd->buttons & IN_MOVELEFT) side -= 450; + if (g_pUserCmd->buttons & IN_MOVERIGHT) side += 450; + + //Push them to userCmd + g_pUserCmd->forwardmove = forward; + g_pUserCmd->sidemove = side; + + //Grab Camera angle + static QAngle cameraAngle; + g_IEngine->GetViewAngles(cameraAngle); + + //Set userAngle = camera angles + g_pUserCmd->viewangles.y = cameraAngle[1]; + g_pLocalPlayer->v_OrigViewangles.y = cameraAngle[1]; + + //Use silent since we dont want to prevent the player from looking around + g_pLocalPlayer->bUseSilentAngles = true; + } + } + } + } if (no_taunt_ticks && CE_GOOD(LOCAL_E)) { RemoveCondition(LOCAL_E); @@ -187,7 +234,7 @@ void CreateMove() { static IClientEntity* last_checked_weapon = nullptr; IF_GAME (IsTF2()) { - if (crit_hack_next && CE_GOOD(LOCAL_W) && WeaponCanCrit() && RandomCrits()) { + if (crit_hack_next && CE_GOOD(LOCAL_E) && CE_GOOD(LOCAL_W) && WeaponCanCrit() && RandomCrits()) { PROF_SECTION(CM_misc_crit_hack_prediction); weapon = RAW_ENT(LOCAL_W); // IsBaseCombatWeapon @@ -204,10 +251,6 @@ void CreateMove() { } }*/ if (g_pUserCmd->command_number && (last_checked_weapon != weapon || last_checked_command_number < g_pUserCmd->command_number)) { - if (!g_PredictionRandomSeed) { - uintptr_t sig = gSignatures.GetClientSignature("89 1C 24 D9 5D D4 FF 90 3C 01 00 00 89 C7 8B 06 89 34 24 C1 E7 08 FF 90 3C 01 00 00 09 C7 33 3D ? ? ? ? 39 BB 34 0B 00 00 74 0E 89 BB 34 0B 00 00 89 3C 24 E8 ? ? ? ? C7 44 24 04 0F 27 00 00"); - g_PredictionRandomSeed = *reinterpret_cast(sig + (uintptr_t)32); - } tries = 0; cmdn = g_pUserCmd->command_number; chc = false; @@ -276,10 +319,29 @@ void CreateMove() { if (flswitch && !g_pUserCmd->impulse) g_pUserCmd->impulse = 100; flswitch = !flswitch; } + + static float afkTimeIdle = 0; + // Check if user settings allow anti-afk if (anti_afk) { - g_pUserCmd->sidemove = RandFloatRange(-450.0, 450.0); - g_pUserCmd->forwardmove = RandFloatRange(-450.0, 450.0); - g_pUserCmd->buttons = rand(); + + // If the timer exceeds 1 minute, jump and reset the timer + if (g_GlobalVars->curtime - 60 > afkTimeIdle) { + + // Send random commands + g_pUserCmd->sidemove = RandFloatRange(-450.0, 450.0); + g_pUserCmd->forwardmove = RandFloatRange(-450.0, 450.0); + g_pUserCmd->buttons = rand(); + + // After 1 second we reset the idletime + if (g_GlobalVars->curtime - 61 > afkTimeIdle) { + logging::Info("Finish anti-idle"); + afkTimeIdle = g_GlobalVars->curtime; + } + } else { + // If the player uses a button, reset the timer + if (g_pUserCmd->buttons & IN_FORWARD || g_pUserCmd->buttons & IN_BACK || g_pUserCmd->buttons & IN_MOVELEFT || g_pUserCmd->buttons & IN_MOVERIGHT || g_pUserCmd->buttons & IN_JUMP || !LOCAL_E->m_bAlivePlayer) + afkTimeIdle = g_GlobalVars->curtime; + } } IF_GAME (IsTF2()) { @@ -287,7 +349,9 @@ void CreateMove() { } } -void Draw() { +#ifndef TEXTMODE + +void DrawText() { if (crit_info && CE_GOOD(LOCAL_W)) { if (CritKeyDown() || experimental_crit_hack.KeyDown()) { AddCenterString("FORCED CRITS!", colors::red); @@ -316,6 +380,15 @@ void Draw() { AddSideString(format("Taunt Concept: ", CE_INT(LOCAL_E, netvar.m_iTauntConcept))); AddSideString(format("Taunt Index: ", CE_INT(LOCAL_E, netvar.m_iTauntIndex))); AddSideString(format("Sequence: ", CE_INT(LOCAL_E, netvar.m_nSequence))); + AddSideString(format("Velocity: ", LOCAL_E->m_vecVelocity.x, ' ', LOCAL_E->m_vecVelocity.y, ' ', LOCAL_E->m_vecVelocity.z)); + AddSideString(format("Velocity3: ", LOCAL_E->m_vecVelocity.Length())); + AddSideString(format("Velocity2: ", LOCAL_E->m_vecVelocity.Length2D())); + AddSideString("NetVar Velocity"); + Vector vel = CE_VECTOR(LOCAL_E, netvar.vVelocity); + AddSideString(format("Velocity: ", vel.x, ' ', vel.y, ' ', vel.z)); + AddSideString(format("Velocity3: ", vel.Length())); + AddSideString(format("Velocity2: ", vel.Length2D())); + AddSideString(format("flSimTime: ", LOCAL_E->var(netvar.m_flSimulationTime))); if (g_pUserCmd) AddSideString(format("command_number: ", last_cmd_number)); /*AddSideString(colors::white, "Weapon: %s [%i]", RAW_ENT(g_pLocalPlayer->weapon())->GetClientClass()->GetName(), g_pLocalPlayer->weapon()->m_iClassID); //AddSideString(colors::white, "flNextPrimaryAttack: %f", CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flNextPrimaryAttack)); @@ -362,7 +435,11 @@ void Draw() { } } +#endif + void Schema_Reload() { + logging::Info("Custom schema loading is not supported right now."); + /* static uintptr_t InitSchema_s = gSignatures.GetClientSignature("55 89 E5 57 56 53 83 EC 4C 0F B6 7D 14 C7 04 ? ? ? ? 01 8B 5D 18 8B 75 0C 89 5C 24 04 E8 ? ? ? ? 89 F8 C7 45 C8 00 00 00 00 8D 7D C8 84 C0 8B 45 10 C7 45 CC"); typedef void(*InitSchema_t)(void*, void*, CUtlBuffer& buffer, bool byte, unsigned version); static InitSchema_t InitSchema = (InitSchema_t)InitSchema_s; @@ -371,7 +448,7 @@ void Schema_Reload() { static GetItemSchema_t GetItemSchema = (GetItemSchema_t)GetItemSchema_s;//(*(uintptr_t*)GetItemSchema_s + GetItemSchema_s + 4); logging::Info("0x%08x 0x%08x", InitSchema, GetItemSchema); - void* itemschema = (GetItemSchema() + 4); + void* itemschema = (void*)((unsigned)GetItemSchema() + 4); void* data; passwd* pwd = getpwuid(getuid()); char* user = pwd->pw_name; @@ -388,6 +465,7 @@ void Schema_Reload() { CUtlBuffer buf(&buffer, 4 * 1000 * 1000, 9); logging::Info("0x%08x 0x%08x", InitSchema, GetItemSchema); InitSchema(0, itemschema, buf, false, 0xDEADCA7); + */ } CatVar debug_info(CV_SWITCH, "debug_info", "0", "Debug info", "Shows some debug info in-game"); @@ -418,27 +496,6 @@ CatCommand name("name_set", "Immediate name change", [](const CCommand& args) { ch->SendNetMsg(setname, false); } }); -CatCommand save_settings("save", "Save settings (optional filename)", [](const CCommand& args) { - std::string filename("lastcfg"); - if (args.ArgC() > 1) { - filename = std::string(args.Arg(1)); - } - std::string path = format(g_pszTFPath, "cfg/cat_", filename, ".cfg"); - logging::Info("Saving settings to %s", path.c_str()); - std::ofstream file(path, std::ios::out); - if (file.bad()) { - logging::Info("Couldn't open the file!"); - return; - } - for (auto i : g_ConVars) { - if (i) { - if (strcmp(i->GetString(), i->GetDefault())) { - file << i->GetName() << " \"" << i->GetString() << "\"\n"; - } - } - } - file.close(); -}); CatCommand say_lines("say_lines", "Say with newlines (\\n)", [](const CCommand& args) { std::string message(args.ArgS()); ReplaceString(message, "\\n", "\n"); diff --git a/src/hacks/Misc.h b/src/hacks/Misc.h index cd605314..276e8b0f 100644 --- a/src/hacks/Misc.h +++ b/src/hacks/Misc.h @@ -8,16 +8,14 @@ #ifndef HACKS_MISC_H_ #define HACKS_MISC_H_ -#include "IHack.h" - -class ConVar; -class CatCommand; -class IClientEntity; +#include "../common.h" namespace hacks { namespace shared { namespace misc { void CreateMove(); -void Draw(); +#ifndef TEXTMODE +void DrawText(); +#endif extern IClientEntity* found_crit_weapon; extern int found_crit_number; diff --git a/src/hacks/Noisemaker.cpp b/src/hacks/Noisemaker.cpp index d61d6af4..974ac477 100644 --- a/src/hacks/Noisemaker.cpp +++ b/src/hacks/Noisemaker.cpp @@ -13,7 +13,7 @@ namespace hacks { namespace tf2 { namespace noisemaker { -extern CatVar enabled(CV_SWITCH, "noisemaker", "0", "Noisemaker spam", "Spams noisemakers Infinitly\nWorks with limited use noisemakers"); +CatVar enabled(CV_SWITCH, "noisemaker", "0", "Noisemaker spam", "Spams noisemakers Infinitly\nWorks with limited use noisemakers"); void CreateMove() { if (enabled) { diff --git a/src/hacks/Noisemaker.h b/src/hacks/Noisemaker.h index 056a9907..666ca1a3 100644 --- a/src/hacks/Noisemaker.h +++ b/src/hacks/Noisemaker.h @@ -8,7 +8,7 @@ #ifndef HACKS_NOISEMAKER_H_ #define HACKS_NOISEMAKER_H_ -#include "IHack.h" +#include "../common.h" namespace hacks { namespace tf2 { namespace noisemaker { diff --git a/src/hacks/Radar.cpp b/src/hacks/Radar.cpp index 95cb15bd..98e0f6e8 100644 --- a/src/hacks/Radar.cpp +++ b/src/hacks/Radar.cpp @@ -10,32 +10,9 @@ namespace hacks { namespace tf { namespace radar { -Texture textures[2][9] = { - { - Texture(&_binary_scout_start, 128, 128), - Texture(&_binary_sniper_start, 128, 128), - Texture(&_binary_soldier_start, 128, 128), - Texture(&_binary_demoman_start, 128, 128), - Texture(&_binary_medic_start, 128, 128), - Texture(&_binary_heavy_start, 128, 128), - Texture(&_binary_pyro_start, 128, 128), - Texture(&_binary_spy_start, 128, 128), - Texture(&_binary_engineer_start, 128, 128) - }, - { - Texture(&_binary_scout_blue_start, 128, 128), - Texture(&_binary_sniper_blue_start, 128, 128), - Texture(&_binary_soldier_blue_start, 128, 128), - Texture(&_binary_demoman_blue_start, 128, 128), - Texture(&_binary_medic_blue_start, 128, 128), - Texture(&_binary_heavy_blue_start, 128, 128), - Texture(&_binary_pyro_blue_start, 128, 128), - Texture(&_binary_spy_blue_start, 128, 128), - Texture(&_binary_engineer_blue_start, 128, 128) - } -}; - -Texture buildings[1] = { Texture(&_binary_dispenser_start, 128, 128) }; +std::unique_ptr tx_classes[3][9]; +std::unique_ptr tx_teams[2]; +std::unique_ptr tx_items[2]; CatVar size(CV_INT, "radar_size", "300", "Radar size", "Defines radar size in pixels"); CatVar zoom(CV_FLOAT, "radar_zoom", "20", "Radar zoom", "Defines radar zoom (1px = Xhu)"); @@ -45,13 +22,22 @@ CatVar icon_size(CV_INT, "radar_icon_size", "20", "Icon size", "Defines radar ic CatVar radar_enabled(CV_SWITCH, "radar", "0", "Enable", "Enable Radar"); CatVar radar_x(CV_INT, "radar_x", "100", "Radar X", "Defines radar position (X)"); CatVar radar_y(CV_INT, "radar_y", "100", "Radar Y", "Defines radar position (Y)"); +CatVar use_icons(CV_SWITCH, "radar_icons", "1", "Use Icons", "Radar will use class icons instead of class portraits"); +CatVar show_teammates(CV_SWITCH, "radar_teammates", "1", "Show Teammates"); +CatVar show_healthpacks(CV_SWITCH, "radar_healthpacks", "1", "Show Healthpacks"); +CatVar show_ammopacks(CV_SWITCH, "radar_ammopacks", "1", "Show Ammopacks"); void Init() { - for (int i = 0; i < 2; i++) { + for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { - textures[i][j].Load(); + tx_classes[i][j].reset(new textures::AtlasTexture(64 * j, textures::atlas_height - 64 * (i + 1), 64, 64)); } } + tx_teams[0].reset(new textures::AtlasTexture(11 * 64, textures::atlas_height - 128, 64, 64)); + tx_teams[1].reset(new textures::AtlasTexture(11 * 64, textures::atlas_height - 64, 64, 64)); + + tx_items[0].reset(new textures::AtlasTexture(10 * 64, textures::atlas_height - 64, 64, 64)); + tx_items[1].reset(new textures::AtlasTexture(10 * 64, textures::atlas_height - 128, 64, 64)); } std::pair WorldToRadar(int x, int y) { @@ -85,8 +71,9 @@ std::pair WorldToRadar(int x, int y) { } void DrawEntity(int x, int y, CachedEntity* ent) { - static int idx, clr; - static float healthp; + int idx; + rgba_t clr; + float healthp; if (CE_GOOD(ent)) { if (ent->m_Type == ENTITY_PLAYER) { @@ -97,14 +84,21 @@ void DrawEntity(int x, int y, CachedEntity* ent) { if (idx < 0 || idx > 1) return; if (clazz <= 0 || clazz > 9) return; const auto& wtr = WorldToRadar(ent->m_vecOrigin.x, ent->m_vecOrigin.y); - textures[idx][clazz - 1].Draw(x + wtr.first, y + wtr.second, (int)icon_size, (int)icon_size); - draw::OutlineRect(x + wtr.first, y + wtr.second, (int)icon_size, (int)icon_size, idx ? colors::blu_v : colors::red_v); + + if (use_icons) { + tx_teams[idx].get()->Draw(x + wtr.first, y + wtr.second, (int)icon_size, (int)icon_size); + tx_classes[2][clazz - 1].get()->Draw(x + wtr.first, y + wtr.second, (int)icon_size, (int)icon_size); + } else { + tx_classes[idx][clazz - 1].get()->Draw(x + wtr.first, y + wtr.second, (int)icon_size, (int)icon_size); + drawgl::Rect(x + wtr.first, y + wtr.second, (int)icon_size, (int)icon_size, idx ? colors::blu_v : colors::red_v); + } + if (ent->m_iMaxHealth && healthbar) { healthp = (float)ent->m_iHealth / (float)ent->m_iMaxHealth; clr = colors::Health(ent->m_iHealth, ent->m_iMaxHealth); if (healthp > 1.0f) healthp = 1.0f; - draw::OutlineRect(x + wtr.first, y + wtr.second + (int)icon_size, (int)icon_size, 4, colors::black); - draw::DrawRect(x + wtr.first + 1, y + wtr.second + (int)icon_size + 1, ((float)icon_size - 2.0f) * healthp, 2, clr); + drawgl::Rect(x + wtr.first, y + wtr.second + (int)icon_size, (int)icon_size, 4, colors::black); + drawgl::FilledRect(x + wtr.first + 1, y + wtr.second + (int)icon_size + 1, ((float)icon_size - 2.0f) * healthp, 2, clr); } } else if (ent->m_Type == ENTITY_BUILDING) { /*if (ent->m_iClassID == CL_CLASS(CObjectDispenser)) { @@ -122,35 +116,55 @@ void DrawEntity(int x, int y, CachedEntity* ent) { draw::DrawRect(x + wtr.first + 1, y + wtr.second + (int)icon_size + 1, ((float)icon_size - 2.0f) * healthp, 2, clr); } }*/ + } else if (ent->m_Type == ENTITY_GENERIC) { + if (show_healthpacks && (ent->m_ItemType == ITEM_HEALTH_LARGE || ent->m_ItemType == ITEM_HEALTH_MEDIUM || ent->m_ItemType == ITEM_HEALTH_SMALL)) { + const auto& wtr = WorldToRadar(ent->m_vecOrigin.x, ent->m_vecOrigin.y); + float sz = float(icon_size) * 0.15f * 0.5f; + float sz2 = float(icon_size) * 0.85; + tx_items[1].get()->Draw(x + wtr.first + sz, y + wtr.second + sz, sz2, sz2); + } else if (show_ammopacks && (ent->m_ItemType == ITEM_AMMO_LARGE || ent->m_ItemType == ITEM_AMMO_MEDIUM || ent->m_ItemType == ITEM_AMMO_SMALL)) { + const auto& wtr = WorldToRadar(ent->m_vecOrigin.x, ent->m_vecOrigin.y); + float sz = float(icon_size) * 0.15f * 0.5f; + float sz2 = float(icon_size) * 0.85; + tx_items[0].get()->Draw(x + wtr.first + sz, y + wtr.second + sz, sz2, sz2); + } } } } void Draw() { - static int x, y, outlineclr; - static std::vector enemies {}; - static CachedEntity *ent; + if (!g_IEngine->IsInGame()) return; + int x, y; + rgba_t outlineclr; + std::vector enemies {}; + CachedEntity *ent; if (!radar_enabled) return; x = (int)radar_x; y = (int)radar_y; - draw::DrawRect(x, y, (int)size, (int)size, colors::Transparent(colors::black, 0.4f)); - outlineclr = (hacks::shared::aimbot::state == hacks::shared::aimbot::EAimbotState::AIMING ? colors::pink : GUIColor()); - draw::OutlineRect(x, y, (int)size, (int)size, outlineclr); - draw::DrawLine(x + (int)size / 2, y, 0, (int)size, GUIColor()); - draw::DrawLine(x, y + (int)size / 2, (int)size, 0, GUIColor()); + int radar_size = size; + int half_size = radar_size / 2; + + outlineclr = (hacks::shared::aimbot::foundTarget ? colors::pink : GUIColor()); + + drawgl::FilledRect(x, y, radar_size, radar_size, colors::Transparent(colors::black, 0.4f)); + drawgl::Rect(x, y, radar_size, radar_size, outlineclr); + if (enemies_over_teammates) enemies.clear(); for (int i = 1; i < HIGHEST_ENTITY; i++) { ent = ENTITY(i); if (CE_BAD(ent)) continue; if (i == g_IEngine->GetLocalPlayer()) continue; - if (!enemies_over_teammates || ent->m_Type != ENTITY_PLAYER) DrawEntity(x, y, ent); + if (ent->m_Type == ENTITY_PLAYER) { + if (!ent->m_bEnemy && !show_teammates) continue; + } + if (!enemies_over_teammates || !show_teammates || ent->m_Type != ENTITY_PLAYER) DrawEntity(x, y, ent); else { if (ent->m_bEnemy) enemies.push_back(ent); else DrawEntity(x, y, ent); } } - if (enemies_over_teammates) { + if (enemies_over_teammates && show_teammates) { for (auto enemy : enemies) { DrawEntity(x, y, enemy); } @@ -158,8 +172,12 @@ void Draw() { if (CE_GOOD(LOCAL_E)) { DrawEntity(x, y, LOCAL_E); const auto& wtr = WorldToRadar(g_pLocalPlayer->v_Origin.x, g_pLocalPlayer->v_Origin.y); - draw::OutlineRect(x + wtr.first, y + wtr.second, (int)icon_size, (int)icon_size, GUIColor()); + if (!use_icons) + drawgl::Rect(x + wtr.first, y + wtr.second, int(icon_size), int(icon_size), GUIColor()); } + + drawgl::Line(x + half_size, y + half_size / 2, 0, half_size, colors::Transparent(GUIColor(), 0.4f)); + drawgl::Line(x + half_size / 2, y + half_size, half_size, 0, colors::Transparent(GUIColor(), 0.4f)); } }}} diff --git a/src/hacks/Radar.hpp b/src/hacks/Radar.hpp index d427390f..315da0de 100644 --- a/src/hacks/Radar.hpp +++ b/src/hacks/Radar.hpp @@ -8,34 +8,13 @@ #ifndef HACKS_RADAR_HPP_ #define HACKS_RADAR_HPP_ -#include "../resource.hpp" #include "../common.h" -extern unsigned char _binary_scout_start; -extern unsigned char _binary_scout_blue_start; -extern unsigned char _binary_soldier_start; -extern unsigned char _binary_soldier_blue_start; -extern unsigned char _binary_pyro_start; -extern unsigned char _binary_pyro_blue_start; -extern unsigned char _binary_demoman_start; -extern unsigned char _binary_demoman_blue_start; -extern unsigned char _binary_heavy_start; -extern unsigned char _binary_heavy_blue_start; -extern unsigned char _binary_engineer_start; -extern unsigned char _binary_engineer_blue_start; -extern unsigned char _binary_medic_start; -extern unsigned char _binary_medic_blue_start; -extern unsigned char _binary_sniper_start; -extern unsigned char _binary_sniper_blue_start; -extern unsigned char _binary_spy_start; -extern unsigned char _binary_spy_blue_start; - -extern unsigned char _binary_dispenser_start; - namespace hacks { namespace tf { namespace radar { -extern Texture textures[2][9]; -extern Texture buildings[1]; +extern std::unique_ptr tx_classes[3][9]; +extern std::unique_ptr tx_teams[2]; +extern std::unique_ptr tx_items[2]; extern CatVar size; extern CatVar zoom; diff --git a/src/hacks/SkinChanger.cpp b/src/hacks/SkinChanger.cpp index be86c1c4..af9b9a20 100644 --- a/src/hacks/SkinChanger.cpp +++ b/src/hacks/SkinChanger.cpp @@ -8,6 +8,9 @@ #include "SkinChanger.hpp" #include "../copypasted/CSignature.h" +#include +#include + namespace hacks { namespace tf2 { namespace skinchanger { // Because fuck you, that's why. @@ -182,9 +185,9 @@ void FrameStageNotify(int stage) { last_weapon_out = my_weapon_ptr; } -static CatVar show_debug_info(CV_SWITCH, "skinchanger_debug", "1", "Debug Skinchanger"); +static CatVar show_debug_info(CV_SWITCH, "skinchanger_debug", "0", "Debug Skinchanger"); -void PaintTraverse() { +void DrawText() { CAttributeList *list; if (!enabled) return; @@ -202,20 +205,13 @@ void PaintTraverse() { #define BINARY_FILE_READ(handle, data) handle.read(reinterpret_cast(&data), sizeof(data)) void Save(std::string filename) { - uid_t uid = geteuid(); - passwd* pw = getpwuid(uid); - if (!pw) { - logging::Info("Couldn't get username!"); - return; - } - std::string name(pw->pw_name); - DIR* cathook_directory = opendir(strfmt("/home/%s/.cathook", pw->pw_name)); + DIR* cathook_directory = opendir("cathook/skinchanger"); if (!cathook_directory) { - logging::Info(".cathook directory doesn't exist, creating one!"); - mkdir(strfmt("/home/%s/.cathook", pw->pw_name), S_IRWXU | S_IRWXG); + logging::Info("Skinchanger directory doesn't exist, creating one!"); + mkdir(strfmt("cathook/skinchanger"), S_IRWXU | S_IRWXG); } else closedir(cathook_directory); try { - std::ofstream file("/home/" + name + "/.cathook/" + filename, std::ios::out | std::ios::binary); + std::ofstream file("cathook/skinchanger/" + filename, std::ios::out | std::ios::binary); BINARY_FILE_WRITE(file, SERIALIZE_VERSION); size_t size = modifier_map.size(); BINARY_FILE_WRITE(file, size); @@ -239,20 +235,13 @@ void Save(std::string filename) { } void Load(std::string filename, bool merge) { - uid_t uid = geteuid(); - passwd* pw = getpwuid(uid); - if (!pw) { - logging::Info("Couldn't get username!"); - return; - } - std::string name(pw->pw_name); - DIR* cathook_directory = opendir(strfmt("/home/%s/.cathook", pw->pw_name)); + DIR* cathook_directory = opendir("cathook/skinchanger"); if (!cathook_directory) { - logging::Info(".cathook directory doesn't exist, creating one!"); - mkdir(strfmt("/home/%s/.cathook", pw->pw_name), S_IRWXU | S_IRWXG); + logging::Info("Skinchanger directory doesn't exist, creating one!"); + mkdir(strfmt("cathook/skinchanger"), S_IRWXU | S_IRWXG); } else closedir(cathook_directory); try { - std::ifstream file("/home/" + name + "/.cathook/" + filename, std::ios::in | std::ios::binary); + std::ifstream file("cathook/skinchanger/" + filename, std::ios::in | std::ios::binary); unsigned file_serialize = 0; BINARY_FILE_READ(file, file_serialize); if (file_serialize != SERIALIZE_VERSION) { diff --git a/src/hacks/SkinChanger.hpp b/src/hacks/SkinChanger.hpp index f266ce8f..8e305ea0 100644 --- a/src/hacks/SkinChanger.hpp +++ b/src/hacks/SkinChanger.hpp @@ -123,7 +123,7 @@ void Load(std::string filename, bool merge = false); void InvalidateCookie(); void FrameStageNotify(int stage); -void PaintTraverse(); +void DrawText(); }}} diff --git a/src/hacks/Spam.cpp b/src/hacks/Spam.cpp index 5e3a8f9b..d059047a 100644 --- a/src/hacks/Spam.cpp +++ b/src/hacks/Spam.cpp @@ -8,24 +8,30 @@ #include "Spam.h" #include "../common.h" #include "../sdk.h" -#include namespace hacks { namespace shared { namespace spam { static CatEnum spam_enum({"DISABLED", "CUSTOM", "DEFAULT", "LENNYFACES", "BLANKS", "NULLCORE", "LMAOBOX", "LITHIUM"}); CatVar spam_source(spam_enum, "spam", "0", "Chat Spam", "Defines source of spam lines. CUSTOM spam file must be set in cat_spam_file and loaded with cat_spam_reload (Use console!)"); CatVar random_order(CV_SWITCH, "spam_random", "0", "Random Order"); -CatVar filename(CV_STRING, "spam_file", "spam.txt", "Spam file (~/.cathook/...)", "Spam file name. Each line should be no longer than 100 characters, file must be located in ~/.cathook folder"); -CatVar teamname_spam(CV_SWITCH, "spam_teamname", "0", "Teamname Spam", "Spam changes the tournament name"); +CatVar filename(CV_STRING, "spam_file", "spam.txt", "Spam file", "Spam file name. Each line should be no longer than 100 characters, file must be located in cathook data folder"); CatCommand reload("spam_reload", "Reload spam file", Reload); +CatVar spam_delay(CV_INT, "spam_delay", "800", "Spam delay", "Delay between spam messages (in ms)", 0.0f, 8000.0f); + +static CatEnum voicecommand_enum({"DISABLED", "RANDOM", "MEDIC", "THANKS", "NICE SHOT", "CHEERS", "JEERS"}); +CatVar voicecommand_spam(voicecommand_enum, "spam_voicecommand", "0", "Voice Command Spam", "Spams tf voice commands"); + +CatVar teamname_spam(CV_SWITCH, "spam_teamname", "0", "Teamname Spam", "Spam changes the tournament name"); + + +std::chrono::time_point last_spam_point {}; -bool teamname_swap = false; int current_index { 0 }; -float last_spam { 0.0f }; - TextFile file {}; const std::string teams[] = { "RED", "BLU" }; + + // FUCK enum class. // It doesn't have bitwise operators by default!! WTF!! static_cast(REEE)! @@ -139,6 +145,12 @@ int QueryPlayer(Query query) { return index_result; } +void Init() { + filename.InstallChangeCallback([](IConVar* var, const char* pszOV, float flOV) { + file.TryLoad(std::string(filename.GetString())); + }); +} + bool SubstituteQueries(std::string& input) { size_t index = input.find("%query:"); while (index != std::string::npos) { @@ -168,21 +180,54 @@ bool FormatSpamMessage(std::string& message) { } void CreateMove() { - if (teamname_spam) { - if (teamname_swap) { - teamname_swap = false; - g_IEngine->ServerCmd("tournament_teamname Cat"); - } else { - teamname_swap = true; - g_IEngine->ServerCmd("tournament_teamname Hook"); - } + + IF_GAME (IsTF2()) { + // Spam changes the tournament name in casual and compeditive gamemodes + if (teamname_spam) { + static bool teamname_swap = false; + if (teamname_swap) { + teamname_swap = false; + g_IEngine->ServerCmd("tournament_teamname Cat"); + } else { + teamname_swap = true; + g_IEngine->ServerCmd("tournament_teamname Hook"); + } + } + + if (voicecommand_spam) { + static float last_voice_spam = 0.0f; + if (g_GlobalVars->curtime - 4.0F > last_voice_spam) { + switch ((int)voicecommand_spam) { + case 1: // RANDOM + g_IEngine->ServerCmd(format("voicemenu ", floor(RandFloatRange(0, 2.9)), " ", floor(RandFloatRange(0, 8.9))).c_str()); + break; + case 2: // MEDIC + g_IEngine->ServerCmd("voicemenu 0 0"); + break; + case 3: // THANKS + g_IEngine->ServerCmd("voicemenu 0 1"); + break; + case 4: // NICE SHOT + g_IEngine->ServerCmd("voicemenu 2 6"); + break; + case 5: // CHEERS + g_IEngine->ServerCmd("voicemenu 2 2"); + break; + case 6: // JEERS + g_IEngine->ServerCmd("voicemenu 2 3"); + } + last_voice_spam = g_GlobalVars->curtime; + } + } } + if (!spam_source) return; static int safety_ticks = 0; - static int last_spam = 0; - if ((int)spam_source != last_spam) { + static int last_source = 0; + static float last_message = 0; + if ((int)spam_source != last_source) { safety_ticks = 300; - last_spam = (int)spam_source; + last_source = (int)spam_source; } if (safety_ticks > 0) { safety_ticks--; @@ -190,7 +235,7 @@ void CreateMove() { } else { safety_ticks = 0; } - if (last_spam > g_GlobalVars->curtime) last_spam = 0.0f; + const std::vector* source = nullptr; switch ((int)spam_source) { case 1: @@ -211,7 +256,7 @@ void CreateMove() { return; } if (!source || !source->size()) return; - if (g_GlobalVars->curtime - last_spam > 0.8f) { + if (std::chrono::duration_cast(std::chrono::system_clock::now() - last_spam_point).count() > int(spam_delay)) { if (chat_stack::stack.empty()) { if (current_index >= source->size()) current_index = 0; if (random_order) current_index = rand() % source->size(); @@ -220,12 +265,8 @@ void CreateMove() { chat_stack::Say(spamString); current_index++; } + last_spam_point = std::chrono::system_clock::now(); } - -} - -void Reset() { - last_spam = 0.0f; } void Reload() { diff --git a/src/hacks/Spam.h b/src/hacks/Spam.h index 9c9a4ed0..8b94c7a4 100644 --- a/src/hacks/Spam.h +++ b/src/hacks/Spam.h @@ -8,9 +8,7 @@ #ifndef HACKS_SPAM_H_ #define HACKS_SPAM_H_ -#include "IHack.h" - -#include "../textfile.h" +#include "../common.h" class CatCommand; @@ -23,12 +21,12 @@ extern const std::vector builtin_nonecore; extern const std::vector builtin_lmaobox; extern const std::vector builtin_lithium; -extern CatVar enabled; +extern CatVar spam_source; extern CatVar filename; extern CatCommand reload; +void Init(); void CreateMove(); -void Reset(); void Reload(); }}} diff --git a/src/hacks/SpyAlert.cpp b/src/hacks/SpyAlert.cpp index 79eb6d63..86b1a7c1 100644 --- a/src/hacks/SpyAlert.cpp +++ b/src/hacks/SpyAlert.cpp @@ -35,7 +35,7 @@ void Draw() { closest_spy_distance = 0.0f; spy_count = 0; if (last_say > g_GlobalVars->curtime) last_say = 0; - for (int i = 0; i < HIGHEST_ENTITY && i < 64; i++) { + for (int i = 0; i < HIGHEST_ENTITY && i < 32; i++) { ent = ENTITY(i); if (CE_BAD(ent)) continue; if (CE_BYTE(ent, netvar.iLifeState)) continue; diff --git a/src/hacks/SpyAlert.h b/src/hacks/SpyAlert.h index 26c12421..4970c5d2 100644 --- a/src/hacks/SpyAlert.h +++ b/src/hacks/SpyAlert.h @@ -8,7 +8,7 @@ #ifndef HACKS_SPYALERT_H_ #define HACKS_SPYALERT_H_ -#include "IHack.h" +#include "../common.h" namespace hacks { namespace tf { namespace spyalert { diff --git a/src/hacks/Trigger.cpp b/src/hacks/Trigger.cpp index c25d5e32..18b5795a 100644 --- a/src/hacks/Trigger.cpp +++ b/src/hacks/Trigger.cpp @@ -1,3 +1,4 @@ + /* * HTrigger.cpp * @@ -16,28 +17,438 @@ namespace hacks { namespace shared { namespace triggerbot { -CatVar enabled(CV_SWITCH, "trigger_enabled", "0", "Enable", "Master Triggerbot switch"); -CatVar respect_cloak(CV_SWITCH, "trigger_respect_cloak", "1", "Respect cloak", "Don't shoot at cloaked spies"); -CatVar zoomed_only(CV_SWITCH, "trigger_zoomed", "1", "Zoomed only", "Don't shoot if you aren't zoomed in"); -CatEnum hitbox_enum({ - "ANY", "HEAD", "PELVIS", "SPINE 0", "SPINE 1", "SPINE 2", "SPINE 3", "UPPER ARM L", "LOWER ARM L", - "HAND L", "UPPER ARM R", "LOWER ARM R", "HAND R", "HIP L", "KNEE L", "FOOT L", "HIP R", - "KNEE R", "FOOT R" -}, -1); -CatVar hitbox(hitbox_enum, "trigger_hitbox", "-1", "Hitbox", "Triggerbot hitbox. Only useful settings are ANY and HEAD. Use ANY for scatter or any other shotgun-based weapon, HEAD for ambassador/sniper rifle"); -CatVar allow_bodyshot(CV_SWITCH, "trigger_bodyshot", "1", "Bodyshot", "Triggerbot will bodyshot enemies if you have enough charge to 1tap them"); -CatVar finishing_hit(CV_SWITCH, "trigger_finish", "1", "Noscope weak enemies", "If enemy has <50 HP, noscope them"); -CatVar max_range(CV_INT, "trigger_range", "0", "Max range", "Triggerbot won't shoot if enemy is too far away", true, 4096.0f); -CatVar buildings(CV_SWITCH, "trigger_buildings", "1", "Trigger at buildings", "Shoot buildings"); -CatVar ignore_vaccinator(CV_SWITCH, "trigger_respect_vaccinator", "1", "Respect vaccinator", "Don't shoot at bullet-vaccinated enemies"); -CatVar ambassador(CV_SWITCH, "trigger_ambassador", "1", "Smart Ambassador", "Don't shoot if your ambassador can't headshot yet (Keep that enabled!)"); -CatVar accuracy(CV_INT, "trigger_accuracy", "0", "Improve accuracy", "Improves triggerbot accuracy when aiming for specific hitbox"); +// Vars for usersettings +static CatVar enabled(CV_SWITCH, "trigger_enabled", "0", "Enable", "Master Triggerbot switch"); + +static CatVar trigger_key(CV_KEY, "trigger_key", "0", "Triggerbot key", "Triggerbot key. Look at Triggerbot key Mode too!"); +static CatEnum trigger_key_modes_enum({ "DISABLED", "TRIGGERKEY", "REVERSE", "TOGGLE" }); +static CatVar trigger_key_mode(trigger_key_modes_enum, "trigger_key_mode", "1", "Triggerbot key mode", "DISABLED: triggerbot is always active\nAIMKEY: triggerbot is active when key is down\nREVERSE: triggerbot is disabled when key is down\nTOGGLE: pressing key toggles triggerbot"); + +static CatEnum hitbox_mode_enum({ "AUTO-HEAD", "AUTO-CLOSEST", "Head only" }); +static CatVar hitbox_mode(hitbox_mode_enum, "trigger_hitboxmode", "0", "Hitbox Mode", "Defines hitbox selection mode"); + +static CatVar accuracy(CV_INT, "trigger_accuracy", "1", "Improve accuracy", "Improves triggerbot accuracy when aiming for specific hitbox. Recommended to use with sniper rifle/ambassador"); -trace_t trace_object; +static CatVar ignore_vaccinator(CV_SWITCH, "trigger_ignore_vaccinator", "1", "Ignore Vaccinator", "Hitscan weapons won't fire if enemy is vaccinated against bullets"); +static CatVar ignore_hoovy(CV_SWITCH, "trigger_ignore_hoovy", "1", "Ignore Hoovies", "Triggerbot won't attack hoovies"); +static CatVar ignore_cloak(CV_SWITCH, "trigger_ignore_cloak", "1", "Ignore cloaked", "Don't trigger at invisible enemies"); +static CatVar buildings_sentry(CV_SWITCH, "trigger_buildings_sentry", "1", "Trigger Sentry", "Should trigger at sentryguns?"); +static CatVar buildings_other(CV_SWITCH, "trigger_buildings_other", "1", "Trigger Other building", "Should trigger at other buildings"); +static CatVar stickybot(CV_SWITCH, "trigger_stickys", "0", "Trigger Sticky", "Should trigger at stickys"); +static CatVar teammates(CV_SWITCH, "trigger_teammates", "0", "Trigger teammates", "Trigger at your own team. Useful for HL2DM"); + +static CatVar wait_for_charge(CV_SWITCH, "trigger_charge", "0", "Wait for sniper rifle charge", "Triggerbot waits until it has enough charge to kill"); +static CatVar zoomed_only(CV_SWITCH, "trigger_zoomed", "1", "Zoomed only", "Don't trigger with unzoomed rifles"); +static CatVar max_range(CV_INT, "trigger_maxrange", "0", "Max distance", + "Max range for triggerbot\n" + "900-1100 range is efficient for scout/widowmaker engineer", 4096.0f); + +static CatVar delay(CV_FLOAT, "trigger_delay", "0", "Delay", "Triggerbot delay in seconds", 0.0f, 1.0f); + +float target_time = 0.0f; + +int last_hb_traced = 0; +Vector forward; + +// The main "loop" of the triggerbot +void CreateMove() { + + float backup_time = target_time; + target_time = 0; + + // Check if aimbot is enabled + if (!enabled) return; + + // Check if player can aim + if (!ShouldShoot()) return; + + // Reset our last hitbox traced + last_hb_traced = -1; + + // Get and ent in front of the player + CachedEntity* ent = FindEntInSight(EffectiveTargetingRange()); + + // Check if dormant or null to prevent crashes + if (CE_BAD(ent)) return; + + // Determine whether the triggerbot should shoot, then act accordingly + if (IsTargetStateGood(ent)) { + target_time = backup_time; + if (delay) { + if (target_time > g_GlobalVars->curtime) { + target_time = 0.0f; + } + if (!target_time) { + target_time = g_GlobalVars->curtime; + } else { + if (g_GlobalVars->curtime - float(delay) >= target_time) { + g_pUserCmd->buttons |= IN_ATTACK; + } + } + } else { + g_pUserCmd->buttons |= IN_ATTACK; + } + } + + return; +} + +// The first check to see if the player should shoot in the first place +bool ShouldShoot() { + + // Check for +use + if (g_pUserCmd->buttons & IN_USE) return false; + + // Check if using action slot item + if (g_pLocalPlayer->using_action_slot_item) return false; + + // Check the aimkey to determine if it should shoot + if (!UpdateAimkey()) return false; + + IF_GAME (IsTF2()) { + // Check if Carrying A building + if (CE_BYTE(g_pLocalPlayer->entity, netvar.m_bCarryingObject)) return false; + // Check if deadringer out + if (CE_BYTE(g_pLocalPlayer->entity, netvar.m_bFeignDeathReady)) return false; + // If zoomed only is on, check if zoomed + if (zoomed_only && g_pLocalPlayer->holding_sniper_rifle) { + if (!g_pLocalPlayer->bZoomed && !(g_pUserCmd->buttons & IN_ATTACK)) return false; + } + // Check if player is taunting + if (HasCondition(g_pLocalPlayer->entity)) return false; + // Check if player is cloaked + if (IsPlayerInvisible(g_pLocalPlayer->entity)) return false; + + if (IsAmbassador(g_pLocalPlayer->weapon())) { + // Check if ambasador can headshot + if (!AmbassadorCanHeadshot()) return false; + } + } + + IF_GAME (IsTF2()) { + switch (GetWeaponMode()) { + case weapon_hitscan: + break; + case weapon_melee: + break; + // Check if player is using a projectile based weapon + case weapon_projectile: + return false; + break; + // Check if player doesnt have a weapon usable by aimbot + default: + return false; + }; + } + IF_GAME (IsTF()) { + // Check if player is zooming + if (g_pLocalPlayer->bZoomed) { + if (!(g_pUserCmd->buttons & (IN_ATTACK | IN_ATTACK2))) { + if (!CanHeadshot()) return false; + } + } + } + IF_GAME (IsTF()) { + // Check if crithack allows attacking + if (!AllowAttacking()) + return false; + } + return true; +} + +// A second check to determine whether a target is good enough to be aimed at +bool IsTargetStateGood(CachedEntity* entity) { + + // Check for Players + if (entity->m_Type == ENTITY_PLAYER) { + // Check if target is The local player + if (entity == LOCAL_E) return false; + // Dont aim at dead player + if (!entity->m_bAlivePlayer) return false; + // Dont aim at teammates + if (!entity->m_bEnemy && !teammates) return false; + + IF_GAME (IsTF()) { + // If settings allow waiting for charge, and current charge cant kill target, dont aim + if (wait_for_charge && g_pLocalPlayer->holding_sniper_rifle) { + float bdmg = CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flChargedDamage); + if (g_GlobalVars->curtime - g_pLocalPlayer->flZoomBegin <= 1.0f) bdmg = 50.0f; + if ((bdmg * 3) < (HasDarwins(entity) ? (entity->m_iHealth * 1.15) : entity->m_iHealth)) { + return false; + } + } + // If settings allow, ignore taunting players + if (ignore_taunting && HasCondition(entity)) return false; + // Dont target invulnerable players, ex: uber, bonk + if (IsPlayerInvulnerable(entity)) return false; + // If settings allow, dont target cloaked players + if (ignore_cloak && IsPlayerInvisible(entity)) return false; + // If settings allow, dont target vaccinated players + if (g_pLocalPlayer->weapon_mode == weaponmode::weapon_hitscan || LOCAL_W->m_iClassID == CL_CLASS(CTFCompoundBow)) + if (ignore_vaccinator && HasCondition(entity)) return false; + } + // Dont target players marked as friendly + if (playerlist::IsFriendly(playerlist::AccessData(entity).state)) return false; + IF_GAME (IsTF()) { + // If settings allow, ignore hoovys + if (ignore_hoovy && IsHoovy(entity)) { + return false; + } + } + + // Head hitbox detection + if (HeadPreferable(entity)) { + if (last_hb_traced != hitbox_t::head) return false; + } + + // If usersettings tell us to use accuracy improvements and the cached hitbox isnt null, then we check if it hits here + if (accuracy) { + + // Get a cached hitbox for the one traced + hitbox_cache::CachedHitbox* hb = entity->hitboxes.GetHitbox(last_hb_traced); + + // Check for null + if (hb) { + + // Get the min and max for the hitbox + Vector minz(min(hb->min.x, hb->max.x), min(hb->min.y, hb->max.y), min(hb->min.z, hb->max.z)); + Vector maxz(max(hb->min.x, hb->max.x), max(hb->min.y, hb->max.y), max(hb->min.z, hb->max.z)); + + // Shrink the hitbox here + Vector size = maxz - minz; + Vector smod = size * 0.05f * (int)accuracy; + + // Save the changes to the vectors + minz += smod; + maxz -= smod; + + // Trace and test if it hits the smaller hitbox, if it fails we return false + Vector hit; + if (!CheckLineBox(minz, maxz, g_pLocalPlayer->v_Eye, forward, hit)) { + return false; + } + } + } + + // Target passed the tests so return true + return true; + + // Check for buildings + } else if (entity->m_Type == ENTITY_BUILDING) { + // Check if building aimbot is enabled + if ( !(buildings_other || buildings_sentry) ) return false; + // Check if enemy building + if (!entity->m_bEnemy) return false; + + // If needed, Check if building type is allowed + if ( !(buildings_other && buildings_sentry) ) { + // Check if target is a sentrygun + if ( entity->m_iClassID == CL_CLASS(CObjectSentrygun) ) { + // If sentrys are not allowed, dont target + if (!buildings_sentry) return false; + } else { + // If target is not a sentry, check if other buildings are allowed + if (!buildings_other) return false; + } + } + + // Target passed the tests so return true + return true; + + // Check for stickybombs + } else if (entity->m_iClassID == CL_CLASS(CTFGrenadePipebombProjectile)) { + // Check if sticky aimbot is enabled + if (!stickybot) return false; + + // Check if thrower is a teammate + if (!entity->m_bEnemy) return false; + + // Check if target is a pipe bomb + if (CE_INT(entity, netvar.iPipeType) != 1) return false; + + // Target passed the tests so return true + return true; + + } else { + // If target is not player, building or sticky, return false + return false; + } + // An impossible error so just return false + return false; +} + +// A function to return a potential entity in front of the player +CachedEntity* FindEntInSight(float range) { + + // We dont want to hit ourself so we set an ignore + trace_t trace; + trace::filter_default.SetSelf(RAW_ENT(g_pLocalPlayer->entity)); + + // Use math to get a vector in front of the player + float sp, sy, cp, cy; + QAngle angle; + g_IEngine->GetViewAngles(angle); + sy = sinf(DEG2RAD(angle[1])); + cy = cosf(DEG2RAD(angle[1])); + sp = sinf(DEG2RAD(angle[0])); + cp = cosf(DEG2RAD(angle[0])); + forward.x = cp * cy; + forward.y = cp * sy; + forward.z = -sp; + forward = forward * range + g_pLocalPlayer->v_Eye; + + // Setup the trace starting with the origin of the local players eyes attemting to hit the end vector we determined + Ray_t ray; + ray.Init(g_pLocalPlayer->v_Eye, forward); + + // Ray trace + g_ITrace->TraceRay(ray, 0x4200400B, &trace::filter_default, &trace); + + // Return an ent if that is what we hit + if (trace.m_pEnt) { + + last_hb_traced = trace.hitbox; + return ENTITY(((IClientEntity*)trace.m_pEnt)->entindex()); + } + + // Since we didnt hit and entity, the vis check failed so return 0 + return 0; + +} + +// A function to find whether the head should be used for a target +bool HeadPreferable(CachedEntity* target) { + + // Switch based on the priority type we need + switch ((int)hitbox_mode) { + case 0: { // AUTO-HEAD priority + // Var to keep if we can bodyshot + bool headonly = false; + // Save the local players current weapon to a var + int ci = g_pLocalPlayer->weapon()->m_iClassID; + IF_GAME (IsTF()) { + // If user is using a sniper rifle, Set headonly to whether we can headshot or not, + if (g_pLocalPlayer->holding_sniper_rifle) { + headonly = CanHeadshot(); + // If player is using an ambassador, set headonly to true + } else if (IsAmbassador(g_pLocalPlayer->weapon())) { + headonly = true; + } + // Bodyshot handling + if (g_pLocalPlayer->holding_sniper_rifle) { + // Some keeper vars + float cdmg, bdmg; + // Grab netvar for current charge damage + cdmg = CE_FLOAT(LOCAL_W, netvar.flChargedDamage); + // Set our baseline bodyshot damage + bdmg = 50; + // Darwins damage correction + if (HasDarwins(target)) { + // Darwins protects against 15% of damage + bdmg = (bdmg * .85) - 1; + cdmg = (cdmg * .85) - 1; + } + // Vaccinator damage correction + if (HasCondition(target)) { + // Vac charge protects against 75% of damage + bdmg = (bdmg * .25) - 1; + cdmg = (cdmg * .25) - 1; + } else if (HasCondition(target)) { + // Passive bullet resist protects against 10% of damage + bdmg = (bdmg * .90) - 1; + cdmg = (cdmg * .90) - 1; + } + // Invis damage correction + if (IsPlayerInvisible(target)) { + // Invis spies get protection from 10% of damage + bdmg = (bdmg * .80) - 1; + cdmg = (cdmg * .80) - 1; + } + // If can headshot and if bodyshot kill from charge damage, or if crit boosted and they have 150 health, or if player isnt zoomed, or if the enemy has less than 40, due to darwins, and only if they have less than 150 health will it try to bodyshot + if (CanHeadshot() && (cdmg >= target->m_iHealth || IsPlayerCritBoosted(g_pLocalPlayer->entity) || !g_pLocalPlayer->bZoomed || target->m_iHealth <= bdmg) && target->m_iHealth <= 150) { + // We dont need to hit the head as a bodyshot will kill + headonly = false; + } + } + // In counter-strike source, headshots are what we want + } else IF_GAME (IsCSS()) { + headonly = true; + } + // Return our var of if we need to headshot + return headonly; + + } break; + case 1: { // AUTO-CLOSEST priority + // We dont need the head so just use anything + return false; + } break; + case 2: { // Head only + // User wants the head only + return true; + } break; + } + // We dont know what the user wants so just use anything + return false; +} + +// A function that determins whether aimkey allows aiming +bool UpdateAimkey() { + static bool trigger_key_flip = false; + static bool pressed_last_tick = false; + bool allow_trigger_key = true; + // Check if aimkey is used + if (trigger_key && trigger_key_mode) { + // Grab whether the aimkey is depressed + bool key_down = g_IInputSystem->IsButtonDown((ButtonCode_t)(int)trigger_key); + // Switch based on the user set aimkey mode + switch ((int)trigger_key_mode) { + // Only while key is depressed, enable + case 1: + if (!key_down) { + allow_trigger_key = false; + } + break; + // Only while key is not depressed, enable + case 2: + if (key_down) { + allow_trigger_key = false; + } + break; + // Aimkey acts like a toggle switch + case 3: + if (!pressed_last_tick && key_down) trigger_key_flip = !trigger_key_flip; + if (!trigger_key_flip) { + allow_trigger_key = false; + } + } + pressed_last_tick = key_down; + } + // Return whether the aimkey allows aiming + return allow_trigger_key; +} + +// Func to find value of how far to target ents +float EffectiveTargetingRange() { + // Melees use a close range, TODO add dynamic range for demoknight swords + if (GetWeaponMode() == weapon_melee) { + return 100.0f; + // Pyros only have so much untill their flames hit + } else if ( g_pLocalPlayer->weapon()->m_iClassID == CL_CLASS(CTFFlameThrower) ) { + return 185.0f; + } + // If user has set a max range, then use their setting, + if (max_range) { + return (float)max_range; + // else use a pre-set range + } else { + return 8012.0f; + } +} + +// Helper functions to trace for hitboxes // TEMPORARY CODE. // TODO - bool GetIntersection(float fDst1, float fDst2, Vector P1, Vector P2, Vector& Hit) { if ((fDst1 * fDst2) >= 0.0f) return false; if (fDst1 == fDst2) return false; @@ -77,108 +488,10 @@ bool CheckLineBox(Vector B1, Vector B2, Vector L1, Vector L2, Vector& Hit) { return false; } - -void CreateMove() { - if (!enabled) return; - if (GetWeaponMode() != weapon_hitscan) return; - if (ambassador) { - if (IsAmbassador(g_pLocalPlayer->weapon())) { - if ((g_GlobalVars->curtime - CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flLastFireTime)) <= 1.0) { - return; - } - } - } - Ray_t ray; - trace::filter_default.SetSelf(RAW_ENT(g_pLocalPlayer->entity)); - Vector forward; - float sp, sy, cp, cy; - sy = sinf(DEG2RAD(g_pUserCmd->viewangles[1])); // yaw - cy = cosf(DEG2RAD(g_pUserCmd->viewangles[1])); - - sp = sinf(DEG2RAD(g_pUserCmd->viewangles[0])); // pitch - cp = cosf(DEG2RAD(g_pUserCmd->viewangles[0])); - - forward.x = cp * cy; - forward.y = cp * sy; - forward.z = -sp; - forward = forward * 8192.0f + g_pLocalPlayer->v_Eye; - ray.Init(g_pLocalPlayer->v_Eye, forward); - g_ITrace->TraceRay(ray, 0x4200400B, &trace::filter_default, &trace_object); - - IClientEntity* raw_entity = (IClientEntity*)(trace_object.m_pEnt); - if (!raw_entity) return; - CachedEntity* entity = ENTITY(raw_entity->entindex()); - if (!entity->m_bEnemy) return; - - bool isPlayer = false; - switch (entity->m_Type) { - case EntityType::ENTITY_PLAYER: - isPlayer = true; break; - case EntityType::ENTITY_BUILDING: - if (!buildings) return; - break; - default: - return; - }; - - Vector enemy_pos = entity->m_vecOrigin; - Vector my_pos = g_pLocalPlayer->entity->m_vecOrigin; - if (max_range) { - if (entity->m_flDistance > (float)max_range) return; - } - if (!isPlayer) { - g_pUserCmd->buttons |= IN_ATTACK; - return; - } - if (HasCondition(entity) && ignore_vaccinator) return; - if (playerlist::IsFriendly(playerlist::AccessData(entity).state)) return; - if (IsPlayerInvulnerable(entity)) return; - if (respect_cloak && (IsPlayerInvisible(entity))) return; - int health = CE_INT(entity, netvar.iHealth); - bool do_bodyshot = false; - if (g_pLocalPlayer->clazz == tf_class::tf_sniper) { - // If sniper.. - if (health <= 50 && finishing_hit) { - do_bodyshot = true; - } - // If we need charge... - if (!allow_bodyshot) { - float bdmg = CE_FLOAT(g_pLocalPlayer->weapon(), netvar.flChargedDamage); - if (CanHeadshot() && (bdmg) >= health) { - do_bodyshot = true; - } - } - - } - if (!do_bodyshot && (g_pLocalPlayer->clazz == tf_class::tf_sniper) && zoomed_only && - !((g_pLocalPlayer->bZoomed) && CanHeadshot())) { - return; - } - - CachedHitbox* hb = entity->hitboxes.GetHitbox(trace_object.hitbox); - - if ((int)hitbox >= 0 && !do_bodyshot) { - if (trace_object.hitbox != (int)hitbox) return; - } - - if (accuracy && hb) { - Vector minz(min(hb->min.x, hb->max.x), min(hb->min.y, hb->max.y), min(hb->min.z, hb->max.z)); - Vector maxz(max(hb->min.x, hb->max.x), max(hb->min.y, hb->max.y), max(hb->min.z, hb->max.z)); - Vector size = maxz - minz; - Vector smod = size * 0.05f * (int)accuracy; - minz += smod; - maxz -= smod; - Vector hit; - if (CheckLineBox(minz, maxz, g_pLocalPlayer->v_Eye, forward, hit)) { - g_pUserCmd->buttons |= IN_ATTACK; - } - } else { - g_pUserCmd->buttons |= IN_ATTACK; - } -} - void Draw() { } }}} + + diff --git a/src/hacks/Trigger.h b/src/hacks/Trigger.h index 41a87785..317a6b8b 100644 --- a/src/hacks/Trigger.h +++ b/src/hacks/Trigger.h @@ -8,26 +8,21 @@ #ifndef HTRIGGER_H_ #define HTRIGGER_H_ -#include "IHack.h" +#include "../common.h" class CatVar; namespace hacks { namespace shared { namespace triggerbot { -extern CatVar enabled; -extern CatVar respect_cloak; // TODO move to Targeting -extern CatVar zoomed_only; -extern CatVar hitbox; -extern CatVar allow_bodyshot; -extern CatVar finishing_hit; -extern CatVar max_range; -extern CatVar buildings; -extern CatVar ignore_vaccinator; -extern CatVar ambassador; -extern CatVar accuracy; - void CreateMove(); +bool ShouldShoot(); +bool IsTargetStateGood(CachedEntity* entity); +CachedEntity* FindEntInSight(float range); +bool HeadPreferable(CachedEntity* target); +bool UpdateAimkey(); +float EffectiveTargetingRange(); void Draw(); +bool CheckLineBox(Vector B1, Vector B2, Vector L1, Vector L2, Vector& Hit); }}} diff --git a/src/hacks/Walkbot.cpp b/src/hacks/Walkbot.cpp new file mode 100644 index 00000000..8230ed21 --- /dev/null +++ b/src/hacks/Walkbot.cpp @@ -0,0 +1,1008 @@ +/* + * Walkbot.cpp + * + * Created on: Jul 23, 2017 + * Author: nullifiedcat + */ + +#include "../common.h" +#include "../hack.h" + +#include +#include + +namespace hacks { namespace shared { namespace walkbot { + +using index_t = unsigned; +using connection = uint8_t; + +constexpr unsigned VERSION = 2; +constexpr index_t BAD_NODE = unsigned(-1); +constexpr connection MAX_CONNECTIONS = 6; +constexpr connection BAD_CONNECTION = uint8_t(-1); + +index_t CreateNode(const Vector& xyz); +void DeleteNode(index_t node); +float distance_2d(Vector& xyz); +void Save(std::string filename); +bool Load(std::string filename); + +enum ENodeFlags { + NF_GOOD = (1 << 0), + NF_DUCK = (1 << 1), + NF_JUMP = (1 << 2) +}; + +enum EWalkbotState { + WB_DISABLED, + WB_RECORDING, + WB_EDITING, + WB_REPLAYING +}; + +struct walkbot_header_s { + unsigned version { VERSION }; + size_t node_count { 0 }; + size_t map_length { 0 }; + size_t author_length { 0 }; +}; + +enum EConnectionFlags { + CF_GOOD = (1 << 0), + CF_LOW_HEALTH = (1 << 1), + CF_LOW_AMMO = (1 << 2) +}; + +struct connection_s { + index_t node { BAD_NODE }; + unsigned flags { 0 }; + + void link(index_t a) { + flags |= CF_GOOD; + node = a; + } + void unlink() { + flags = 0; + node = BAD_NODE; + } + bool good() const { + return (flags & CF_GOOD); + } + bool free() const { + return not good(); + } +}; + +struct walkbot_node_s { + float x { 0 }; + float y { 0 }; + float z { 0 }; + unsigned flags { 0 }; + connection_s connections[MAX_CONNECTIONS]; + + Vector& xyz() { + return *reinterpret_cast(&x); + } + + connection free_connection() const { + for (connection i = 0; i < MAX_CONNECTIONS; i++) { + if (connections[i].free()) + return i; + } + return BAD_CONNECTION; + } + + void link(index_t node) { + connection free = free_connection(); + if (free == BAD_CONNECTION) { + logging::Info("[wb] Too many connections! Node at (%.2f %.2f %.2f)", x, y, z); + return; + } + connections[free].link(node); + } + + void unlink(index_t node) { + for (connection i = 0; i < MAX_CONNECTIONS; i++) { + if (connections[i].good() and connections[i].node == node) { + connections[i].unlink(); + } + } + } +}; // 40 + +float distance_2d(Vector& xyz) { + float dx = xyz.x - g_pLocalPlayer->v_Origin.x; + float dy = xyz.y - g_pLocalPlayer->v_Origin.y; + return sqrt(dx * dx + dy * dy); +} + +namespace state { + +index_t free_node(); + +// A vector containing all loaded nodes, used in both recording and replaying +std::vector nodes {}; + +bool node_good(index_t node) { + return node != BAD_NODE && node < nodes.size() && (nodes[node].flags & NF_GOOD); +} + +// Target node when replaying, selected node when editing, last node when recording +index_t active_node { BAD_NODE }; +walkbot_node_s *active() { + if (node_good(active_node)) + return &nodes[active_node]; + return nullptr; +} + +// Last reached node when replaying +index_t last_node { BAD_NODE }; +walkbot_node_s *last() { + if (node_good(last_node)) + return &nodes[last_node]; + return nullptr; +} + +// Node closest to your crosshair when editing +index_t closest_node { BAD_NODE }; +walkbot_node_s *closest() { + if (node_good(closest_node)) + return &nodes[closest_node]; + return nullptr; +} + +// Global state +EWalkbotState state { WB_DISABLED }; + +// g_pUserCmd->buttons state when last node was recorded +int last_node_buttons { 0 }; + +// Set to true when bot is moving to nearest node after dying/losing its active node +bool recovery { true }; + +// Time when bot started to move towards next point +std::chrono::system_clock::time_point time {}; + +// A little bit too expensive function, finds next free node or creates one if no free slots exist +index_t free_node() { + for (index_t i = 0; i < nodes.size(); i++) { + if (not (nodes[i].flags & NF_GOOD)) + return i; + } + + nodes.emplace_back(); + return nodes.size() - 1; +} + +} + +using state::nodes; +using state::node_good; + +bool HasLowAmmo() { + // 0x13D = CBaseCombatWeapon::HasPrimaryAmmo() + // 190 = IsBaseCombatWeapon + // 1C1 = C_TFWeaponBase::UsesPrimaryAmmo() + int *weapon_list = (int*)((unsigned)(RAW_ENT(LOCAL_E)) + netvar.hMyWeapons); + for (int i = 0; weapon_list[i]; i++) { + int handle = weapon_list[i]; + int eid = handle & 0xFFF; + if (eid >= 32 && eid <= HIGHEST_ENTITY) { + IClientEntity* weapon = g_IEntityList->GetClientEntity(eid); + if (weapon and vfunc(weapon, 190, 0)(weapon) and + vfunc(weapon, 0x1C1, 0)(weapon) and + not vfunc(weapon, 0x13D, 0)(weapon)) { + return true; + } + } + } + return false; +} + +bool HasLowHealth() { + return float(LOCAL_E->m_iHealth) / float(LOCAL_E->m_iMaxHealth) < 0.45; +} + +void DeleteNode(index_t node) { + if (not node_good(node)) + return; + logging::Info("[wb] Deleting node %u", node); + auto& n = nodes[node]; + for (size_t i = 0; i < MAX_CONNECTIONS; i++) { + if (n.connections[i].good() and node_good(n.connections[i].node)) { + nodes[n.connections[i].node].unlink(node); + } + } + memset(&n, 0, sizeof(walkbot_node_s)); +} + +#define BINARY_FILE_WRITE(handle, data) handle.write(reinterpret_cast(&data), sizeof(data)) +#define BINARY_FILE_READ(handle, data) handle.read(reinterpret_cast(&data), sizeof(data)) + +void Save(std::string filename) { + if (g_Settings.bInvalid) { + logging::Info("Not in-game, cannot save!"); + return; + } + { + DIR* walkbot_dir = opendir("cathook/walkbot"); + if (!walkbot_dir) { + logging::Info("Walkbot directory doesn't exist, creating one!"); + mkdir("cathook/walkbot", S_IRWXU | S_IRWXG); + } else closedir(walkbot_dir); + } + std::string path = format("cathook/walkbot/", GetLevelName()); + { + DIR* level_dir = opendir(path.c_str()); + if (!level_dir) { + logging::Info("Walkbot directory for %s doesn't exist, creating one!", GetLevelName().c_str()); + mkdir(path.c_str(), S_IRWXU | S_IRWXG); + } else closedir(level_dir); + } + logging::Info("Saving in %s", format(path, "/", filename).c_str()); + try { + std::ofstream file(format(path, "/", filename), std::ios::out | std::ios::binary); + if (not file) { + logging::Info("Could not open file!"); + return; + } + walkbot_header_s header; + header.node_count = state::nodes.size(); + const char* name = g_ISteamFriends->GetPersonaName(); + const char* map = g_IEngine->GetLevelName(); + size_t name_s = strlen(name); + size_t map_s = strlen(map); + header.author_length = name_s; + header.map_length = map_s; + BINARY_FILE_WRITE(file, header); + file.write(map, map_s); + file.write(name, name_s); + file.write(reinterpret_cast(state::nodes.data()), sizeof(walkbot_node_s) * header.node_count); + file.close(); + logging::Info("Writing successful"); + } catch (std::exception& e) { + logging::Info("Writing unsuccessful: %s", e.what()); + } +} + +bool Load(std::string filename) { + { + DIR* walkbot_dir = opendir("cathook/walkbot"); + if (!walkbot_dir) { + logging::Info("Walkbot directory doesn't exist, creating one!"); + mkdir("cathook/walkbot", S_IRWXU | S_IRWXG); + } else closedir(walkbot_dir); + } + std::string path = format("cathook/walkbot/", GetLevelName()); + { + DIR* level_dir = opendir(path.c_str()); + if (!level_dir) { + logging::Info("Walkbot directory for %s doesn't exist, creating one!", GetLevelName().c_str()); + mkdir(path.c_str(), S_IRWXU | S_IRWXG); + } else closedir(level_dir); + } + try { + std::ifstream file(format(path, "/", filename), std::ios::in | std::ios::binary); + if (!file) { + return false; + } + walkbot_header_s header; + BINARY_FILE_READ(file, header); + // FIXME magic number: 1 + if (header.version != VERSION) { + logging::Info("Outdated/corrupted walkbot file! Cannot load this."); + file.close(); + return false; + } + if (header.author_length > 64 or header.map_length > 512 or (not header.author_length or not header.map_length)) { + logging::Info("Corrupted author/level data"); + } else { + char name_buffer[header.author_length + 1]; + char map_buffer[header.map_length + 1]; + file.read(map_buffer, header.map_length); + file.read(name_buffer, header.author_length); + name_buffer[header.author_length] = 0; + map_buffer[header.map_length] = 0; + logging::Info("Walkbot navigation map for %s\nAuthor: %s", map_buffer, name_buffer); + } + state::nodes.clear(); + logging::Info("Reading %i entries...", header.node_count); + if (header.node_count > 32768) { + logging::Info("Read %d nodes, max is %d. Aborting.", header.node_count, 32768); + return false; + } + state::nodes.resize(header.node_count); + file.read(reinterpret_cast(state::nodes.data()), sizeof(walkbot_node_s) * header.node_count); + file.close(); + logging::Info("Reading successful! Result: %i entries.", state::nodes.size()); + return true; + } catch (std::exception& e) { + logging::Info("Reading unsuccessful: %s", e.what()); + } + return false; +} + +static CatCommand save("wb_save", "Save", [](const CCommand& args) { + logging::Info("Saving"); + std::string filename = "default"; + if (args.ArgC() > 1) { + filename = args.Arg(1); + } + Save(filename); +}); +static CatCommand load("wb_load", "Load", [](const CCommand& args) { + logging::Info("Loading"); + std::string filename = "default"; + if (args.ArgC() > 1) { + filename = args.Arg(1); + } + Load(filename); +}); + +index_t CreateNode(const Vector& xyz) { + index_t node = state::free_node(); + logging::Info("[wb] Creating node %u at (%.2f %.2f %.2f)", node, xyz.x, xyz.y, xyz.z); + auto& n = state::nodes[node]; + memset(&n, 0, sizeof(n)); + n.xyz() = xyz; + n.flags |= NF_GOOD; + return node; +} + +CatVar active_recording(CV_SWITCH, "wb_recording", "0", "Do recording", "Use BindToggle with this"); +CatVar draw_info(CV_SWITCH, "wb_info", "1", "Walkbot info"); +CatVar draw_path(CV_SWITCH, "wb_path", "1", "Walkbot path"); +CatVar draw_nodes(CV_SWITCH, "wb_nodes", "1", "Walkbot nodes"); +CatVar draw_indices(CV_SWITCH, "wb_indices", "0", "Node indices"); +CatVar free_move(CV_SWITCH, "wb_freemove", "1", "Allow free movement", "Allow free movement while pressing movement keys"); +CatVar spawn_distance(CV_FLOAT, "wb_node_spawn_distance", "54", "Node spawn distance"); +CatVar max_distance(CV_FLOAT, "wb_replay_max_distance", "100", "Max distance to node when replaying"); +CatVar reach_distance(CV_FLOAT, "wb_replay_reach_distance", "32", "Distance where bot can be considered 'stepping' on the node"); +CatVar draw_connection_flags(CV_SWITCH, "wb_connection_flags", "1", "Connection flags"); +CatVar force_slot(CV_INT, "wb_force_slot", "1", "Force slot", "Walkbot will always select weapon in this slot"); +CatVar leave_if_empty(CV_SWITCH, "wb_leave_if_empty", "0", "Leave if no walkbot", "Leave game if there is no walkbot map"); + +CatCommand c_start_recording("wb_record", "Start recording", []() { state::state = WB_RECORDING; }); +CatCommand c_start_editing("wb_edit", "Start editing", []() { state::state = WB_EDITING; }); +CatCommand c_start_replaying("wb_replay", "Start replaying", []() { + state::last_node = state::active_node; + state::active_node = state::closest_node; + state::state = WB_REPLAYING; +}); +CatCommand c_exit("wb_exit", "Exit", []() { state::state = WB_DISABLED; }); + +// Selects closest node, clears selection if node is selected +CatCommand c_select_node("wb_select", "Select node", []() { + if (state::active_node == state::closest_node) { + state::active_node = BAD_NODE; + } else { + state::active_node = state::closest_node; + } +}); +// Makes a new node in the middle of connection between 2 nodes +CatCommand c_split_connection("wb_split", "Split connection", []() { + if (not (state::node_good(state::active_node) and state::node_good(state::closest_node))) + return; + + if (state::active_node == state::closest_node) + return; + + auto& a = state::nodes[state::active_node]; + auto& b = state::nodes[state::closest_node]; + + a.unlink(state::closest_node); + b.unlink(state::active_node); + + index_t node = CreateNode((a.xyz() + b.xyz()) / 2); + auto& n = state::nodes[node]; + a.link(node); + n.link(state::active_node); + b.link(node); + n.link(state::closest_node); + +}); +// Deletes closest node and its connections +CatCommand c_delete_node("wb_delete", "Delete node", []() { + DeleteNode(state::closest_node); +}); +// Creates a new node under your feet and connects it to closest node to your crosshair +CatCommand c_create_node("wb_create", "Create node", []() { + index_t node = CreateNode(g_pLocalPlayer->v_Origin); + auto& n = state::nodes[node]; + if (g_pUserCmd->buttons & IN_DUCK) + n.flags |= NF_DUCK; + if (state::node_good(state::closest_node)) { + auto& c = state::nodes[state::closest_node]; + n.link(state::closest_node); + c.link(node); + logging::Info("[wb] Node %u linked to node %u at (%.2f %.2f %.2f)", node, state::closest_node, c.x, c.y, c.z); + } +}); +// Connects selected node to closest one +CatCommand c_connect_node("wb_connect", "Connect nodes", []() { + if (not (state::node_good(state::active_node) and state::node_good(state::closest_node))) + return; + // Don't link a node to itself, idiot + if (state::active_node == state::closest_node) + return; + + auto& a = state::nodes[state::active_node]; + auto& b = state::nodes[state::closest_node]; + + a.link(state::closest_node); + b.link(state::active_node); +}); +// Makes a one-way connection +CatCommand c_connect_single_node("wb_connect_single", "Connect nodes (one-way)", []() { + if (not (state::node_good(state::active_node) and state::node_good(state::closest_node))) + return; + // Don't link a node to itself, idiot + if (state::active_node == state::closest_node) + return; + + auto& a = state::nodes[state::active_node]; + + a.link(state::closest_node); +}); +// Connects selected node to closest one +CatCommand c_disconnect_node("wb_disconnect", "Disconnect nodes", []() { + if (not (state::node_good(state::active_node) and state::node_good(state::closest_node))) + return; + // Don't link a node to itself, idiot + if (state::active_node == state::closest_node) + return; + + auto& a = state::nodes[state::active_node]; + auto& b = state::nodes[state::closest_node]; + + a.unlink(state::closest_node); + b.unlink(state::active_node); +}); +// Makes a one-way connection +CatCommand c_disconnect_single_node("wb_disconnect_single", "Connect nodes (one-way)", []() { + if (not (state::node_good(state::active_node) and state::node_good(state::closest_node))) + return; + // Don't link a node to itself, idiot + if (state::active_node == state::closest_node) + return; + + auto& a = state::nodes[state::active_node]; + + a.unlink(state::closest_node); +}); +// Toggles jump flag on closest node +CatCommand c_update_duck("wb_duck", "Toggle duck flag", []() { + if (not state::node_good(state::closest_node)) + return; + + auto& n = state::nodes[state::closest_node]; + + if (n.flags & NF_DUCK) + n.flags &= ~NF_DUCK; + else + n.flags |= NF_DUCK; +}); +// Toggles jump flag on closest node +CatCommand c_update_jump("wb_jump", "Toggle jump flag", []() { + if (not state::node_good(state::closest_node)) + return; + + auto& n = state::nodes[state::closest_node]; + + if (n.flags & NF_JUMP) + n.flags &= ~NF_JUMP; + else + n.flags |= NF_JUMP; +}); +// Assuming node is good and conn is in range [0; MAX_CONNECTIONS) +std::string DescribeConnection(index_t node, connection conn) { + const connection_s& c = nodes[node].connections[conn]; + std::string extra; + bool broken = not node_good(c.node); + bool oneway = true; + if (not broken) { + auto& n = state::nodes[c.node]; + for (size_t j = 0; j < MAX_CONNECTIONS; j++) { + if (n.connections[j].good() and n.connections[j].node == node) { + oneway = false; + break; + } + } + if (c.flags & CF_LOW_AMMO) { + extra += "A"; + } + if (c.flags & CF_LOW_HEALTH) { + extra += "H"; + } + } + std::string result = format(node, ' ', (broken ? "-x>" : (oneway ? "-->" : "<->")), ' ', c.node, ' ', extra); + return result; +} +CatCommand c_toggle_cf_ammo("wb_conn_ammo", "Toggle 'ammo' flag on connection from ACTIVE to CLOSEST node", []() { + auto a = state::active(); + auto b = state::closest(); + if (not (a and b)) return; + for (connection i = 0; i < MAX_CONNECTIONS; i++) { + auto& c = a->connections[i]; + if (c.free()) + continue; + if (c.node != state::closest_node) + continue; + // Actually flip the flag + if (c.flags & CF_LOW_AMMO) + c.flags &= ~CF_LOW_AMMO; + else + c.flags |= CF_LOW_AMMO; + } +}); +CatCommand c_toggle_cf_health("wb_conn_health", "Toggle 'health' flag on connection from ACTIVE to CLOSEST node", []() { + auto a = state::active(); + auto b = state::closest(); + if (not (a and b)) return; + for (connection i = 0; i < MAX_CONNECTIONS; i++) { + auto& c = a->connections[i]; + if (c.free()) + continue; + if (c.node != state::closest_node) + continue; + // Actually flip the flag + if (c.flags & CF_LOW_HEALTH) + c.flags &= ~CF_LOW_HEALTH; + else + c.flags |= CF_LOW_HEALTH; + } +}); +// Displays all info about closest node and its connections +CatCommand c_info("wb_dump", "Show info", []() { + index_t node = state::closest_node; + if (not node_good(node)) + return; + + auto& n = nodes[node]; + + logging::Info("[wb] Info about node %u", node); + logging::Info("[wb] Flags: Duck=%d, Jump=%d, Raw=%u", n.flags & NF_DUCK, n.flags & NF_JUMP, n.flags); + logging::Info("[wb] X: %.2f | Y: %.2f | Z: %.2f", n.x, n.y, n.z); + logging::Info("[wb] Connections:"); + for (size_t i = 0; i < MAX_CONNECTIONS; i++) { + if (n.connections[i].free()) + continue; + logging::Info("[wb] %s", DescribeConnection(node, i).c_str()); + } +}); +// Deletes a whole region of nodes +// Deletes a single closest node if no node is selected +CatCommand c_delete_region("wb_delete_region", "Delete region of nodes", []() { + logging::Info("< DISABLED >"); + /*index_t a = state::active_node; + index_t b = state::closest_node; + + if (not (state::node_good(a) and state::node_good(b))) + return; + + index_t current = state::closest_node; + index_t next = INVALID_NODE; + + do { + auto& n = state::nodes[current]; + + if (n.connection_count > 2) { + logging::Info("[wb] More than 2 connections on a node! Quitting."); + return; + } + bool found_next = false; + for (size_t i = 0; i < 2; i++) { + if (n.connections[i] != current) { + next = n.connections[i]; + found_next = true; + } + } + DeleteNode(current); + current = next; + if (not found_next) { + logging::Info("[wb] Dead end? Can't find next node after %u", current); + break; + } + } while (state::node_good(current) and (current != a));*/ +}); +// Clears the state +CatCommand c_clear("wb_clear", "Removes all nodes", []() { + state::nodes.clear(); +}); + +void Initialize() { +} + +void UpdateClosestNode() { + float n_fov = 360.0f; + index_t n_idx = BAD_NODE; + + for (index_t i = 0; i < state::nodes.size(); i++) { + auto& node = state::nodes[i]; + + if (not node.flags & NF_GOOD) + continue; + // Eclipse shits itself when it sees Vector& beung used as Vector in GetFov + float fov = GetFov(g_pLocalPlayer->v_OrigViewangles, g_pLocalPlayer->v_Eye, node.xyz()); + if (fov < n_fov) { + n_fov = fov; + n_idx = i; + } + } + + // Don't select a node if you don't even look at it + if (n_fov < 10) + state::closest_node = n_idx; + else + state::closest_node = BAD_NODE; +} + +// Finds nearest node by position, not FOV +// Not to be confused with FindClosestNode +index_t FindNearestNode(bool traceray) { + index_t r_node { BAD_NODE }; + float r_dist { 65536.0f }; + + for (index_t i = 0; i < state::nodes.size(); i++) { + if (state::node_good(i)) { + auto& n = state::nodes[i]; + if (traceray and not IsVectorVisible(g_pLocalPlayer->v_Eye, n.xyz())) + continue; + float dist = distance_2d(n.xyz()); + if (dist < r_dist) { + r_dist = dist; + r_node = i; + } + } + } + + return r_node; +} + +index_t SelectNextNode() { + if (not state::node_good(state::active_node)) { + return FindNearestNode(true); + } + auto& n = state::nodes[state::active_node]; + // TODO medkit connections and shit + std::vector chance {}; + for (index_t i = 0; i < MAX_CONNECTIONS; i++) { + if (n.connections[i].good() and n.connections[i].node != state::last_node and node_good(n.connections[i].node)) { + if (HasLowAmmo() && (n.connections[i].flags & CF_LOW_AMMO)) { + return n.connections[i].node; + } + if (HasLowHealth() && (n.connections[i].flags & CF_LOW_HEALTH)) { + return n.connections[i].node; + } + if (not (n.connections[i].flags & (CF_LOW_AMMO | CF_LOW_HEALTH))) + chance.push_back(n.connections[i].node); + } + } + if (not chance.empty()) { + return chance.at(unsigned(rand()) % chance.size()); + } else { + return BAD_NODE; + } + return BAD_NODE; +} + +bool free_move_used = false; + +void UpdateSlot() { + static auto last_check = std::chrono::system_clock::now(); + auto ms = std::chrono::duration_cast(std::chrono::system_clock::now() - last_check).count(); + + if (CE_GOOD(LOCAL_E) && CE_GOOD(LOCAL_W) && !g_pLocalPlayer->life_state && ms > 1000) { + IClientEntity* weapon = RAW_ENT(LOCAL_W); + // IsBaseCombatWeapon() + if (vfunc(weapon, 190, 0)(weapon)) { + int slot = vfunc(weapon, 395, 0)(weapon); + if (slot != int(force_slot) - 1) { + hack::ExecuteCommand(format("slot", int(force_slot))); + } + } + } + + last_check = std::chrono::system_clock::now(); +} + +void UpdateWalker() { + free_move_used = false; + if (free_move) { + if (g_pUserCmd->forwardmove != 0.0f or g_pUserCmd->sidemove != 0.0f) { + free_move_used = true; + return; + } + } + + static int jump_ticks = 0; + if (jump_ticks > 0) { + g_pUserCmd->buttons |= IN_JUMP; + jump_ticks--; + } + bool timeout = std::chrono::duration_cast(std::chrono::system_clock::now() - state::time).count() > 1; + if (not state::node_good(state::active_node) or timeout) { + state::active_node = FindNearestNode(true); + state::recovery = true; + } + auto& n = state::nodes[state::active_node]; + WalkTo(n.xyz()); + if (state::node_good(state::last_node)) { + auto& l = state::nodes[state::last_node]; + if (l.flags & NF_DUCK) + g_pUserCmd->buttons |= IN_DUCK; + } + float dist = distance_2d(n.xyz()); + if (dist > float(max_distance)) { + state::active_node = FindNearestNode(true); + state::recovery = true; + } + if (dist < float(reach_distance)) { + state::recovery = false; + index_t last = state::active_node; + state::active_node = SelectNextNode(); + state::last_node = last; + state::time = std::chrono::system_clock::now(); + if (state::node_good(state::active_node)) { + if (state::nodes[state::active_node].flags & NF_JUMP) { + g_pUserCmd->buttons |= IN_DUCK; + g_pUserCmd->buttons |= IN_JUMP; + jump_ticks = 6; + } + } else { + if (not state::recovery) { + state::recovery = true; + } + } + } +} + +bool ShouldSpawnNode() { + if (not state::node_good(state::active_node)) + return true; + + bool was_jumping = state::last_node_buttons & IN_JUMP; + bool is_jumping = g_pUserCmd->buttons & IN_JUMP; + + if (was_jumping != is_jumping and is_jumping) + return true; + + if ((state::last_node_buttons & IN_DUCK) != (g_pUserCmd->buttons & IN_DUCK)) + return true; + + auto& node = state::nodes[state::active_node]; + + if (distance_2d(node.xyz()) > float(spawn_distance)) { + return true; + } + + return false; +} + +void RecordNode() { + index_t node = CreateNode(g_pLocalPlayer->v_Origin); + auto& n = state::nodes[node]; + if (g_pUserCmd->buttons & IN_DUCK) + n.flags |= NF_DUCK; + if (g_pUserCmd->buttons & IN_JUMP) + n.flags |= NF_JUMP; + if (state::node_good(state::active_node)) { + auto& c = state::nodes[state::active_node]; + n.link(state::active_node); + c.link(node); + logging::Info("[wb] Node %u auto-linked to node %u at (%.2f %.2f %.2f)", node, state::active_node, c.x, c.y, c.z); + } + state::last_node_buttons = g_pUserCmd->buttons; + state::active_node = node; +} + +#ifndef TEXTMODE + +// Draws a single colored connection between 2 nodes +void DrawConnection(index_t a, connection_s& b) { + if (b.free()) + return; + if (not (node_good(a) and node_good(b.node))) + return; + + auto& a_ = state::nodes[a]; + auto& b_ = state::nodes[b.node]; + + Vector center = (a_.xyz() + b_.xyz()) / 2; + Vector center_connection = (a_.xyz() + center) / 2; + + Vector wts_a, wts_c, wts_cc; + if (not (draw::WorldToScreen(a_.xyz(), wts_a) and draw::WorldToScreen(center, wts_c) and draw::WorldToScreen(center_connection, wts_cc))) + return; + + rgba_t* color = &colors::white; + if ((a_.flags & b_.flags) & NF_JUMP) color = &colors::yellow; + else if ((a_.flags & b_.flags) & NF_DUCK) color = &colors::green; + + drawgl::Line(wts_a.x, wts_a.y, wts_c.x - wts_a.x, wts_c.y - wts_a.y, color->rgba); + + if (draw_connection_flags && b.flags != CF_GOOD) { + std::string flags; + if (b.flags & CF_LOW_AMMO) flags += "A"; + if (b.flags & CF_LOW_HEALTH) flags += "H"; + int size_x = 0, size_y = 0; + FTGL_StringLength(flags, fonts::ftgl_ESP, &size_x, &size_y); + FTGL_Draw(flags, wts_cc.x - size_x / 2, wts_cc.y - size_y - 4, fonts::ftgl_ESP); + } +} + +// Draws a node and its connections +void DrawNode(index_t node, bool draw_back) { + if (not state::node_good(node)) + return; + + auto& n = state::nodes[node]; + + for (size_t i = 0; i < MAX_CONNECTIONS; i++) { + DrawConnection(node, n.connections[i]); + } + + if (draw_nodes) { + rgba_t* color = &colors::white; + if (n.flags & NF_JUMP) color = &colors::yellow; + else if (n.flags & NF_DUCK) color = &colors::green; + + Vector wts; + if (not draw::WorldToScreen(n.xyz(), wts)) + return; + + size_t node_size = 2; + if (state::state != WB_REPLAYING) { + if (node == state::closest_node) + node_size = 6; + } + if (node == state::active_node) + color = &colors::red; + + drawgl::FilledRect(wts.x - node_size, wts.y - node_size, 2 * node_size, 2 * node_size, color->rgba); + } + + if (draw_indices) { + rgba_t* color = &colors::white; + if (n.flags & NF_JUMP) color = &colors::yellow; + else if (n.flags & NF_DUCK) color = &colors::green; + + Vector wts; + if (not draw::WorldToScreen(n.xyz(), wts)) + return; + + FTGL_Draw(std::to_string(node), wts.x, wts.y, fonts::ftgl_ESP, *color); + } +} + +void DrawPath() { + for (index_t i = 0; i < state::nodes.size(); i++) { + DrawNode(i, true); + } +} + +void Draw() { + if (state::state == WB_DISABLED) return; + switch (state::state) { + case WB_RECORDING: { + AddSideString("Walkbot: Recording"); + } break; + case WB_EDITING: { + AddSideString("Walkbot: Editing"); + } break; + case WB_REPLAYING: { + AddSideString("Walkbot: Replaying"); + if (free_move and free_move_used) { + AddSideString("Walkbot: FREE MOVEMENT (User override)", colors::green); + } + if (HasLowAmmo()) { + AddSideString("Walkbot: LOW AMMO", colors::yellow); + } + if (HasLowHealth()) { + AddSideString("Walkbot: LOW HEALTH", colors::red); + } + } break; + } + if (draw_info) { + AddSideString(format("Active node: ", state::active_node)); + AddSideString(format("Highlighted node: ", state::closest_node)); + AddSideString(format("Last node: ", state::last_node)); + AddSideString(format("Node count: ", state::nodes.size())); + if (state::recovery) { + AddSideString(format("(Recovery mode)")); + } + } + if (draw_path) + DrawPath(); +} + +#endif + +void OnLevelInit() { + if (leave_if_empty && state::state == WB_REPLAYING) { + nodes.clear(); + } +} + +static CatVar wb_abandon_too_many_bots(CV_INT, "wb_population_control", "0", "Abandon if bots >"); +void CheckLivingSpace() { +#if IPC_ENABLED + if (ipc::peer && wb_abandon_too_many_bots) { + std::vector players {}; + for (int j = 1; j < 32; j++) { + player_info_s info; + if (g_IEngine->GetPlayerInfo(j, &info)) { + if (info.friendsID) + players.push_back(info.friendsID); + } + } + int count = 0; + unsigned highest = 0; + std::vector botlist {}; + for (unsigned i = 1; i < cat_ipc::max_peers; i++) { + if (!ipc::peer->memory->peer_data[i].free) { + for (auto& k : players) { + if (ipc::peer->memory->peer_user_data[i].friendid && k == ipc::peer->memory->peer_user_data[i].friendid) { + botlist.push_back(i); + count++; + highest = i; + } + } + } + } + if (ipc::peer->client_id == highest && count > int(wb_abandon_too_many_bots)) { + static Timer timer {}; + if (timer.test_and_set(1000 * 5)) { + logging::Info("Found %d other bots in-game, abandoning (%u)", count, ipc::peer->client_id); + for (auto i : botlist) { + logging::Info("-> Bot %d with ID %u", i, ipc::peer->memory->peer_user_data[i].friendid); + } + g_TFGCClientSystem->SendExitMatchmaking(true); + } + } + } +#endif +} + +void Move() { + if (state::state == WB_DISABLED) return; + switch (state::state) { + case WB_RECORDING: { + UpdateClosestNode(); + if (active_recording and ShouldSpawnNode()) { + RecordNode(); + } + } break; + case WB_EDITING: { + UpdateClosestNode(); + } break; + case WB_REPLAYING: { + if (leave_if_empty) { + if (nodes.size() == 0) { + Load("default"); + if (nodes.size() == 0) { + static auto last_abandon = std::chrono::system_clock::from_time_t(0); + auto s = std::chrono::duration_cast(std::chrono::system_clock::now() - last_abandon).count(); + + if (s < 3) { + return; + } + logging::Info("No map file, shutting down"); + g_TFGCClientSystem->SendExitMatchmaking(true); + last_abandon = std::chrono::system_clock::now(); + } + } + } + static Timer livingspace_timer {}; + if (livingspace_timer.test_and_set(1000 * 8)) { + CheckLivingSpace(); + } + if (nodes.size() == 0) return; + if (force_slot) + UpdateSlot(); + UpdateWalker(); + } break; + } +} + +}}} diff --git a/src/hacks/Walkbot.hpp b/src/hacks/Walkbot.hpp new file mode 100644 index 00000000..ce20930e --- /dev/null +++ b/src/hacks/Walkbot.hpp @@ -0,0 +1,19 @@ +/* + * Walkbot.hpp + * + * Created on: Jul 23, 2017 + * Author: nullifiedcat + */ + +#pragma once + +namespace hacks { namespace shared { namespace walkbot { + +void Initialize(); +#ifndef TEXTMODE +void Draw(); +#endif +void Move(); +void OnLevelInit(); + +}}} diff --git a/src/hacks/ac/aimbot.cpp b/src/hacks/ac/aimbot.cpp new file mode 100644 index 00000000..a001901f --- /dev/null +++ b/src/hacks/ac/aimbot.cpp @@ -0,0 +1,80 @@ +/* + * aimbot.cpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#include "aimbot.hpp" +#include "../../common.h" + +namespace ac { namespace aimbot { + +static CatVar enabled(CV_SWITCH, "ac_aimbot", "0", "Detect Aimbot", "Is not recommended"); +static CatVar detect_angle(CV_FLOAT, "ac_aimbot_angle", "30", "Aimbot Angle"); +static CatVar detections_warning(CV_INT, "ac_aimbot_detections", "3", "Min detections to warn"); + +ac_data data_table[32]; + +void ResetEverything() { + memset(&data_table, 0, sizeof(ac_data) * 32); +} + +void ResetPlayer(int idx) { + memset(&data_table[idx - 1], 0, sizeof(ac_data)); +} + +void Init() { + ResetEverything(); +} + +void Update(CachedEntity* player) { + if (not enabled) return; + auto& data = data_table[player->m_IDX - 1]; + if (data.check_timer) { + data.check_timer--; + if (!data.check_timer) { + auto& angles = angles::data(player); + float deviation = angles.deviation(2); + if (deviation > float(detect_angle)) { + //logging::Info("[ac] %d deviation %.2f #%d", player->m_IDX, deviation, data.detections); + if (++data.detections > int(detections_warning)) { + const char* wp_name = "[unknown]"; + int widx = CE_INT(player, netvar.hActiveWeapon) & 0xFFF; + if (IDX_GOOD(widx)) { + CachedEntity* weapon = ENTITY(widx); + wp_name = weapon->InternalEntity()->GetClientClass()->GetName(); + /*logging::Info("%d", weapon->m_IDX); + logging::Info("%s", ); + IClientEntity* e_weapon = RAW_ENT(weapon); + if (CE_GOOD(weapon)) { + const char* wname = vfunc(e_weapon, 398, 0)(e_weapon); + if (wname) wp_name = wname; + }*/ + } + hacks::shared::anticheat::Accuse(player->m_IDX, "Aimbot", format("Weapon: ", wp_name, " | Deviation: ", deviation, "° | ", data.detections)); + } + } + } + } +} + +void Event(KeyValues* event) { + if (not enabled) return; + if (!strcmp(event->GetName(), "player_death") || !strcmp(event->GetName(), "player_hurt")) { + int attacker = event->GetInt("attacker"); + int victim = event->GetInt("userid"); + int eid = g_IEngine->GetPlayerForUserID(attacker); + int vid = g_IEngine->GetPlayerForUserID(victim); + if (eid > 0 && eid < 33) { + CachedEntity* victim = ENTITY(vid); + CachedEntity* attacker = ENTITY(eid); + if (victim->m_vecOrigin.DistTo(attacker->m_vecOrigin) > 250) { + data_table[eid - 1].check_timer = 1; + data_table[eid - 1].last_weapon = event->GetInt("weaponid"); + } + } + } +} + +}} diff --git a/src/hacks/ac/aimbot.hpp b/src/hacks/ac/aimbot.hpp new file mode 100644 index 00000000..d3022e84 --- /dev/null +++ b/src/hacks/ac/aimbot.hpp @@ -0,0 +1,30 @@ +/* + * aimbot.hpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class KeyValues; +class CachedEntity; + +#include + +namespace ac { namespace aimbot { + +struct ac_data { + size_t detections; + int check_timer; + int last_weapon; +}; + +void ResetEverything(); +void ResetPlayer(int idx); + +void Init(); +void Update(CachedEntity* player); +void Event(KeyValues* event); + +}} diff --git a/src/hacks/ac/antiaim.cpp b/src/hacks/ac/antiaim.cpp new file mode 100644 index 00000000..e3556047 --- /dev/null +++ b/src/hacks/ac/antiaim.cpp @@ -0,0 +1,51 @@ +/* + * antiaim.cpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#include "antiaim.hpp" +#include "../../common.h" + +namespace ac { namespace antiaim { + +unsigned long last_accusation[32] { 0 }; + +void ResetEverything() { + memset(last_accusation, 0, sizeof(unsigned long) * 32); +} + +void ResetPlayer(int idx) { + last_accusation[idx - 1] = 0; +} + +void Init() { + ResetEverything(); +} + +void Update(CachedEntity* player) { + if (tickcount - last_accusation[player->m_IDX - 1] < 60 * 60) return; + const auto& d = angles::data(player); + if (d.angle_count) { + int idx = d.angle_index - 1; + if (idx < 0) idx = d.count - 1; + if ((d.angles[idx].x < -89 || d.angles[idx].x > 89) && (d.angles[idx].x < 89.2941 || d.angles[idx].x > 89.2942)) { + std::string reason = format("Pitch: ", d.angles[idx].x, " Yaw: ", d.angles[idx].y); + if (d.angles[idx].x == -271.0f) { + reason += " (Fakeup)"; + } else if (d.angles[idx].x == 271.0f) { + reason += " (Fakedown)"; + } + hacks::shared::anticheat::Accuse(player->m_IDX, "AntiAim", reason); + last_accusation[player->m_IDX - 1] = tickcount; + } + } +} + +void Event(KeyValues* event) { + +} + +}} + diff --git a/src/hacks/ac/antiaim.hpp b/src/hacks/ac/antiaim.hpp new file mode 100644 index 00000000..2b5b5c3e --- /dev/null +++ b/src/hacks/ac/antiaim.hpp @@ -0,0 +1,25 @@ +/* + * antiaim.hpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class KeyValues; +class CachedEntity; + +namespace ac { namespace antiaim { + +void ResetEverything(); +void ResetPlayer(int idx); + +void Init(); +void Update(CachedEntity* player); +void Event(KeyValues* event); + +}} + + + diff --git a/src/hacks/ac/bhop.cpp b/src/hacks/ac/bhop.cpp new file mode 100644 index 00000000..7bcadcde --- /dev/null +++ b/src/hacks/ac/bhop.cpp @@ -0,0 +1,64 @@ +/* + * bhop.cpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#include "bhop.hpp" +#include "../../common.h" + +namespace ac { namespace bhop { + +static CatVar bhop_detect_count(CV_INT, "ac_bhop_count", "4", "BHop Detections"); + +ac_data data_table[32] {}; + +void ResetEverything() { + memset(data_table, 0, sizeof(ac_data) * 32); +} + +void ResetPlayer(int idx) { + memset(&data_table[idx - 1], 0, sizeof(ac_data)); +} + +void Init() { + ResetEverything(); +} + +void Update(CachedEntity* player) { + auto& data = data_table[player->m_IDX - 1]; + bool ground = player->var(netvar.iFlags) & FL_ONGROUND; + if (ground) { + if (!data.was_on_ground) { + data.ticks_on_ground = 1; + } else { + data.ticks_on_ground++; + } + } else { + if (data.was_on_ground) { + if (data.ticks_on_ground == 1) { + data.detections++; + // TODO FIXME + if (data.detections >= int(bhop_detect_count)) { + logging::Info("[%d] Suspected BHop: %d", player->m_IDX, data.detections); + if ((tickcount - data.last_accusation) > 600) { + hacks::shared::anticheat::Accuse(player->m_IDX, "Bunnyhop", format("Perfect jumps = ", data.detections)); + data.last_accusation = tickcount; + } + } + } else { + data.detections = 0; + } + } + data.ticks_on_ground = 0; + } + data.was_on_ground = ground; +} + +void Event(KeyValues* event) { + +} + +}} + diff --git a/src/hacks/ac/bhop.hpp b/src/hacks/ac/bhop.hpp new file mode 100644 index 00000000..01afca63 --- /dev/null +++ b/src/hacks/ac/bhop.hpp @@ -0,0 +1,32 @@ +/* + * bhop.hpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class KeyValues; +class CachedEntity; + +namespace ac { namespace bhop { + +struct ac_data { + int detections { 0 }; + bool was_on_ground { false }; + int ticks_on_ground { 0 }; + unsigned long last_accusation { 0 }; +}; + +void ResetEverything(); +void ResetPlayer(int idx); + +void Init(); +void Update(CachedEntity* player); +void Event(KeyValues* event); + +}} + + + diff --git a/src/hacks/ac/removecond.cpp b/src/hacks/ac/removecond.cpp new file mode 100644 index 00000000..297aeb04 --- /dev/null +++ b/src/hacks/ac/removecond.cpp @@ -0,0 +1,55 @@ +/* + * removecond.cpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#include "removecond.hpp" +#include "../../common.h" + +namespace ac { namespace removecond { + +static CatVar removecond_detect(CV_SWITCH, "ac_removecond", "0", "Detect RemoveCond"); +static CatVar removecond_timer(CV_FLOAT, "ac_removecond_timer", "1.1", "RemoveCond timer"); + +ac_data data_table[32] {}; + +void ResetEverything() { + memset(data_table, 0, sizeof(ac_data) * 32); +} + +void ResetPlayer(int idx) { + memset(&data_table[idx - 1], 0, sizeof(ac_data)); +} + +void Init() { + ResetEverything(); +} + +void Update(CachedEntity* player) { + if (!removecond_detect) return; + auto& d = data_table[player->m_IDX - 1]; + if (CE_GOOD(player)) { + float simtime = player->var(netvar.m_flSimulationTime); + if (player->var(netvar.m_flSimulationTime) != d.stime) { + if (d.stime && (simtime - d.stime > float(removecond_timer))) { + d.detections++; + if (tickcount - d.last_accusation > 60 * 30 || !d.last_accusation) { + hacks::shared::anticheat::Accuse(player->m_IDX, "Crithack/Removecond", format("Detections: ", d.detections, " dt: ", simtime - d.stime)); + d.last_accusation = tickcount; + } + } + } + d.stime = simtime; + if (CE_BYTE(player, netvar.iLifeState)) d.stime = 0.0f; + } else { + d.stime = 0.0f; + } +} + +void Event(KeyValues* event) { + +} + +}} diff --git a/src/hacks/ac/removecond.hpp b/src/hacks/ac/removecond.hpp new file mode 100644 index 00000000..1d6274b8 --- /dev/null +++ b/src/hacks/ac/removecond.hpp @@ -0,0 +1,29 @@ +/* + * removecond.hpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class KeyValues; +class CachedEntity; + +namespace ac { namespace removecond { + +struct ac_data { + float stime; + int detections; + unsigned long last_accusation; +}; + +void ResetEverything(); +void ResetPlayer(int idx); + +void Init(); +void Update(CachedEntity* player); +void Event(KeyValues* event); + +}} + diff --git a/src/hacks/hacklist.h b/src/hacks/hacklist.h index 0c23ef48..fe4cd48a 100644 --- a/src/hacks/hacklist.h +++ b/src/hacks/hacklist.h @@ -8,28 +8,37 @@ #ifndef HACKS_HACKLIST_H_ #define HACKS_HACKLIST_H_ +#ifndef TEXTMODE + +#include "ESP.h" +#include "SkinChanger.hpp" +#include "Radar.hpp" +#include "SpyAlert.h" + +#endif + #include "Aimbot.h" #include "AntiAim.h" #include "AntiDisguise.h" #include "AutoHeal.h" #include "AutoReflect.h" #include "AutoSticky.h" +#include "AntiCheat.hpp" #include "Bunnyhop.h" -#include "ESP.h" #include "LagExploit.hpp" +#include "Walkbot.hpp" +#include "AutoJoin.hpp" #include "AntiBackstab.hpp" #include "AutoBackstab.hpp" #include "FollowBot.h" +#include "HealArrows.hpp" #include "Misc.h" -#include "SpyAlert.h" #include "Trigger.h" #include "KillSay.h" #include "UberSpam.hpp" -#include "SkinChanger.hpp" #include "Achievement.h" #include "Spam.h" #include "Noisemaker.h" #include "FollowBot.h" -#include "Radar.hpp" #endif /* HACKS_HACKLIST_H_ */ diff --git a/src/headshake.cpp b/src/headshake.cpp new file mode 100644 index 00000000..8c8f28cb --- /dev/null +++ b/src/headshake.cpp @@ -0,0 +1,12 @@ +/* + * headshake.cpp + * + * Created on: Aug 2, 2017 + * Author: nullifiedcat + */ + +#include + +const std::vector headshake_pitch_deltas = { + -0.2, 0.8, -1.7, 0.8, -0.8, 0.19, -0.99, 1.9 +}; diff --git a/src/headshake.hpp b/src/headshake.hpp new file mode 100644 index 00000000..6b61018d --- /dev/null +++ b/src/headshake.hpp @@ -0,0 +1,12 @@ +/* + * headshake.hpp + * + * Created on: Aug 2, 2017 + * Author: nullifiedcat + */ + +#pragma once + + + + diff --git a/src/helpers.cpp b/src/helpers.cpp index 9ff472b9..e9434758 100644 --- a/src/helpers.cpp +++ b/src/helpers.cpp @@ -10,71 +10,53 @@ #include "sdk.h" #include "profiler.h" -#include -#include #include -std::vector g_ConVars; -FILE* hConVarsFile = 0; -void BeginConVars() { - FILE *hAutoexec, *hMatchexec; +std::vector& RegisteredVarsList() { + static std::vector list {}; + return list; +} - hConVarsFile = fopen(strfmt("%scfg/cat_defaults.cfg", g_pszTFPath), "w"); - hAutoexec = fopen(strfmt("%scfg/cat_autoexec.cfg", g_pszTFPath), "r+"); - if (!hAutoexec) { - hAutoexec = fopen(strfmt("%scfg/cat_autoexec.cfg", g_pszTFPath), "w"); - if (hAutoexec) { - fprintf(hAutoexec, "// Put your custom cathook settings in this file\n// This script will be executed EACH TIME YOU INJECT CATHOOK\n"); - fclose(hAutoexec); +std::vector& RegisteredCommandsList() { + static std::vector list {}; + return list; +} + +void BeginConVars() { + logging::Info("Begin ConVars"); + if (!std::ifstream("tf/cfg/cat_autoexec.cfg")) { + std::ofstream cfg_autoexec("tf/cfg/cat_autoexec.cfg", std::ios::out | std::ios::trunc); + if (cfg_autoexec.good()) { + cfg_autoexec << "// Put your custom cathook settings in this file\n// This script will be executed EACH TIME YOU INJECT CATHOOK\n"; } - } else fclose(hAutoexec); - hMatchexec = fopen(strfmt("%scfg/cat_matchexec.cfg", g_pszTFPath), "r+"); - if (!hMatchexec) { - hMatchexec = fopen(strfmt("%scfg/cat_matchexec.cfg", g_pszTFPath), "w"); - if (hMatchexec) { - fprintf(hMatchexec, "// Put your custom cathook settings in this file\n// This script will be executed EACH TIME YOU JOIN A MATCH\n"); - fclose(hMatchexec); + } + if (!std::ifstream("tf/cfg/cat_autoexec.cfg")) { + std::ofstream cfg_autoexec("tf/cfg/cat_matchexec.cfg", std::ios::out | std::ios::trunc); + if (cfg_autoexec.good()) { + cfg_autoexec << "// Put your custom cathook settings in this file\n// This script will be executed EACH TIME YOU JOIN A MATCH\n"; } - } else fclose(hMatchexec); - if (hConVarsFile) fprintf(hConVarsFile, "// THIS FILE IS AUTO-GENERATED BY CATHOOK\n// DO NOT EDIT IT, ALL CHANGES WILL BE UNDONE!\n// If you want to change default settings, add changed convars to cat_autoexec.cfg\n"); + } + logging::Info(":b:"); SetCVarInterface(g_ICvar); } void EndConVars() { + logging::Info("Registering ConVars"); RegisterCatVars(); RegisterCatCommands(); - if (hConVarsFile) { - //fprintf(hConVarsFile, "\nexec cat_autoexec\n"); - fprintf(hConVarsFile, "cat_killsay_reload\ncat_spam_reload\n"); - fclose(hConVarsFile); - } ConVar_Register(); -} -// StackOverflow copypasta xddd -void ReplaceString(char* target, char* what, char* with_what) { - char buffer[1024] = { 0 }; - char *insert_point; - const char *tmp, *p; - size_t needle_len, repl_len; - buffer[0] = 0; - insert_point = &buffer[0]; - tmp = target; - needle_len = strlen(what); - repl_len = strlen(with_what); - while (1) { - p = strstr(tmp, what); - if (p == NULL) { - strcpy(insert_point, tmp); - break; + std::ofstream cfg_defaults("tf/cfg/cat_defaults.cfg", std::ios::out | std::ios::trunc); + if (cfg_defaults.good()) { + cfg_defaults << "// This file is auto-generated and will be overwritten each time you inject cathook\n// Do not make edits to this file\n\n// Every registered variable dump\n"; + for (const auto& i : RegisteredVarsList()) { + cfg_defaults << i->GetName() << " \"" << i->GetDefault() << "\"\n"; + } + cfg_defaults << "\n// Every registered command dump\n"; + for (const auto& i : RegisteredCommandsList()) { + cfg_defaults << "// " << i->GetName() << "\n"; } - memcpy(insert_point, tmp, p - tmp); - insert_point += p - tmp; - memcpy(insert_point, with_what, repl_len); - insert_point += repl_len; - tmp = p + needle_len; } - strcpy(target, buffer); } ConVar* CreateConVar(std::string name, std::string value, std::string help) { @@ -85,17 +67,51 @@ ConVar* CreateConVar(std::string name, std::string value, std::string help) { strncpy(valuec, value.c_str(), 255); strncpy(helpc, help.c_str(), 255); //logging::Info("Creating ConVar: %s %s %s", namec, valuec, helpc); - ConVar* ret = new ConVar((const char*)namec, (const char*)valuec, 0, (const char*)helpc); - if (hConVarsFile) - fprintf(hConVarsFile, "%s \"%s\"\n", name.c_str(), value.c_str()); + ConVar* ret = new ConVar(const_cast(namec), const_cast(valuec), 0, const_cast(helpc)); g_ICvar->RegisterConCommand(ret); - g_ConVars.push_back(ret); + RegisteredVarsList().push_back(ret); return ret; } +// Function for when you want to goto a vector +void WalkTo(const Vector& vector) { + if (CE_BAD(LOCAL_E)) return; + // Calculate how to get to a vector + auto result = ComputeMove(LOCAL_E->m_vecOrigin, vector); + // Push our move to usercmd + g_pUserCmd->forwardmove = result.first; + g_pUserCmd->sidemove = result.second; +} + + +std::string GetLevelName() { + + std::string name(g_IEngine->GetLevelName()); + size_t slash = name.find('/'); + if (slash == std::string::npos) slash = 0; + else slash++; + size_t bsp = name.find(".bsp"); + size_t length = (bsp == std::string::npos ? name.length() - slash : bsp - slash); + return name.substr(slash, length); +} + +std::pair ComputeMove(const Vector& a, const Vector& b) { + Vector diff = (b - a); + if (diff.Length() == 0) return { 0, 0 }; + const float x = diff.x; + const float y = diff.y; + Vector vsilent(x, y, 0); + float speed = sqrt(vsilent.x * vsilent.x + vsilent.y * vsilent.y); + Vector ang; + VectorAngles(vsilent, ang); + float yaw = DEG2RAD(ang.y - g_pUserCmd->viewangles.y); + return { cos(yaw) * 450, -sin(yaw) * 450 }; +} + ConCommand* CreateConCommand(const char* name, FnCommandCallback_t callback, const char* help) { ConCommand* ret = new ConCommand(name, callback, help); g_ICvar->RegisterConCommand(ret); + RegisteredCommandsList().push_back(ret); return ret; } @@ -107,40 +123,8 @@ const char* GetBuildingName(CachedEntity* ent) { return "[NULL]"; } -void format_internal(std::stringstream& stream) {} - -std::string WordWrap(std::string& in, int max, unsigned long font) { - std::stringstream result, line, wordstream, next; - std::string word; - char ch; - for (int i = 0; i < in.size(); i++) { - ch = in.at(i); - if (ch == ' ' || ch == '\n') { - word = wordstream.str(); - //logging::Info("got word: '%s'", word.c_str()); - wordstream.str(""); - auto size = draw::GetStringLength(font, line.str() + word); - if (size.first >= max) { - //logging::Info("wrapping: '%s'", line.str().c_str()); - result << line.str() << '\n'; - line.str(""); - } - line << word << ch; - } else { - wordstream << ch; - } - } - word = wordstream.str(); - wordstream.str(""); - auto size = draw::GetStringLength(fonts::MENU, line.str() + word); - if (size.first >= max) { - result << line.str() << '\n'; - line.str(word); - } else { - line << word; - } - result << line.str(); - return result.str(); +void format_internal(std::stringstream& stream) { + (void)(stream); } void ReplaceString(std::string& input, const std::string& what, const std::string& with_what) { @@ -154,7 +138,7 @@ void ReplaceString(std::string& input, const std::string& what, const std::strin powerup_type GetPowerupOnPlayer(CachedEntity* player) { if (CE_BAD(player)) return powerup_type::not_powerup; - if (!HasCondition(player)) return powerup_type::not_powerup; +// if (!HasCondition(player)) return powerup_type::not_powerup; if (HasCondition(player)) return powerup_type::strength; if (HasCondition(player)) return powerup_type::haste; if (HasCondition(player)) return powerup_type::regeneration; @@ -170,14 +154,31 @@ powerup_type GetPowerupOnPlayer(CachedEntity* player) { return powerup_type::not_powerup; } -bool HasDarwins(CachedEntity* ent) { +// A function to tell if a player is using a specific weapon +bool HasWeapon(CachedEntity* ent, int wantedId) { + if (CE_BAD(ent)) return false; + // Create a var to store the handle int *hWeapons; - if (CE_INT(ent, netvar.iClass) != tf_sniper) return false; + // Grab the handle and store it into the var hWeapons = (int*)((unsigned)(RAW_ENT(ent) + netvar.hMyWeapons)); - for (int i = 0; i < 4; i++) { + // Go through the handle array and search for the item + for (int i = 0; hWeapons[i]; i++) { + // Get the weapon id from the handle array IClientEntity* weapon = g_IEntityList->GetClientEntityFromHandle(hWeapons[i]); - if (weapon && NET_INT(weapon, netvar.iItemDefinitionIndex) == 231) return true; + // if weapon is what we are looking for, return true + if (weapon && NET_INT(weapon, netvar.iItemDefinitionIndex) == wantedId) return true; } + // We didnt find the weapon we needed, return false + return false; +} + +bool HasDarwins(CachedEntity* ent) { + if (CE_BAD(ent)) return false; + // Check if player is sniper + if (CE_INT(ent, netvar.iClass) != tf_sniper) return false; + // Check if player is using darwins, 231 is the id for darwins danger sheild + if (HasWeapon(ent, 231)) return true; + // Else return false return false; } @@ -188,7 +189,7 @@ void VectorTransform (const float *in1, const matrix3x4_t& in2, float *out) { } bool GetHitbox(CachedEntity* entity, int hb, Vector& out) { - CachedHitbox *box; + hitbox_cache::CachedHitbox *box; if (CE_BAD(entity)) return false; box = entity->hitboxes.GetHitbox(hb); @@ -351,6 +352,48 @@ bool IsEntityVectorVisible(CachedEntity* entity, Vector endpos) { return (trace_object.fraction >= 0.99f || (((IClientEntity*)trace_object.m_pEnt)) == RAW_ENT(entity)); } +// For when you need to vis check something that isnt the local player +bool VisCheckEntFromEnt(CachedEntity* startEnt, CachedEntity* endEnt) { + // We setSelf as the starting ent as we dont want to hit it, we want the other ent + trace_t trace; + trace::filter_default.SetSelf(RAW_ENT(startEnt)); + + // Setup the trace starting with the origin of the starting ent attemting to hit the origin of the end ent + Ray_t ray; + ray.Init(startEnt->m_vecOrigin, endEnt->m_vecOrigin); + { + PROF_SECTION(IEVV_TraceRay); + g_ITrace->TraceRay(ray, MASK_SHOT_HULL, &trace::filter_default, &trace); + } + // Is the entity that we hit our target ent? if so, the vis check passes + if (trace.m_pEnt) { + if ((((IClientEntity*)trace.m_pEnt)) == RAW_ENT(endEnt)) return true; + } + // Since we didnt hit our target ent, the vis check failed so return false + return false; +} + +// Use when you need to vis check something but its not the ent origin that you use, so we check from the vector to the ent, ignoring the first just in case +bool VisCheckEntFromEntVector(Vector startVector, CachedEntity* startEnt, CachedEntity* endEnt) { + // We setSelf as the starting ent as we dont want to hit it, we want the other ent + trace_t trace; + trace::filter_default.SetSelf(RAW_ENT(startEnt)); + + // Setup the trace starting with the origin of the starting ent attemting to hit the origin of the end ent + Ray_t ray; + ray.Init(startVector, endEnt->m_vecOrigin); + { + PROF_SECTION(IEVV_TraceRay); + g_ITrace->TraceRay(ray, MASK_SHOT_HULL, &trace::filter_default, &trace); + } + // Is the entity that we hit our target ent? if so, the vis check passes + if (trace.m_pEnt) { + if ((((IClientEntity*)trace.m_pEnt)) == RAW_ENT(endEnt)) return true; + } + // Since we didnt hit our target ent, the vis check failed so return false + return false; +} + Vector GetBuildingPosition(CachedEntity* ent) { Vector res; res = ent->m_vecOrigin; @@ -439,7 +482,10 @@ weaponmode GetWeaponMode() { weapon->m_iClassID == CL_CLASS(CTFBat_Giftwrap) || weapon->m_iClassID == CL_CLASS(CTFFlareGun) || weapon->m_iClassID == CL_CLASS(CTFFlareGun_Revenge) || - weapon->m_iClassID == CL_CLASS(CTFSyringeGun)) { + weapon->m_iClassID == CL_CLASS(CTFSyringeGun) || + weapon->m_iClassID == CL_CLASS(CTFCrossbow) || + weapon->m_iClassID == CL_CLASS(CTFShotgunBuildingRescue) || + weapon->m_iClassID == CL_CLASS(CTFDRGPomson)) { return weaponmode::weapon_projectile; } else if (weapon->m_iClassID == CL_CLASS(CTFJar) || weapon->m_iClassID == CL_CLASS(CTFJarMilk)) { @@ -460,6 +506,7 @@ bool LineIntersectsBox(Vector& bmin, Vector& bmax, Vector& lmin, Vector& lmax) { return true; } +// TODO add bison and grapple hook // TODO FIX this function bool GetProjectileData(CachedEntity* weapon, float& speed, float& gravity) { float rspeed, rgrav; @@ -496,13 +543,21 @@ bool GetProjectileData(CachedEntity* weapon, float& speed, float& gravity) { } else if (weapon->m_iClassID == CL_CLASS(CTFSyringeGun)) { rgrav = 0.2f; rspeed = 990.0f; + } else if (weapon->m_iClassID == CL_CLASS(CTFCrossbow)) { + rgrav = 0.2f; + rspeed = 2400.0f; + } else if (weapon->m_iClassID == CL_CLASS(CTFShotgunBuildingRescue)) { + rgrav = 0.2f; + rspeed = 2400.0f; + } else if (weapon->m_iClassID == CL_CLASS(CTFDRGPomson)) { + rspeed = 1200.0f; } speed = rspeed; gravity = rgrav; return (rspeed || rgrav); } -constexpr unsigned developer_list[] = { 306902159, 347272825, 401679596 }; +constexpr unsigned developer_list[] = { 306902159, 347272825, 401679596, 416491033, 175278337 }; bool Developer(CachedEntity* ent) { for (int i = 0; i < sizeof(developer_list) / sizeof(unsigned); i++) { @@ -703,136 +758,45 @@ bool IsEntityVisiblePenetration(CachedEntity* entity, int hb) { return false; } -void RunEnginePrediction(IClientEntity* ent, CUserCmd *ucmd) { - if (!ent) return; - - typedef void(*SetupMoveFn)(IPrediction*, IClientEntity *, CUserCmd *, class IMoveHelper *, CMoveData *); - typedef void(*FinishMoveFn)(IPrediction*, IClientEntity *, CUserCmd*, CMoveData*); - - void **predictionVtable = *((void ***)g_IPrediction); - SetupMoveFn oSetupMove = (SetupMoveFn)(*(unsigned*)(predictionVtable + 19)); - FinishMoveFn oFinishMove = (FinishMoveFn)(*(unsigned*)(predictionVtable + 20)); - - CMoveData *pMoveData = (CMoveData*)(sharedobj::client->lmap->l_addr + 0x1F69C0C); - - float frameTime = g_GlobalVars->frametime; - float curTime = g_GlobalVars->curtime; - - CUserCmd defaultCmd; - if(ucmd == NULL) { - ucmd = &defaultCmd; - } - - NET_VAR(ent, 4188, CUserCmd*) = ucmd; - - g_GlobalVars->curtime = g_GlobalVars->interval_per_tick * NET_INT(ent, netvar.nTickBase); - g_GlobalVars->frametime = g_GlobalVars->interval_per_tick; - - *g_PredictionRandomSeed = MD5_PseudoRandom(g_pUserCmd->command_number) & 0x7FFFFFFF; - g_IGameMovement->StartTrackPredictionErrors(reinterpret_cast(ent)); - oSetupMove(g_IPrediction, ent, ucmd, NULL, pMoveData); - g_IGameMovement->ProcessMovement(reinterpret_cast(ent), pMoveData); - oFinishMove(g_IPrediction, ent, ucmd, pMoveData); - g_IGameMovement->FinishTrackPredictionErrors(reinterpret_cast(ent)); - - NET_VAR(ent, 4188, CUserCmd*) = nullptr; - - g_GlobalVars->frametime = frameTime; - g_GlobalVars->curtime = curTime; - - return; -} - - -class CMoveData; - -/*void RunEnginePrediction(IClientEntity* ent, CUserCmd *ucmd) { - // we are going to require some helper functions for this to work - // notably SetupMove, FinishMove and ProcessMovement - - - // setup the types of the functions - typedef void(*SetupMoveFn)(IClientEntity *, CUserCmd *, class IMoveHelper *, CMoveData *); - typedef void(*FinishMoveFn)(IClientEntity *, CUserCmd*, CMoveData*); - typedef void(*ProcessMovementFn)(IClientEntity *, CMoveData *); - typedef void(*StartTrackPredictionErrorsFn)(IClientEntity *); - typedef void(*FinishTrackPredictionErrorsFn)(IClientEntity *); - - // get the vtable - void **predictionVtable = *(void ***)prediction; - logging::Info("predictionVtable 0x%08x", predictionVtable); - // get the functions - SetupMoveFn oSetupMove = (SetupMoveFn) predictionVtable[19]; - FinishMoveFn oFinishMove = (FinishMoveFn) predictionVtable[20]; - - // get the vtable - void **gameMovementVtable = *(void ***)gamemovement; - logging::Info("gameMovementVtable 0x%08x", gameMovementVtable); - // get the functions - ProcessMovementFn oProcessMovement = (ProcessMovementFn) gameMovementVtable[2]; - StartTrackPredictionErrorsFn oStartTrackPredictionErrors = (StartTrackPredictionErrorsFn) gameMovementVtable[3]; - FinishTrackPredictionErrorsFn oFinishTrackPredictionErrors = (FinishTrackPredictionErrorsFn) gameMovementVtable[4]; - - // use this as movedata (should be big enough - otherwise the stack will die!) - unsigned char moveData[2048]; - CMoveData *pMoveData = (CMoveData *)&(moveData[0]); - logging::Info("pMoveData 0x%08x", pMoveData); - - // back up globals - float frameTime = gvars->frametime; - float curTime = gvars->curtime; - - CUserCmd defaultCmd; - if(ucmd == NULL) - { - ucmd = &defaultCmd; +// Used for getting class names +CatCommand print_classnames("debug_print_classnames", "Lists classnames currently available in console", []() { + + // Create a tmp ent for the loop + CachedEntity* ent; + + // Go through all the entities + for (int i = 0; i < HIGHEST_ENTITY; i++) { + + // Get an entity + ent = ENTITY(i); + // Check for null/dormant + if (CE_BAD(ent)) continue; + + // Print in console, the class name of the ent + logging::Info(format(RAW_ENT(ent)->GetClientClass()->m_pNetworkName).c_str()); } - // set the current command - NET_VAR(ent, 0x105C, void*) = ucmd; - - // set up the globals - gvars->curtime = gvars->interval_per_tick * NET_INT(ent, netvar.nTickBase); - gvars->frametime = gvars->interval_per_tick; - - oStartTrackPredictionErrors(ent); - - logging::Info("StartTrackPredictionErrors(ent)"); - oSetupMove(ent, ucmd, NULL, pMoveData); - logging::Info("oSetupMove"); - oProcessMovement(ent, pMoveData); - logging::Info("oProcessMovement"); - oFinishMove(ent, ucmd, pMoveData); - logging::Info("oFinishMove"); - - oFinishTrackPredictionErrors(ent); - logging::Info("oFinishTrackPredictionErrors"); - // reset the current command - NET_VAR(ent, 0x105C, void *) = 0; - - // restore globals - gvars->frametime = frameTime; - gvars->curtime = curTime; +}); +void PrintChat(const char* fmt, ...) { +#if TEXTMODE return; +#endif + CHudBaseChat* chat = (CHudBaseChat*)g_CHUD->FindElement("CHudChat"); + if (chat) { + char* buf = new char[1024]; + va_list list; + va_start(list, fmt); + vsprintf(buf, fmt, list); + va_end(list); + std::unique_ptr str(strfmt("\x07%06X[\x07%06XCAT\x07%06X]\x01 %s", 0x5e3252, 0xba3d9a, 0x5e3252, buf)); + // FIXME DEBUG LOG + logging::Info("%s", str.get()); + chat->Printf(str.get()); + } else { + } } -float oldCurtime; -float oldFrametime; - -void StartPrediction(CUserCmd* cmd) { - oldCurtime = gvars->curtime; - oldFrametime = gvars->frametime; - gvars->curtime = NET_INT(g_pLocalPlayer->entity, netvar.nTickBase) * gvars->interval_per_tick; - gvars->frametime = gvars->interval_per_tick; - //gamemovement-> -} - -void EndPrediction() { - gvars->curtime = oldCurtime; - gvars->frametime = oldFrametime; -}*/ - // You are responsible for delete[]'ing the resulting string. char* strfmt(const char* fmt, ...) { diff --git a/src/helpers.h b/src/helpers.h index 7a9221d2..81bddce3 100644 --- a/src/helpers.h +++ b/src/helpers.h @@ -41,8 +41,9 @@ void SetCVarInterface(ICvar* iface); // TODO split this shit -extern std::vector g_ConVars; -extern FILE* hConVarsFile; +std::vector& RegisteredVarsList(); +std::vector& RegisteredCommandsList(); + void BeginConVars(); void EndConVars(); @@ -72,32 +73,45 @@ void VectorAngles(Vector &forward, Vector &angles); bool IsEntityVisible(CachedEntity* entity, int hb); bool IsEntityVectorVisible(CachedEntity* entity, Vector endpos); - +bool VisCheckEntFromEnt(CachedEntity* startEnt, CachedEntity* endEnt); +bool VisCheckEntFromEntVector(Vector startVector, CachedEntity* startEnt, CachedEntity* endEnt); + bool LineIntersectsBox(Vector& bmin, Vector& bmax, Vector& lmin, Vector& lmax); float DistToSqr(CachedEntity* entity); void fClampAngle(Vector& qaAng); -void VectorAngles(Vector &forward, Vector &angles); //const char* MakeInfoString(IClientEntity* player); bool GetProjectileData(CachedEntity* weapon, float& speed, float& gravity); bool IsVectorVisible(Vector a, Vector b); bool IsSentryBuster(CachedEntity* ent); char* strfmt(const char* fmt, ...); -void ReplaceString(char* target, char* what, char* with_what); // TODO move that to weaponid.h +bool HasWeapon(CachedEntity* ent, int wantedId); bool IsAmbassador(CachedEntity* ent); bool HasDarwins(CachedEntity* ent); bool AmbassadorCanHeadshot(); +inline const char* teamname(int team) { + if (team == 2) return "RED"; + else if (team == 3) return "BLU"; + return "SPEC"; +} +extern const std::string classes[10]; +inline const char* classname(int clazz) { + if (clazz > 0 && clazz < 10) { + return classes[clazz - 1].c_str(); + } + return "Unknown"; +} + +void PrintChat(const char* fmt, ...); + void WhatIAmLookingAt(int* result_eindex, Vector* result_pos); void Patch(void* address, void* patch, size_t length); void AimAt(Vector origin, Vector target, CUserCmd* cmd); void AimAtHitbox(CachedEntity* ent, int hitbox, CUserCmd* cmd); - -std::string WordWrap(std::string& in, int max, unsigned long font); - bool IsProjectileCrit(CachedEntity* ent); QAngle VectorToQAngle(Vector in); @@ -111,8 +125,6 @@ char GetChar(ButtonCode_t button); bool IsEntityVisiblePenetration(CachedEntity* entity, int hb); -void RunEnginePrediction(IClientEntity* ent, CUserCmd *ucmd); - //void RunEnginePrediction(IClientEntity* ent, CUserCmd *ucmd = NULL); //void StartPrediction(CUserCmd* cmd); //void EndPrediction(); @@ -127,6 +139,11 @@ float GetFov(Vector ang, Vector src, Vector dst); void ReplaceString(std::string& input, const std::string& what, const std::string& with_what); +std::pair ComputeMove(const Vector& a, const Vector& b); +void WalkTo(const Vector& vector); + +std::string GetLevelName(); + void format_internal(std::stringstream& stream); template void format_internal(std::stringstream& stream, T value, Targs... args) { diff --git a/src/hooks.cpp b/src/hooks.cpp index 6ee8013f..3e86ca27 100644 --- a/src/hooks.cpp +++ b/src/hooks.cpp @@ -41,6 +41,7 @@ void VMTHook::Set(ptr_t inst, uint32_t offset) { vtable_ptr = &GetVMT(inst, offset); vtable_original = *vtable_ptr; int mc = CountMethods(vtable_original); + logging::Info("Hooking vtable 0x%08x with %d methods", vtable_original ,mc); vtable_hooked = static_cast(calloc(mc + 3, sizeof(ptr_t))); memcpy(&vtable_hooked[2], vtable_original, sizeof(ptr_t) * mc); vtable_hooked[0] = this; @@ -65,6 +66,7 @@ void* VMTHook::GetMethod(uint32_t idx) const { } void VMTHook::HookMethod(ptr_t func, uint32_t idx) { + logging::Info("Hooking method %d of vtable 0x%08x, replacing 0x%08x", idx, vtable_original, GetMethod(idx)); vtable_hooked[2 + idx] = func; } @@ -84,5 +86,7 @@ VMTHook clientdll {}; VMTHook matsurface {}; VMTHook studiorender {}; VMTHook modelrender {}; +VMTHook clientmode4 {}; +VMTHook materialsystem {}; } diff --git a/src/hooks.h b/src/hooks.h index 74af6205..a2f47388 100644 --- a/src/hooks.h +++ b/src/hooks.h @@ -48,6 +48,7 @@ public: extern VMTHook panel; extern VMTHook clientmode; +extern VMTHook clientmode4; extern VMTHook client; extern VMTHook netchannel; extern VMTHook clientdll; @@ -58,6 +59,7 @@ extern VMTHook modelrender; extern VMTHook baseclientstate; extern VMTHook baseclientstate8; extern VMTHook steamfriends; +extern VMTHook materialsystem; } diff --git a/src/hooks/CreateMove.cpp b/src/hooks/CreateMove.cpp index 2ceda364..15e420af 100644 --- a/src/hooks/CreateMove.cpp +++ b/src/hooks/CreateMove.cpp @@ -11,25 +11,7 @@ #include "../hack.h" #include "../common.h" #include "hookedmethods.h" - -// FIXME remove this temporary code already! -float AngleDiff( float destAngle, float srcAngle ) -{ - float delta; - - delta = fmodf(destAngle - srcAngle, 360.0f); - if ( destAngle > srcAngle ) - { - if ( delta >= 180 ) - delta -= 360; - } - else - { - if ( delta <= -180 ) - delta += 360; - } - return delta; -} +#include #include "../profiler.h" @@ -38,18 +20,71 @@ static CatVar minigun_jump(CV_SWITCH, "minigun_jump", "0", "TF2C minigun jump", CatVar jointeam(CV_SWITCH, "fb_autoteam", "1", "Joins player team automatically (NYI)"); CatVar joinclass(CV_STRING, "fb_autoclass", "spy", "Class that will be picked after joining a team (NYI)"); +CatVar nolerp(CV_SWITCH, "nolerp", "0", "NoLerp mode (experimental)"); + +class CMoveData; namespace engine_prediction { -float o_curtime; + +void RunEnginePrediction(IClientEntity* ent, CUserCmd *ucmd) { + if (!ent) return; + + typedef void(*SetupMoveFn)(IPrediction*, IClientEntity *, CUserCmd *, class IMoveHelper *, CMoveData *); + typedef void(*FinishMoveFn)(IPrediction*, IClientEntity *, CUserCmd*, CMoveData*); + + void **predictionVtable = *((void ***)g_IPrediction); + SetupMoveFn oSetupMove = (SetupMoveFn)(*(unsigned*)(predictionVtable + 19)); + FinishMoveFn oFinishMove = (FinishMoveFn)(*(unsigned*)(predictionVtable + 20)); + + //CMoveData *pMoveData = (CMoveData*)(sharedobj::client->lmap->l_addr + 0x1F69C0C); + //CMoveData movedata {}; + char* object = new char[165]; + CMoveData *pMoveData = (CMoveData*)object; + + float frameTime = g_GlobalVars->frametime; + float curTime = g_GlobalVars->curtime; + + CUserCmd defaultCmd; + if(ucmd == NULL) { + ucmd = &defaultCmd; + } + + NET_VAR(ent, 4188, CUserCmd*) = ucmd; + + g_GlobalVars->curtime = g_GlobalVars->interval_per_tick * NET_INT(ent, netvar.nTickBase); + g_GlobalVars->frametime = g_GlobalVars->interval_per_tick; + + *g_PredictionRandomSeed = MD5_PseudoRandom(g_pUserCmd->command_number) & 0x7FFFFFFF; + g_IGameMovement->StartTrackPredictionErrors(reinterpret_cast(ent)); + oSetupMove(g_IPrediction, ent, ucmd, NULL, pMoveData); + g_IGameMovement->ProcessMovement(reinterpret_cast(ent), pMoveData); + oFinishMove(g_IPrediction, ent, ucmd, pMoveData); + g_IGameMovement->FinishTrackPredictionErrors(reinterpret_cast(ent)); + + delete[] object; + + NET_VAR(ent, 4188, CUserCmd*) = nullptr; + + g_GlobalVars->frametime = frameTime; + g_GlobalVars->curtime = curTime; + + return; +} + +/*float o_curtime; float o_frametime; void Start() { + g_IGameMovement->StartTrackPredictionErrors((CBasePlayer*)(RAW_ENT(LOCAL_E))); + + IClientEntity* player = RAW_ENT(LOCAL_E); + // CPredictableId::ResetInstanceCounters(); + *(reinterpret_cast(reinterpret_cast(player) + 1047)) = g_pUserCmd; o_curtime = g_GlobalVars->curtime; o_frametime = g_GlobalVars->frametime; *g_PredictionRandomSeed = MD5_PseudoRandom(g_pUserCmd->command_number) & 0x7FFFFFFF; g_GlobalVars->curtime = CE_INT(LOCAL_E, netvar.nTickBase) * g_GlobalVars->interval_per_tick; g_GlobalVars->frametime = g_GlobalVars->interval_per_tick; - g_IGameMovement->StartTrackPredictionErrors((CBasePlayer*)(RAW_ENT(LOCAL_E))); CMoveData data; @@ -59,10 +94,15 @@ void End() { *g_PredictionRandomSeed = -1; g_GlobalVars->curtime = o_curtime; g_GlobalVars->frametime = o_frametime; -} +}*/ } +static CatVar engine_pred(CV_SWITCH, "engine_prediction", "0", "Engine Prediction"); +static CatVar debug_projectiles(CV_SWITCH, "debug_projectiles", "0", "Debug Projectiles"); + +static CatVar fakelag_amount(CV_INT, "fakelag", "0", "Bad Fakelag"); + bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { static CreateMove_t original_method = (CreateMove_t)hooks::clientmode.GetMethod(offsets::CreateMove()); bool time_replaced, ret, speedapplied; @@ -104,10 +144,13 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { ch = (INetChannel*)g_IEngine->GetNetChannelInfo(); if (ch && !hooks::IsHooked((void*)ch)) { hooks::netchannel.Set(ch); - //hooks::netchannel.HookMethod((void*)CanPacket_hook, offsets::CanPacket()); + hooks::netchannel.HookMethod((void*)CanPacket_hook, offsets::CanPacket()); hooks::netchannel.HookMethod((void*)SendNetMsg_hook, offsets::SendNetMsg()); hooks::netchannel.HookMethod((void*)Shutdown_hook, offsets::Shutdown()); hooks::netchannel.Apply(); +#if IPC_ENABLED + ipc::UpdateServerAddress(); +#endif } /**bSendPackets = true; @@ -123,6 +166,21 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { time_replaced = false; curtime_old = g_GlobalVars->curtime; + if (nolerp) { + g_pUserCmd->tick_count += 1; + if (sv_client_min_interp_ratio->GetInt() != -1) { + //sv_client_min_interp_ratio->m_nFlags = 0; + sv_client_min_interp_ratio->SetValue(-1); + } + if (cl_interp->m_fValue != 0) { + cl_interp->SetValue(0); + cl_interp->m_fValue = 0.0f; + cl_interp->m_nValue = 0; + } + if (cl_interp_ratio->GetInt() != 0) cl_interp_ratio->SetValue(0); + if (cl_interpolate->GetInt() != 0) cl_interpolate->SetValue(0); + } + if (!g_Settings.bInvalid && CE_GOOD(g_pLocalPlayer->entity)) { servertime = (float)CE_INT(g_pLocalPlayer->entity, netvar.nTickBase) * g_GlobalVars->interval_per_tick; g_GlobalVars->curtime = servertime; @@ -131,6 +189,9 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { if (g_Settings.bInvalid) { entity_cache::Invalidate(); } + + // Disabled because this causes EXTREME aimbot inaccuracy + //if (!cmd->command_number) return ret; // PROF_BEGIN(); { PROF_SECTION(EntityCache); @@ -146,8 +207,9 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { SAFE_CALL(g_pLocalPlayer->Update()); } g_Settings.bInvalid = false; - // Disabled because this causes EXTREME aimbot inaccuracy - //if (!cmd->command_number) return ret; + + hacks::shared::autojoin::Update(); + #ifdef IPC_ENABLED static int team_joining_state = 0; static float last_jointeam_try = 0; @@ -205,12 +267,22 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { IF_GAME (IsTF2()) { SAFE_CALL(UpdateHoovyList()); } - g_pLocalPlayer->v_OrigViewangles = cmd->viewangles; + g_pLocalPlayer->v_OrigViewangles = cmd->viewangles; +#ifndef TEXTMODE { PROF_SECTION(CM_esp); SAFE_CALL(hacks::shared::esp::CreateMove()); } +#endif if (!g_pLocalPlayer->life_state && CE_GOOD(g_pLocalPlayer->weapon())) { + { + PROF_SECTION(CM_walkbot); + SAFE_CALL(hacks::shared::walkbot::Move()); + } + // Walkbot can leave game. + if (!g_IEngine->IsInGame()) { + return ret; + } IF_GAME (IsTF()) { PROF_SECTION(CM_uberspam); SAFE_CALL(hacks::tf::uberspam::CreateMove()); @@ -227,6 +299,7 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { PROF_SECTION(CM_bunnyhop); SAFE_CALL(hacks::shared::bunnyhop::CreateMove()); } + if (engine_pred) engine_prediction::RunEnginePrediction(RAW_ENT(LOCAL_E), g_pUserCmd); { PROF_SECTION(CM_aimbot); SAFE_CALL(hacks::shared::aimbot::CreateMove()); @@ -255,6 +328,9 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { PROF_SECTION(CM_autobackstab); SAFE_CALL(hacks::tf2::autobackstab::CreateMove()); } + if (debug_projectiles) + projectile_logging::Update(); + Prediction_CreateMove(); } { PROF_SECTION(CM_misc); @@ -271,6 +347,10 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { PROF_SECTION(CM_chat_stack); chat_stack::OnCreateMove(); } + { + PROF_SECTION(CM_healarrow); + hacks::tf2::healarrow::CreateMove(); + } { PROF_SECTION(CM_lagexploit); hacks::shared::lagexploit::CreateMove(); @@ -278,15 +358,31 @@ bool CreateMove_hook(void* thisptr, float inputSample, CUserCmd* cmd) { // TODO Auto Steam Friend - if (g_GlobalVars->framecount % 1000 == 0) { +#if IPC_ENABLED + { PROF_SECTION(CM_playerlist); - playerlist::DoNotKillMe(); -#ifdef IPC_ENABLED - ipc::UpdatePlayerlist(); -#endif + static Timer ipc_update_timer {}; + // playerlist::DoNotKillMe(); + if (ipc_update_timer.test_and_set(1000 * 10)) { + ipc::UpdatePlayerlist(); + } } +#endif + + *bSendPackets = true; if (CE_GOOD(g_pLocalPlayer->entity)) { + static int fakelag_queue = 0; + if (fakelag_amount) { + if (fakelag_queue == int(fakelag_amount) || (g_pUserCmd->buttons & IN_ATTACK)) { + *bSendPackets = true; + } else if (fakelag_queue < int(fakelag_amount)) { + *bSendPackets = false; + } else { + fakelag_queue = 0; + } + fakelag_queue++; + } speedapplied = false; if (roll_speedhack && g_IInputSystem->IsButtonDown((ButtonCode_t)((int)roll_speedhack)) && !(cmd->buttons & IN_ATTACK)) { speed = cmd->forwardmove; diff --git a/src/hooks/PaintTraverse.cpp b/src/hooks/PaintTraverse.cpp index d1763477..f703f7df 100644 --- a/src/hooks/PaintTraverse.cpp +++ b/src/hooks/PaintTraverse.cpp @@ -14,14 +14,9 @@ #include "../profiler.h" #include "../netmessage.h" -#if NOGUI != 1 -#include "../gui/GUI.h" -#endif - CatVar clean_screenshots(CV_SWITCH, "clean_screenshots", "1", "Clean screenshots", "Don't draw visuals while taking a screenshot"); CatVar disable_visuals(CV_SWITCH, "no_visuals", "0", "Disable ALL drawing", "Completely hides cathook"); CatVar no_zoom(CV_SWITCH, "no_zoom", "0", "Disable scope", "Disables black scope overlay"); -CatVar info_text(CV_SWITCH, "info", "1", "Show info", "Show cathook version in top left corner"); CatVar pure_bypass(CV_SWITCH, "pure_bypass", "0", "Pure Bypass", "Bypass sv_pure"); void* pure_orig = nullptr; void** pure_addr = nullptr; @@ -46,10 +41,12 @@ void PaintTraverse_hook(void* _this, unsigned int vp, bool fr, bool ar) { if (!segvcatch::handler_segv) segvcatch::init_fpe(); } #endif +#ifndef TEXTMODE if (!textures_loaded) { textures_loaded = true; hacks::tf::radar::Init(); } +#endif if (pure_bypass) { if (!pure_addr) { pure_addr = *reinterpret_cast(gSignatures.GetEngineSignature("55 89 E5 83 EC 18 A1 ? ? ? ? 89 04 24 E8 0D FF FF FF A1 ? ? ? ? 85 C0 74 08 89 04 24 E8 ? ? ? ? C9 C3") + 7); @@ -73,7 +70,7 @@ void PaintTraverse_hook(void* _this, unsigned int vp, bool fr, bool ar) { case 2: if (software_cursor->GetBool()) software_cursor->SetValue(0); break; -#if NOGUI != 1 +#if ENABLE_GUI case 3: if (cur != g_pGUI->Visible()) { software_cursor->SetValue(g_pGUI->Visible()); @@ -92,6 +89,7 @@ void PaintTraverse_hook(void* _this, unsigned int vp, bool fr, bool ar) { PROF_SECTION(PT_total); + if (vp == panel_top) draw_flag = true; if (!cathook) return; @@ -122,94 +120,29 @@ void PaintTraverse_hook(void* _this, unsigned int vp, bool fr, bool ar) { g_Settings.bInvalid = true; } - ResetStrings(); - if (vp != panel_focus) return; g_IPanel->SetTopmostPopup(panel_focus, true); if (!draw_flag) return; draw_flag = false; - if (!hack::command_stack().empty()) { - PROF_SECTION(PT_command_stack); - std::lock_guard guard(hack::command_stack_mutex); - while (!hack::command_stack().empty()) { - logging::Info("executing %s", hack::command_stack().top().c_str()); - g_IEngine->ClientCmd_Unrestricted(hack::command_stack().top().c_str()); - hack::command_stack().pop(); - } - } - if (disable_visuals) return; if (clean_screenshots && g_IEngine->IsTakingScreenshot()) return; PROF_SECTION(PT_active); - - if (info_text) { - PROF_SECTION(PT_info_text); - AddSideString("cathook by nullifiedcat", colors::RainbowCurrent()); - AddSideString(hack::GetVersion(), GUIColor()); -#if NOGUI != 1 - AddSideString("Press 'INSERT' or 'F11' key to open/close cheat menu.", GUIColor()); - AddSideString("Use mouse to navigate in menu.", GUIColor()); -#endif - if (!g_IEngine->IsInGame() -#if NOGUI != 1 - || g_pGUI->Visible() -#endif - ) { - name_s = force_name.GetString(); - if (name_s.length() < 3) name = "*Not Set*"; - AddSideString(""); // foolish - name_stripped = name_s ; - ReplaceString(name_stripped, "\n", "\\n"); - reason_stripped = disconnect_reason.GetString(); - ReplaceString(reason_stripped, "\n", "\\n"); - AddSideString(format("Custom Name: ", name_stripped), GUIColor()); - AddSideString(format("Custom Disconnect Reason: ", (reason_stripped.length() > 3 ? reason_stripped : "*Not Set*")), GUIColor()); - } - } - - if (CE_GOOD(g_pLocalPlayer->entity) && !g_Settings.bInvalid) { - PROF_SECTION(PT_total_hacks); - IF_GAME(IsTF()) { - PROF_SECTION(PT_antidisguise); - SAFE_CALL(hacks::tf2::antidisguise::Draw()); - } - { - PROF_SECTION(PT_misc); - SAFE_CALL(hacks::shared::misc::Draw()); - } - { - PROF_SECTION(PT_esp); - SAFE_CALL(hacks::shared::esp::Draw()); - } - IF_GAME(IsTF()) { - PROF_SECTION(PT_spyalert); - SAFE_CALL(hacks::tf::spyalert::Draw()); - } - IF_GAME(IsTF()) { - PROF_SECTION(PT_radar); - SAFE_CALL(hacks::tf::radar::Draw()); - } - IF_GAME(IsTF2()) { - PROF_SECTION(PT_skinchanger); - SAFE_CALL(hacks::tf2::skinchanger::PaintTraverse()); - } - { - SAFE_CALL(hacks::shared::aimbot::PaintTraverse()); - } - } +#ifndef TEXTMODE + draw::UpdateWTS(); + BeginCheatVisuals(); + DrawCheatVisuals(); -#if NOGUI != 1 +#if ENABLE_GUI g_pGUI->Update(); #endif - { - PROF_SECTION(PT_draw_strings); - DrawStrings(); - } + + EndCheatVisuals(); +#endif SEGV_END; } diff --git a/src/hooks/PaintTraverse.h b/src/hooks/PaintTraverse.h index 2c463d4a..ad70f2b0 100644 --- a/src/hooks/PaintTraverse.h +++ b/src/hooks/PaintTraverse.h @@ -12,6 +12,7 @@ class CatVar; extern CatVar no_zoom; extern CatVar clean_screenshots; +extern CatVar disable_visuals; void PaintTraverse_hook(void*, unsigned int, bool, bool); #endif /* PAINTTRAVERSE_H_ */ diff --git a/src/hooks/hookedmethods.h b/src/hooks/hookedmethods.h index 85436c8b..184e704d 100644 --- a/src/hooks/hookedmethods.h +++ b/src/hooks/hookedmethods.h @@ -36,9 +36,25 @@ bool ProcessGetCvarValue_hook(CBaseClientState* _this, SVC_GetCvarValue* msg); typedef const char*(*GetFriendPersonaName_t)(ISteamFriends*, CSteamID); const char* GetFriendPersonaName_hook(ISteamFriends* _this, CSteamID steamID); +typedef void(*FireGameEvent_t)(void* _this, IGameEvent* event); +void FireGameEvent_hook(void* _this, IGameEvent* event); + CUserCmd* GetUserCmd_hook(IInput*, int); void DrawModelExecute_hook(IVModelRender* _this, const DrawModelState_t& state, const ModelRenderInfo_t& info, matrix3x4_t* matrix); +/* SDL HOOKS */ +union SDL_Event; +class SDL_Window; + +typedef int(*SDL_PollEvent_t)(SDL_Event* event); +typedef void(*SDL_GL_SwapWindow_t)(SDL_Window* window); + +int SDL_PollEvent_hook(SDL_Event* event); +void SDL_GL_SwapWindow_hook(SDL_Window* window); + +void DoSDLHooking(); +void DoSDLUnhooking(); + #include "CreateMove.h" #include "PaintTraverse.h" #include "others.h" diff --git a/src/hooks/nographics.cpp b/src/hooks/nographics.cpp new file mode 100644 index 00000000..8f047361 --- /dev/null +++ b/src/hooks/nographics.cpp @@ -0,0 +1,31 @@ +/* + * nographics.cpp + * + * Created on: Aug 1, 2017 + * Author: nullifiedcat + */ + +#include "../common.h" + +/*// 81 +ITexture *FindTexture_null_hook(void* this_, char const* pTextureName, const char *pTextureGroupName, bool complain, int nAdditionalCreationFlags) { + static ITexture *st = ((FindTexture_t)hooks::materialsystem.GetMethod(81))(this_, pTextureName, pTextureGroupName, complain, nAdditionalCreationFlags); + return st; +} + +// 123 +IMaterial *FindMaterialEx_null_hook(void* this_, char const* pMaterialName, const char *pTextureGroupName, int nContext, bool complain, const char *pComplainPrefix) { + static IMaterial *st = ((FindMaterialEx_t)hooks::materialsystem.GetMethod(123))(this_, pMaterialName, pTextureGroupName, nContext, complain, pComplainPrefix); + return st; +} + +// 73 +IMaterial *FindMaterial_null_hook(void* this_, char const* pMaterialName, const char *pTextureGroupName, bool complain, const char *pComplainPrefix) { + static IMaterial *st = ((FindMaterial_t)hooks::materialsystem.GetMethod(73))(this_, pMaterialName, pTextureGroupName, complain, pComplainPrefix); + return st; +} + +void ReloadTextures_null_hook(void* this_) {} +void ReloadMaterials_null_hook(void* this_, const char *pSubString) {} +void ReloadFilesInList_null_hook(void* this_, IFileList *pFilesToReload) {} +*/ diff --git a/src/hooks/others.cpp b/src/hooks/others.cpp index 0fe4e42e..089d706a 100644 --- a/src/hooks/others.cpp +++ b/src/hooks/others.cpp @@ -7,9 +7,13 @@ #include "../common.h" #include "../netmessage.h" +#include "../chatlog.hpp" #include "../hack.h" +#include "ucccccp.hpp" #include "hookedmethods.h" +#ifndef TEXTMODE + static CatVar no_invisibility(CV_SWITCH, "no_invis", "0", "Remove Invisibility", "Useful with chams!"); // This hook isn't used yet! @@ -66,6 +70,41 @@ void DrawModelExecute_hook(IVModelRender* _this, const DrawModelState_t& state, original(_this, state, info, matrix); } + +int IN_KeyEvent_hook(void* _this, int eventcode, int keynum, const char* pszCurrentBinding) { + static const IN_KeyEvent_t original = (IN_KeyEvent_t)hooks::client.GetMethod(offsets::IN_KeyEvent()); +#if ENABLE_GUI + SEGV_BEGIN; + if (g_pGUI->ConsumesKey((ButtonCode_t)keynum) && g_pGUI->Visible()) { + return 0; + } + SEGV_END; +#endif + return original(_this, eventcode, keynum, pszCurrentBinding); +} + +CatVar override_fov_zoomed(CV_FLOAT, "fov_zoomed", "0", "FOV override (zoomed)", "Overrides FOV with this value when zoomed in (default FOV when zoomed is 20)"); +CatVar override_fov(CV_FLOAT, "fov", "0", "FOV override", "Overrides FOV with this value"); + +void OverrideView_hook(void* _this, CViewSetup* setup) { + static const OverrideView_t original = (OverrideView_t)hooks::clientmode.GetMethod(offsets::OverrideView()); + static bool zoomed; + SEGV_BEGIN; + original(_this, setup); + if (!cathook) return; + if (g_pLocalPlayer->bZoomed && override_fov_zoomed) { + setup->fov = override_fov_zoomed; + } else { + if (override_fov) { + setup->fov = override_fov; + } + } + draw::fov = setup->fov; + SEGV_END; +} + +#endif + bool CanPacket_hook(void* _this) { const CanPacket_t original = (CanPacket_t)hooks::netchannel.GetMethod(offsets::CanPacket()); SEGV_BEGIN; @@ -91,22 +130,9 @@ CUserCmd* GetUserCmd_hook(IInput* _this, int sequence_number) { ch = (INetChannel*)g_IEngine->GetNetChannelInfo();//*(INetChannel**)((unsigned)g_IBaseClientState + offsets::m_NetChannel()); *(int*)((unsigned)ch + offsets::m_nOutSequenceNr()) = def->command_number - 1; } - hacks::shared::lagexploit::GetUserCmd(def, sequence_number); return def; } -int IN_KeyEvent_hook(void* _this, int eventcode, int keynum, const char* pszCurrentBinding) { - static const IN_KeyEvent_t original = (IN_KeyEvent_t)hooks::client.GetMethod(offsets::IN_KeyEvent()); -#if NOGUI != 1 - SEGV_BEGIN; - if (g_pGUI->ConsumesKey((ButtonCode_t)keynum) && g_pGUI->Visible()) { - return 0; - } - SEGV_END; -#endif - return original(_this, eventcode, keynum, pszCurrentBinding); -} - static CatVar log_sent(CV_SWITCH, "debug_log_sent_messages", "0", "Log sent messages"); static CatCommand plus_use_action_slot_item_server("+cat_use_action_slot_item_server", "use_action_slot_item_server", []() { @@ -126,6 +152,9 @@ static CatVar newlines_msg(CV_INT, "chat_newlines", "0", "Prefix newlines", "Add // TODO name \\n = \n //static CatVar queue_messages(CV_SWITCH, "chat_queue", "0", "Queue messages", "Use this if you want to use spam/killsay and still be able to chat normally (without having your msgs eaten by valve cooldown)"); +static CatVar airstuck(CV_KEY, "airstuck", "0", "Airstuck"); +static CatVar crypt_chat(CV_SWITCH, "chat_crypto", "0", "Crypto chat", "Start message with !! and it will be only visible to cathook users"); + bool SendNetMsg_hook(void* _this, INetMessage& msg, bool bForceReliable = false, bool bVoice = false) { static size_t say_idx, say_team_idx; static int offset; @@ -136,13 +165,23 @@ bool SendNetMsg_hook(void* _this, INetMessage& msg, bool bForceReliable = false, const SendNetMsg_t original = (SendNetMsg_t)hooks::netchannel.GetMethod(offsets::SendNetMsg()); SEGV_BEGIN; // net_StringCmd - if (msg.GetType() == 4 && (newlines_msg)) { + if (msg.GetType() == 4 && (newlines_msg || crypt_chat)) { std::string str(msg.ToString()); say_idx = str.find("net_StringCmd: \"say \""); say_team_idx = str.find("net_StringCmd: \"say_team \""); if (!say_idx || !say_team_idx) { offset = say_idx ? 26 : 21; - if (newlines_msg) { + bool crpt = false; + if (crypt_chat) { + std::string msg(str.substr(offset)); + msg = msg.substr(0, msg.length() - 2); + if (msg.find("!!") == 0) { + msg = ucccccp::encrypt(msg.substr(2)); + str = str.substr(0, offset) + msg + "\"\""; + crpt = true; + } + } + if (!crpt && newlines_msg) { // TODO move out? update in a value change callback? newlines = std::string((int)newlines_msg, '\n'); str.insert(offset, newlines); @@ -154,6 +193,20 @@ bool SendNetMsg_hook(void* _this, INetMessage& msg, bool bForceReliable = false, //} } } + static ConVar* sv_player_usercommand_timeout = g_ICvar->FindVar("sv_player_usercommand_timeout"); + static float lastcmd = 0.0f; + if (lastcmd > g_GlobalVars->absoluteframetime) { + lastcmd = g_GlobalVars->absoluteframetime; + } + if (airstuck.KeyDown() && !g_Settings.bInvalid) { + if (CE_GOOD(LOCAL_E)) { + if (lastcmd + sv_player_usercommand_timeout->GetFloat() - 0.1f < g_GlobalVars->curtime) { + if (msg.GetType() == clc_Move) return false; + } else { + lastcmd = g_GlobalVars->absoluteframetime; + } + } + } if (log_sent && msg.GetType() != 3 && msg.GetType() != 9) { logging::Info("=> %s [%i] %s", msg.GetName(), msg.GetType(), msg.ToString()); unsigned char buf[4096]; @@ -172,14 +225,16 @@ bool SendNetMsg_hook(void* _this, INetMessage& msg, bool bForceReliable = false, return false; } -CatVar disconnect_reason(CV_STRING, "disconnect_reason", "", "Disconnect reason", "A custom disconnect reason"); - void Shutdown_hook(void* _this, const char* reason) { // This is a INetChannel hook - it SHOULDN'T be static because netchannel changes. const Shutdown_t original = (Shutdown_t)hooks::netchannel.GetMethod(offsets::Shutdown()); + logging::Info("Disconnect: %s", reason); +#if IPC_ENABLED + ipc::UpdateServerAddress(true); +#endif SEGV_BEGIN; if (cathook && (disconnect_reason.convar_parent->m_StringLength > 3) && strstr(reason, "user")) { - original(_this, disconnect_reason.GetString()); + original(_this, disconnect_reason_newlined); } else { original(_this, reason); } @@ -188,16 +243,129 @@ void Shutdown_hook(void* _this, const char* reason) { static CatVar resolver(CV_SWITCH, "resolver", "0", "Resolve angles"); +CatEnum namesteal_enum({ "OFF", "PASSIVE", "ACTIVE" }); +CatVar namesteal(namesteal_enum, "name_stealer", "0", "Name Stealer", "Attemt to steal your teammates names. Usefull for avoiding kicks\nPassive only changes when the name stolen is no longer the best name to use\nActive Attemps to change the name whenever possible"); + +static std::string stolen_name; + +// Func to get a new entity to steal name from +bool StolenName(){ + + // Array to store potential namestealer targets with a bookkeeper to tell how full it is + int potential_targets[32]; + int potential_targets_length = 0; + + // Go through entities looking for potential targets + for (int i = 1; i < HIGHEST_ENTITY; i++) { + CachedEntity* ent = ENTITY(i); + + // Check if ent is a good target + if (!ent) continue; + if (ent == LOCAL_E) continue; + if (!ent->m_Type == ENTITY_PLAYER) continue; + if (ent->m_bEnemy) continue; + + // Check if name is current one + player_info_s info; + if (g_IEngine->GetPlayerInfo(ent->m_IDX, &info)) { + + // If our name is the same as current, than change it + if (std::string(info.name) == stolen_name) { + // Since we found the ent we stole our name from and it is still good, if user settings are passive, then we return true and dont alter our name + if ((int)namesteal == 1) { + return true; + // Otherwise we continue to change our name to something else + } else continue; + } + + // a ent without a name is no ent we need, contine for a different one + } else continue; + + // Save the ent to our array + potential_targets[potential_targets_length] = i; + potential_targets_length++; + + // With our maximum amount of players reached, dont search for anymore + if (potential_targets_length >= 32) break; + } + + // Checks to prevent crashes + if (potential_targets_length == 0) return false; + + // Get random number that we can use with our array + int target_random_num = floor(RandFloatRange(0, potential_targets_length - 0.1F)); + + // Get a idx from our random array position + int new_target = potential_targets[target_random_num]; + + // Grab username of user + player_info_s info; + if (g_IEngine->GetPlayerInfo(new_target, &info)) { + + // If our name is the same as current, than change it and return true + stolen_name = std::string(info.name); + return true; + } + + // Didnt get playerinfo + return false; +} + +static CatVar ipc_name(CV_STRING, "name_ipc", "", "IPC Name"); + const char* GetFriendPersonaName_hook(ISteamFriends* _this, CSteamID steamID) { static const GetFriendPersonaName_t original = (GetFriendPersonaName_t)hooks::steamfriends.GetMethod(offsets::GetFriendPersonaName()); - if ((force_name.convar->m_StringLength > 2) && steamID == g_ISteamUser->GetSteamID()) { - return force_name.GetString(); + +#if IPC_ENABLED + if (ipc::peer) { + static std::string namestr(ipc_name.GetString()); + namestr.assign(ipc_name.GetString()); + if (namestr.length() > 3) { + ReplaceString(namestr, "%%", std::to_string(ipc::peer->client_id)); + return namestr.c_str(); + } + } +#endif + + // Check User settings if namesteal is allowed + if (namesteal && steamID == g_ISteamUser->GetSteamID()) { + + // We dont want to steal names while not in-game as there are no targets to steal from + if (g_IEngine->IsInGame()) { + + // Check if we have a username to steal, func automaticly steals a name in it. + if (StolenName()) { + + // Return the name that has changed from the func above + return format(stolen_name, "\x0F").c_str(); + } + } + } + + if ((strlen(force_name.GetString()) > 1) && steamID == g_ISteamUser->GetSteamID()) { + + return force_name_newlined; } return original(_this, steamID); } static CatVar cursor_fix_experimental(CV_SWITCH, "experimental_cursor_fix", "1", "Cursor fix"); +void FireGameEvent_hook(void* _this, IGameEvent* event) { + static const FireGameEvent_t original = (FireGameEvent_t)hooks::clientmode4.GetMethod(offsets::FireGameEvent()); + const char* name = event->GetName(); + if (name) { + if (event_log) { + if (!strcmp(name, "player_connect_client") || + !strcmp(name, "player_disconnect") || + !strcmp(name, "player_team")) { + return; + } + } + } + original(_this, event); +} + void FrameStageNotify_hook(void* _this, int stage) { static IClientEntity *ent; @@ -206,11 +374,16 @@ void FrameStageNotify_hook(void* _this, int stage) { static const FrameStageNotify_t original = (FrameStageNotify_t)hooks::client.GetMethod(offsets::FrameStageNotify()); SEGV_BEGIN; if (!g_IEngine->IsInGame()) g_Settings.bInvalid = true; - // TODO hack FSN hook +#ifndef TEXTMODE { PROF_SECTION(FSN_skinchanger); hacks::tf2::skinchanger::FrameStageNotify(stage); } +#endif + if (stage == FRAME_NET_UPDATE_POSTDATAUPDATE_START) { + angles::Update(); + hacks::shared::anticheat::CreateMove(); + } if (resolver && cathook && !g_Settings.bInvalid && stage == FRAME_NET_UPDATE_POSTDATAUPDATE_START) { PROF_SECTION(FSN_resolver); for (int i = 1; i < 32 && i < HIGHEST_ENTITY; i++) { @@ -226,8 +399,44 @@ void FrameStageNotify_hook(void* _this, int stage) { } } } + if (stage == FRAME_START) { +#if IPC_ENABLED + static Timer nametimer {}; + if (nametimer.test_and_set(1000 * 10)) { + if (ipc::peer) { + ipc::StoreClientData(); + } + } + static Timer ipc_timer {}; + if (ipc_timer.test_and_set(1000)) { + if (ipc::peer) { + ipc::Heartbeat(); + ipc::UpdateTemporaryData(); + } + } +#endif + hacks::shared::autojoin::UpdateSearch(); + if (!hack::command_stack().empty()) { + PROF_SECTION(PT_command_stack); + std::lock_guard guard(hack::command_stack_mutex); + while (!hack::command_stack().empty()) { + logging::Info("executing %s", hack::command_stack().top().c_str()); + g_IEngine->ClientCmd_Unrestricted(hack::command_stack().top().c_str()); + hack::command_stack().pop(); + } + } +#if defined(TEXTMODE) and defined(TEXTMODE_STDIN) + static auto last_stdin = std::chrono::system_clock::from_time_t(0); + auto ms = std::chrono::duration_cast(std::chrono::system_clock::now() - last_stdin).count(); + if (ms > 500) { + UpdateInput(); + last_stdin = std::chrono::system_clock::now(); + } +#endif + } +#ifndef TEXTMODE if (cathook && !g_Settings.bInvalid && stage == FRAME_RENDER_START) { -#if NOGUI != 1 +#if ENABLE_GUI if (cursor_fix_experimental) { if (gui_visible) { g_ISurface->SetCursorAlwaysVisible(true); @@ -239,9 +448,6 @@ void FrameStageNotify_hook(void* _this, int stage) { IF_GAME(IsTF()) { if (CE_GOOD(LOCAL_E) && no_zoom) RemoveCondition(LOCAL_E); } - IF_GAME(IsTF2()) { - GlowFrameStageNotify(stage); - } if (force_thirdperson && !g_pLocalPlayer->life_state && CE_GOOD(g_pLocalPlayer->entity)) { CE_INT(g_pLocalPlayer->entity, netvar.nForceTauntCam) = 1; } @@ -252,29 +458,11 @@ void FrameStageNotify_hook(void* _this, int stage) { } } } +#endif /* TEXTMODE */ SAFE_CALL(original(_this, stage)); SEGV_END; } -CatVar override_fov_zoomed(CV_FLOAT, "fov_zoomed", "0", "FOV override (zoomed)", "Overrides FOV with this value when zoomed in (default FOV when zoomed is 20)"); -CatVar override_fov(CV_FLOAT, "fov", "0", "FOV override", "Overrides FOV with this value"); - -void OverrideView_hook(void* _this, CViewSetup* setup) { - static const OverrideView_t original = (OverrideView_t)hooks::clientmode.GetMethod(offsets::OverrideView()); - static bool zoomed; - SEGV_BEGIN; - original(_this, setup); - if (!cathook) return; - if (g_pLocalPlayer->bZoomed && override_fov_zoomed) { - setup->fov = override_fov_zoomed; - } else { - if (override_fov) { - setup->fov = override_fov; - } - } - SEGV_END; -} - static CatVar clean_chat(CV_SWITCH, "clean_chat", "0", "Clean chat", "Removes newlines from chat"); static CatVar dispatch_log(CV_SWITCH, "debug_log_usermessages", "0", "Log dispatched user messages"); @@ -284,24 +472,35 @@ bool DispatchUserMessage_hook(void* _this, int type, bf_read& buf) { static const DispatchUserMessage_t original = (DispatchUserMessage_t)hooks::client.GetMethod(offsets::DispatchUserMessage()); SEGV_BEGIN; - if (clean_chat) { - if (type == 4) { - loop_index = 0; - s = buf.GetNumBytesLeft(); - if (s < 256) { - data = (char*)alloca(s); - for (i = 0; i < s; i++) - data[i] = buf.ReadByte(); - j = 0; - for (i = 0; i < 3; i++) { - while ((c = data[j++]) && (loop_index < 128)) { - loop_index++; + if (type == 4) { + loop_index = 0; + s = buf.GetNumBytesLeft(); + if (s < 256) { + data = (char*)alloca(s); + for (i = 0; i < s; i++) + data[i] = buf.ReadByte(); + j = 0; + std::string name; + std::string message; + for (i = 0; i < 3; i++) { + while ((c = data[j++]) && (loop_index < 128)) { + loop_index++; + if (clean_chat) if ((c == '\n' || c == '\r') && (i == 1 || i == 2)) data[j - 1] = '*'; + if (i == 1) name.push_back(c); + if (i == 2) message.push_back(c); + } + } + if (crypt_chat) { + if (message.find("!!") == 0) { + if (ucccccp::validate(message)) { + PrintChat("\x07%06X%s\x01: %s", 0xe05938, name.c_str(), ucccccp::decrypt(message).c_str()); } } - buf = bf_read(data, s); - buf.Seek(0); } + chatlog::LogMessage(data[0], message); + buf = bf_read(data, s); + buf.Seek(0); } } if (dispatch_log) { @@ -318,8 +517,9 @@ void LevelInit_hook(void* _this, const char* newmap) { g_IEngine->ClientCmd_Unrestricted("exec cat_matchexec"); hacks::shared::aimbot::Reset(); chat_stack::Reset(); - hacks::shared::spam::Reset(); + hacks::shared::anticheat::ResetEverything(); original(_this, newmap); + hacks::shared::walkbot::OnLevelInit(); } void LevelShutdown_hook(void* _this) { @@ -329,7 +529,7 @@ void LevelShutdown_hook(void* _this) { g_Settings.bInvalid = true; hacks::shared::aimbot::Reset(); chat_stack::Reset(); - hacks::shared::spam::Reset(); + hacks::shared::anticheat::ResetEverything(); original(_this); } diff --git a/src/hooks/others.h b/src/hooks/others.h index 8f5f67ba..dfbfe301 100644 --- a/src/hooks/others.h +++ b/src/hooks/others.h @@ -25,7 +25,20 @@ bool DispatchUserMessage_hook(void*, int, bf_read&); void FrameStageNotify_hook(void*, int); void LevelInit_hook(void*, const char*); void LevelShutdown_hook(void*); -void SwapWindow_hook(SDL_Window* window); + + +#ifdef TEXTMODE +typedef ITexture*(*FindTexture_t)(void*, const char*, const char*, bool, int); +typedef IMaterial*(*FindMaterialEx_t)(void*, const char*, const char*, int, bool, const char*); +typedef IMaterial*(*FindMaterial_t)(void*, const char*, const char*, bool, const char*); + +/* 70 */ void ReloadTextures_null_hook(void* this_); +/* 71 */ void ReloadMaterials_null_hook(void* this_, const char *pSubString); +/* 73 */ IMaterial *FindMaterial_null_hook(void* this_, char const* pMaterialName, const char *pTextureGroupName, bool complain, const char *pComplainPrefix); +/* 81 */ ITexture *FindTexture_null_hook(void* this_, char const* pTextureName, const char *pTextureGroupName, bool complain, int nAdditionalCreationFlags); +/* 121 */ void ReloadFilesInList_null_hook(void* this_, IFileList *pFilesToReload); +/* 123 */ IMaterial *FindMaterialEx_null_hook(void* this_, char const* pMaterialName, const char *pTextureGroupName, int nContext, bool complain, const char *pComplainPrefix); +#endif //extern unsigned int* swapwindow_ptr; //extern unsigned int swapwindow_orig; diff --git a/src/hooks/sdl.cpp b/src/hooks/sdl.cpp new file mode 100644 index 00000000..5e3e7504 --- /dev/null +++ b/src/hooks/sdl.cpp @@ -0,0 +1,111 @@ +/* + * sdl.cpp + * + * Created on: May 19, 2017 + * Author: nullifiedcat + */ + +#include "hookedmethods.h" +#include "../common.h" +#include "../hack.h" + +#include + +#include +#include +#include +#include "../ftrender.hpp" + +SDL_PollEvent_t* SDL_PollEvent_loc { nullptr }; +SDL_GL_SwapWindow_t* SDL_GL_SwapWindow_loc { nullptr }; +SDL_PollEvent_t SDL_PollEvent_o { nullptr }; +SDL_GL_SwapWindow_t SDL_GL_SwapWindow_o { nullptr }; + +int SDL_PollEvent_hook(SDL_Event* event) { + int retval = SDL_PollEvent_o(event); + if (event && (event->key.keysym.sym & ~SDLK_SCANCODE_MASK) < 512) { + ImGui_ImplSdl_ProcessEvent(event); + } + return retval; +} + +#include +#include "../atlas.hpp" +#include "../drawgl.hpp" +#include "../gui/im/Im.hpp" + +void SDL_GL_SwapWindow_hook(SDL_Window* window) { + static SDL_GLContext ctx_tf2 = SDL_GL_GetCurrentContext(); + static SDL_GLContext ctx_imgui = nullptr; + static SDL_GLContext ctx_text = nullptr; + if (!disable_visuals) { + PROF_SECTION(DRAW_cheat); + if (!ctx_imgui) { + ctx_imgui = SDL_GL_CreateContext(window); + ImGui_ImplSdl_Init(window); + ctx_text = SDL_GL_CreateContext(window); + FTGL_Init(); + textures::Init(); + drawgl::Initialize(); + } + + if (!cathook) { + SDL_GL_MakeCurrent(window, ctx_tf2); + SDL_GL_SwapWindow_o(window); + return; + } + + SDL_GL_MakeCurrent(window, ctx_text); + { + std::lock_guard draw_lock(drawing_mutex); + drawgl::PreRender(); + { + PROF_SECTION(DRAW_gl); + drawgl::Render(); + } + + { + PROF_SECTION(DRAW_freetype); + FTGL_Render(); + } + + drawgl::PostRender(); + } + SDL_GL_MakeCurrent(window, ctx_imgui); + { + PROF_SECTION(DRAW_imgui); + ImGui_ImplSdl_NewFrame(window); + menu::im::Render(); + ImGui::Render(); + } + } + { + PROF_SECTION(DRAW_valve); + SDL_GL_MakeCurrent(window, ctx_tf2); + SDL_GL_SwapWindow_o(window); + } +} + +void DoSDLHooking() { + SDL_GL_SwapWindow_loc = reinterpret_cast(sharedobj::libsdl().Pointer(0xFD648)); + SDL_PollEvent_loc = reinterpret_cast(sharedobj::libsdl().Pointer(0xFCF64)); + + SDL_GL_SwapWindow_o = *SDL_GL_SwapWindow_loc; + SDL_PollEvent_o = *SDL_PollEvent_loc; + + /*char patch_1[4]; + char patch_2[4]; + *((unsigned*)patch_1) = (unsigned)SDL_GL_SwapWindow_hook; + *((unsigned*)patch_2) = (unsigned)SDL_PollEvent_hook; + + Patch(SDL_GL_SwapWindow_loc, patch_1, 4); + Patch(SDL_PollEvent_loc, patch_2, 4);*/ + + *SDL_GL_SwapWindow_loc = SDL_GL_SwapWindow_hook; + *SDL_PollEvent_loc = SDL_PollEvent_hook; +} + +void DoSDLUnhooking() { + *SDL_GL_SwapWindow_loc = SDL_GL_SwapWindow_o; + *SDL_PollEvent_loc = SDL_PollEvent_o; +} diff --git a/src/https_request.cpp b/src/https_request.cpp new file mode 100644 index 00000000..6b3af389 --- /dev/null +++ b/src/https_request.cpp @@ -0,0 +1,125 @@ +/* + * https_request.cpp + * + * Created on: Jul 23, 2017 + * Author: nullifiedcat + */ + +#include "https_request.hpp" + +#include "logging.h" + +#include +#include +#include + +#include + +#include +#include + + +namespace https { + +SSL_CTX *ssl_context; + +bool initialized = false; + +RAII_HTTPS_Socket::RAII_HTTPS_Socket(const std::string& host) : hostname_(host) { + if (!initialized) { + logging::Info("Initializing SSL"); + initialize(); + } + sock_ = socket(AF_INET, SOCK_STREAM, 0); + if (sock_ < 0) { + throw std::runtime_error("Socket creation error"); + } + host_ = gethostbyname(hostname_.c_str()); + if (not host_) { + throw std::runtime_error("Could not resolve hostname: " + host); + } + memset(&addr_, 0, sizeof(addr_)); + addr_.sin_family = AF_INET; + addr_.sin_port = htons(443); + memcpy(&addr_.sin_addr.s_addr, host_->h_addr, host_->h_length); + if (connect(sock_, (sockaddr *)&addr_, sizeof(addr_)) < 0) { + close(sock_); + sock_ = -1; + throw std::runtime_error("Couldn't connect to host"); + } + ssl_connect(); +} + +RAII_HTTPS_Socket::~RAII_HTTPS_Socket() { + ssl_die(); + if (sock_ >= 0) + close(sock_); +} + +bool RAII_HTTPS_Socket::ssl_connect() { + connection_ = SSL_new(ssl_context); + SSL_set_fd(connection_, sock_); + int ret = SSL_connect(connection_); + if (ret != 1) { + logging::Info("SSL connection error: %d, %d, %x\n", ret, SSL_get_error(connection_, ret), ERR_get_error()); + return false; + } + return true; +} + +void RAII_HTTPS_Socket::ssl_die() { + if (connection_) { + SSL_free(connection_); + connection_ = nullptr; + } +} + +std::string RAII_HTTPS_Socket::get(const std::string& path) { + constexpr size_t rq_size = 1024 * 8; + constexpr size_t rs_size = 1024 * 1024; + + std::unique_ptr + buffer_rq(new char[rq_size]), + buffer_rs(new char[rs_size]); + + memset(buffer_rq.get(), 0, rq_size); + int rq_length = snprintf(buffer_rq.get(), rq_size, "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", path.c_str(), hostname_.c_str()); + int sent = 0; + int chunk = 0; + do { + chunk = SSL_write(connection_, buffer_rq.get() + sent, rq_length - sent); + if (chunk < 0) { + throw std::runtime_error("Error writing to Secure Socket: " + std::to_string(ERR_get_error())); + } else if (chunk == 0) { + break; + } + sent += chunk; + } while (sent < rq_length); + + memset(buffer_rs.get(), 0, rs_size); + int total = rs_size - 1; + int received = 0; + do { + chunk = SSL_read(connection_, buffer_rs.get() + received, total - received); + if (chunk < 0) + throw std::runtime_error("Error reading from socket"); + if (chunk == 0) + break; + received += chunk; + } while (received < total); + + if (received == total) + throw std::runtime_error("Response too large"); + + return std::string(buffer_rs.get()); +} + + +void initialize() { + SSL_load_error_strings(); + SSL_library_init(); + ssl_context = SSL_CTX_new(SSLv23_client_method()); + initialized = true; +} + +} diff --git a/src/https_request.hpp b/src/https_request.hpp new file mode 100644 index 00000000..f56a7adc --- /dev/null +++ b/src/https_request.hpp @@ -0,0 +1,44 @@ +/* + * https_request.hpp + * + * Created on: Jul 23, 2017 + * Author: nullifiedcat + */ + +#pragma once + +#include +#include + +#include "beforecheaders.h" +#include +#include "aftercheaders.h" + + +namespace https { + +extern SSL_CTX *ssl_context; + +class RAII_HTTPS_Socket { +public: + RAII_HTTPS_Socket(const std::string& host); + ~RAII_HTTPS_Socket(); + + bool ssl_connect(); + void ssl_die(); + + std::string get(const std::string& path); + + const std::string hostname_; + + hostent *host_ { nullptr }; + sockaddr_in addr_ {}; + int sock_ { -1 }; + SSL *connection_ { nullptr }; +}; + +void initialize(); + +} + + diff --git a/src/imgui/LICENSE b/src/imgui/LICENSE new file mode 100644 index 00000000..b28ef225 --- /dev/null +++ b/src/imgui/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2015 Omar Cornut and ImGui contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/imgui/README.md b/src/imgui/README.md new file mode 100644 index 00000000..9cb17933 --- /dev/null +++ b/src/imgui/README.md @@ -0,0 +1,237 @@ +dear imgui, +===== +[![Build Status](https://travis-ci.org/ocornut/imgui.svg?branch=master)](https://travis-ci.org/ocornut/imgui) +[![Coverity Status](https://scan.coverity.com/projects/4720/badge.svg)](https://scan.coverity.com/projects/4720) + +(This library is free but needs your support to sustain its development. There are lots of desirable new features and maintenance to do. If you are an individual using dear imgui, please consider financial support via Patreon/PayPal. If your company is using dear imgui, please consider sponsorship (e.g. sponsoring a few weeks of development). I can invoice for private support, custom development etc. E-mail: omarcornut at gmail.) + +Monthly donations via Patreon: +
[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) + +One-off donations via PayPal: +
[![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U) + +dear imgui (AKA ImGui), is a bloat-free graphical user interface library for C++. It outputs optimized vertex buffers that you can render anytime in your 3D-pipeline enabled application. It is fast, portable, renderer agnostic and self-contained (no external dependencies). + +ImGui is designed to enable fast iteration and empower programmers to create content creation tools and visualization/ debug tools (as opposed to UI for the average end-user). It favors simplicity and productivity toward this goal, and thus lacks certain features normally found in more high-level libraries. + +ImGui is particularly suited to integration in realtime 3D applications, fullscreen applications, embedded applications, games, or any applications on consoles platforms where operating system features are non-standard. + +ImGui is self-contained within a few files that you can easily copy and compile into your application/engine: + + - imgui.cpp + - imgui.h + - imgui_demo.cpp + - imgui_draw.cpp + - imgui_internal.h + - imconfig.h (empty by default, user-editable) + - stb_rect_pack.h + - stb_textedit.h + - stb_truetype.h + +No specific build process is required. You can add the .cpp files to your project or #include them from an existing file. + +Your code passes mouse/keyboard inputs and settings to ImGui (see example applications for more details). After ImGui is setup, you can use it like in this example: + +![screenshot of sample code alongside its output with ImGui](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01.png) + +ImGui outputs vertex buffers and simple command-lists that you can render in your application. The number of draw calls and state changes is typically very small. Because it doesn't know or touch graphics state directly, you can call ImGui commands anywhere in your code (e.g. in the middle of a running algorithm, or in the middle of your own rendering process). Refer to the sample applications in the examples/ folder for instructions on how to integrate ImGui with your existing codebase. + +_A common misunderstanding is to think that immediate mode gui == immediate mode rendering, which usually implies hammering your driver/GPU with a bunch of inefficient draw calls and state changes, as the gui functions are called by the user. This is NOT what Dear ImGui does. Dear ImGui outputs vertex buffers and a small list of draw calls batches. It never touches your GPU directly. The draw call batches are decently optimal and you can render them later, in your app or even remotely._ + +ImGui allows you create elaborate tools as well as very short-lived ones. On the extreme side of short-liveness: using the Edit&Continue feature of modern compilers you can add a few widgets to tweaks variables while your application is running, and remove the code a minute later! ImGui is not just for tweaking values. You can use it to trace a running algorithm by just emitting text commands. You can use it along with your own reflection data to browse your dataset live. You can use it to expose the internals of a subsystem in your engine, to create a logger, an inspection tool, a profiler, a debugger, an entire game making editor/framework, etc. + +Binaries/Demo +------------- + +You should be able to build the examples from sources (tested on Windows/Mac/Linux). If you don't, let me know! If you want to have a quick look at the features of ImGui, you can download Windows binaries of the demo app here. +- [imgui-demo-binaries-20161113.zip](http://www.miracleworld.net/imgui/binaries/imgui-demo-binaries-20161113.zip) (Windows binaries, ImGui 1.49+ 2016/11/13, 5 executables, 588 KB) + +Bindings +-------- + +_NB: those third-party bindings may be more or less maintained, more or less close to the spirit of original API and therefore I cannot give much guarantee about them. People who create language bindings sometimes haven't used the C++ API themselves (for the good reason that they aren't C++ users). ImGui was designed with C++ in mind and some of the subtleties may be lost in translation with other languages. If your language supports it, I would suggest replicating the function overloading and default parameters used in the original, else the API may be harder to use. In doubt, please check the original C++ version first!_ + +_Integrating Dear ImGui within your custom engine is a matter of wiring mouse/keyboard inputs and providing a render function that can bind a texture and render simple textured triangles. The examples/ folder is populated with applications doing just that. If you are an experienced programmer it should take you less than an hour to integrate Dear ImGui in your custom engine, but make sure to spend time reading the FAQ, the comments and other documentation!_ + +Languages: +- cimgui: thin c-api wrapper for ImGui https://github.com/Extrawurst/cimgui +- ImGui.NET: An ImGui wrapper for .NET Core https://github.com/mellinoe/ImGui.NET +- imgui-rs: Rust bindings for dear imgui https://github.com/Gekkio/imgui-rs +- DerelictImgui: Dynamic bindings for the D programming language: https://github.com/Extrawurst/DerelictImgui +- CyImGui: Python bindings for dear imgui using Cython: https://github.com/chromy/cyimgui +- pyimgui: Another Python bindings for dear imgui: https://github.com/swistakm/pyimgui +- LUA: https://github.com/patrickriordan/imgui_lua_bindings +- imgui-pas: P ascal bindings for imgui https://github.com/dpethes/imgui-pas + +Frameworks: +- Main ImGui repository include examples for DirectX9, DirectX10, DirectX11, OpenGL2/3, Vulkan, Allegro 5, SDL+GL2/3, iOS and Marmalade: https://github.com/ocornut/imgui/tree/master/examples +- Unmerged PR: DirectX12 example (with issues) https://github.com/ocornut/imgui/pull/301 +- Unmerged PR: SDL2 + OpenGLES + Emscripten example https://github.com/ocornut/imgui/pull/336 +- Unmerged PR: FreeGlut + OpenGL2 example https://github.com/ocornut/imgui/pull/801 +- Unmerged PR: Native Win32 and OSX example https://github.com/ocornut/imgui/pull/281 +- Unmerged PR: Android Example https://github.com/ocornut/imgui/pull/421 +- Cinder backend for dear imgui https://github.com/simongeilfus/Cinder-ImGui +- FlexGUI: Flexium/SFML backend for dear imgui https://github.com/DXsmiley/FlexGUI +- IrrIMGUI: Irrlicht backend for dear imgui https://github.com/ZahlGraf/IrrIMGUI +- UnrealEngine_ImGui: Unreal Engine 4 backend for dear imgui https://github.com/sronsse/UnrealEngine_ImGui +- LÖVE backend for dear imgui https://github.com/slages/love-imgui +- Ogre backend for dear imgui https://bitbucket.org/LMCrashy/ogreimgui/src +- ofxImGui: openFrameworks backend for dear imgui https://github.com/jvcleave/ofxImGui +- SFML backend for dear imgui https://github.com/EliasD/imgui-sfml +- SFML backend for dear imgui https://github.com/Mischa-Alff/imgui-backends +- cocos2d-x with imgui https://github.com/c0i/imguix https://github.com/ocornut/imgui/issues/551 +- NanoRT: software raytraced version https://github.com/syoyo/imgui/tree/nanort/examples/raytrace_example + +For other bindings: see [this page](https://github.com/ocornut/imgui/wiki/Links/). +Please contact me with the Issues tracker or Twitter to fix/update this list. + +Gallery +------- + +See the [Screenshots Thread](https://github.com/ocornut/imgui/issues/123) for some user creations. + +![screenshot 1](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_01.png) +[![screenshot game](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v149/gallery_TheDragonsTrap-01-thumb.jpg)](https://cloud.githubusercontent.com/assets/8225057/20628927/33e14cac-b329-11e6-80f6-9524e93b048a.png) +![screenshot 2](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/examples_02.png) + +[![screenshot profiler](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler-880.jpg)](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v148/profiler.png) + +![screenshot 3](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_01.png) +![screenshot 4](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/test_window_03.png) +![screenshot 5](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v140/test_window_05_menus.png) +![screenshot 6](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v143/skinning_sample_02.png) +![screenshot 7](https://cloud.githubusercontent.com/assets/8225057/7903336/96f0fb7c-07d0-11e5-95d6-41c6a1595e5a.png) + +ImGui can load TTF fonts. UTF-8 is supported for text display and input. Here using Arial Unicode font to display Japanese. Initialize custom font with: +``` +ImGuiIO& io = ImGui::GetIO(); +io.Fonts->AddFontFromFileTTF("ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); + +// For Microsoft IME, pass your HWND to enable IME positioning: +io.ImeWindowHandle = my_hwnd; +``` +![Japanese screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/code_sample_01_jp.png) + +References +---------- + +The Immediate Mode GUI paradigm may at first appear unusual to some users. This is mainly because "Retained Mode" GUIs have been so widespread and predominant. The following links can give you a better understanding about how Immediate Mode GUIs works. +- [Johannes 'johno' Norneby's article](http://www.johno.se/book/imgui.html). +- [A presentation by Rickard Gustafsson and Johannes Algelind](http://www.cse.chalmers.se/edu/year/2011/course/TDA361/Advanced%20Computer%20Graphics/IMGUI.pdf). +- [Jari Komppa's tutorial on building an ImGui library](http://iki.fi/sol/imgui/). +- [Casey Muratori's original video that popularized the concept](https://mollyrocket.com/861). +- [Nicolas Guillemot's CppCon'16 flashtalk about Dear ImGui](https://www.youtube.com/watch?v=LSRJ1jZq90k). + +See the [Links page](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to different languages and frameworks. + +Frequently Asked Question (FAQ) +------------------------------- + +Where is the documentation? + +- The documentation is at the top of imgui.cpp + effectively imgui.h. +- Example code is in imgui_demo.cpp and particularly the ImGui::ShowTestWindow() function. It covers most features of ImGui so you can read the code and call the function itself to see its output. +- Standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder. +- We obviously needs better documentation! Consider contributing or becoming a [Patron](http://www.patreon.com/imgui) to promote this effort. + +Why the odd dual naming, "dear imgui" vs "ImGui"? + +The library started its life and is best known as "ImGui" only due to the fact that I didn't give it a proper name when I released it. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations. It seemed confusing and unfair to hog the name. To reduce the ambiguity without affecting existing codebases, I have decided on an alternate, longer name "dear imgui" that people can use to refer to this specific library in ambiguous situations. + +How do I update to a newer version of ImGui? +
What is ImTextureID and how do I display an image? +
I integrated ImGui in my engine and the text or lines are blurry.. +
I integrated ImGui in my engine and some elements are disappearing when I move windows around.. +
How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. +
How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? +
How can I load a different font than the default? +
How can I easily use icons in my application? +
How can I load multiple fonts? +
How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? +
How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + +See the FAQ in imgui.cpp for answers. + +How do you use ImGui on a platform that may not have a mouse or keyboard? + +I recommend using [Synergy](http://synergy-project.org) ([sources](https://github.com/symless/synergy)). In particular, the _src/micro/uSynergy.c_ file contains a small client that you can use on any platform to connect to your host PC. You can seamlessly use your PC input devices from a video game console or a tablet. ImGui allows to increase the hit box of widgets (via the _TouchPadding_ setting) to accommodate a little for the lack of precision of touch inputs, but it is recommended you use a mouse to allow optimising for screen real-estate. + +Can you create elaborate/serious tools with ImGui? + +Yes. I have written data browsers, debuggers, profilers and all sort of non-trivial tools with the library. In my experience the simplicity of the API is very empowering. Your UI runs close to your live data. Make the tools always-on and everybody in the team will be inclined to create new tools (as opposed to more "offline" UI toolkits where only a fraction of your team effectively creates tools). + +ImGui is very programmer centric and the immediate-mode GUI paradigm might requires you to readjust some habits before you can realize its full potential. Many programmers have unfortunately been taught by their environment to make unnecessarily complicated things. ImGui is about making things that are simple, efficient and powerful. + +Is ImGui fast? + +Probably fast enough for most uses. Down to the foundation of its visual design, ImGui is engineered to be fairly performant both in term of CPU and GPU usage. Running elaborate code and creating elaborate UI will of course have a cost but ImGui aims to minimize it. + +Mileage may vary but the following screenshot can give you a rough idea of the cost of running and rendering UI code (In the case of a trivial demo application like this one, your driver/os setup are likely to be the bottleneck. Testing performance as part of a real application is recommended). + +![performance screenshot](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v138/performance_01.png) + +This is showing framerate for the full application loop on my 2011 iMac running Windows 7, OpenGL, AMD Radeon HD 6700M with an optimized executable. In contrast, librairies featuring higher-quality rendering and layouting techniques may have a higher resources footprint. + +If you intend to display large lists of items (say, 1000+) it can be beneficial for your code to perform clipping manually - one way is using helpers such as ImGuiListClipper - in order to avoid submitting them to ImGui in the first place. Even though ImGui will discard your clipped items it still needs to calculate their size and that overhead will add up if you have thousands of items. If you can handle clipping and height positionning yourself then browsing a list with millions of items isn't a problem. + +Can you reskin the look of ImGui? + +You can alter the look of the interface to some degree: changing colors, sizes, padding, rounding, fonts. However, as ImGui is designed and optimised to create debug tools, the amount of skinning you can apply is limited. There is only so much you can stray away from the default look and feel of the interface. + +This is [LumixEngine](https://github.com/nem0/LumixEngine) with a minor skinning hack + a docking/tabs extension (both of which you can find in the Issues section and will eventually be merged). + +[![Skinning in LumixEngine](https://cloud.githubusercontent.com/assets/8225057/13198792/92808c5c-d812-11e5-9507-16b63918b05b.jpg)](https://cloud.githubusercontent.com/assets/8225057/13044612/59f07aec-d3cf-11e5-8ccb-39adf2e13e69.png) + +Why using C++ (as opposed to C)? + +ImGui takes advantage of a few C++ languages features for convenience but nothing anywhere Boost-insanity/quagmire. ImGui doesn't use any C++ header file. Language-wise, function overloading and default parameters are used to make the API easier to use and code more terse. Doing so I believe the API is sitting on a sweet spot and giving up on those features would make the API more cumbersome. Other features such as namespace, constructors and templates (in the case of the ImVector<> class) are also relied on as a convenience. + +There is an unofficial but reasonably maintained [c-api for ImGui](https://github.com/Extrawurst/cimgui) by Stephan Dilly. I would suggest using your target language functionality to try replicating the function overloading and default parameters used in C++ else the API may be harder to use. It was really designed with C++ in mind and may not make the same amount of sense with another language. Also see [Links](https://github.com/ocornut/imgui/wiki/Links) for third-party bindings to other languages. + +Donate +------ + +How can I help financing further development of Dear ImGui? + +Monthly donations via Patreon: +
[![Patreon](https://cloud.githubusercontent.com/assets/8225057/5990484/70413560-a9ab-11e4-8942-1a63607c0b00.png)](http://www.patreon.com/imgui) + +One-off donations via PayPal: +
[![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5Q73FPZ9C526U) + +Your contributions are keeping the library alive. For end-users, I have setup an [**ImGui Patreon page**](http://www.patreon.com/imgui) if you want to donate and enable me to spend more time improving the library. If your company uses ImGui please consider making a contribution. One-off donations are also greatly appreciated. I can invoice for private support, custom development or whatever makes more sense in a given context. I am available for hire to work on or with ImGui. Please e-mail omarcornut at gmail for details. Thanks! + +Credits +------- + +Developed by [Omar Cornut](http://www.miracleworld.net) and every direct or indirect contributors to the GitHub. The early version of this library was developed with the support of [Media Molecule](http://www.mediamolecule.com) and first used internally on the game [Tearaway](http://tearaway.mediamolecule.com). + +I first discovered imgui principles at [Q-Games](http://www.q-games.com) where Atman had dropped his own simple imgui implementation in the codebase, which I spent quite some time improving and thinking about. It turned out that Atman was exposed to the concept directly by working with Casey. When I moved to Media Molecule I rewrote a new library trying to overcome the flaws and limitations of the first one I've worked with. It became this library and since then I have spent an unreasonable amount of time iterating on it. + +Embeds [ProggyClean.ttf](http://upperbounds.net) font by Tristan Grimmer (MIT license). + +Embeds [stb_textedit.h, stb_truetype.h, stb_rectpack.h](https://github.com/nothings/stb/) by Sean Barrett (public domain). + +Inspiration, feedback, and testing for early versions: Casey Muratori, Atman Binstock, Mikko Mononen, Emmanuel Briney, Stefan Kamoda, Anton Mikhailov, Matt Willis. And everybody posting feedback, questions and patches on the GitHub. + +Ongoing ImGui development is financially supported on [**Patreon**](http://www.patreon.com/imgui). + +Double-chocolate sponsors: +- Media Molecule +- Mobigame +- Insomniac Games (sponsored the gamepad/keyboard navigation branch) +- Aras Pranckevičius + +Salty caramel supporters: +- Jetha Chan, Wild Sheep Studio, Pastagames, Mārtiņš Možeiko, Daniel Collin, Recognition Robotics, Chris Genova, ikrima, Glenn Fiedler, Geoffrey Evans, Dakko Dakko. + +Caramel supporters: +- Michel Courtine, César Leblic, Dale Kim, Alex Evans, Rui Figueira, Paul Patrashcu, Jerome Lanquetot, Ctrl Alt Ninja, Paul Fleming, Neil Henning, Stephan Dilly, Neil Blakey-Milner, Aleksei, NeiloGD, Justin Paver, FiniteSol, Vincent Pancaldi, James Billot, Robin Hübner, furrtek, Eric, Simon Barratt, Game Atelier, Julian Bosch, Simon Lundmark, Vincent Hamm, Farhan Wali, Jeff Roberts, Matt Reyer, Colin Riley, Victor Martins, Josh Simmons, Garrett Hoofman, Sergio Gonzales, Andrew Berridge, Roy Eltham, Game Preservation Society, [Kit framework](http://svkonsult.se/kit), Josh Faust, Martin Donlon, Quinton, Felix. + +And other supporters; thanks! + +License +------- + +Dear ImGui is licensed under the MIT License, see LICENSE for more information. diff --git a/src/imgui/imconfig.h b/src/imgui/imconfig.h new file mode 100644 index 00000000..19911acc --- /dev/null +++ b/src/imgui/imconfig.h @@ -0,0 +1,58 @@ +//----------------------------------------------------------------------------- +// USER IMPLEMENTATION +// This file contains compile-time options for ImGui. +// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO(). +//----------------------------------------------------------------------------- + +#pragma once + +//---- Define assertion handler. Defaults to calling assert(). +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) + +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows. +//#define IMGUI_API __declspec( dllexport ) +//#define IMGUI_API __declspec( dllimport ) + +//---- Include imgui_user.h at the end of imgui.h +//#define IMGUI_INCLUDE_IMGUI_USER_H + +//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions) +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS +//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS + +//---- Don't implement test window functionality (ShowTestWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty) +//---- It is very strongly recommended to NOT disable the test windows. Please read the comment at the top of imgui_demo.cpp to learn why. +//#define IMGUI_DISABLE_TEST_WINDOWS + +//---- Don't define obsolete functions names +//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//---- Pack colors to BGRA instead of RGBA (remove need to post process vertex buffer in back ends) +//#define IMGUI_USE_BGRA_PACKED_COLOR + +//---- Implement STB libraries in a namespace to avoid conflicts +//#define IMGUI_STB_NAMESPACE ImGuiStb + +//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. +/* +#define IM_VEC2_CLASS_EXTRA \ + ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ + operator MyVec2() const { return MyVec2(x,y); } + +#define IM_VEC4_CLASS_EXTRA \ + ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ + operator MyVec4() const { return MyVec4(x,y,z,w); } +*/ + +//---- Use 32-bit vertex indices (instead of default: 16-bit) to allow meshes with more than 64K vertices +//#define ImDrawIdx unsigned int + +//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. +//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers. +/* +namespace ImGui +{ + void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL); +} +*/ + diff --git a/src/imgui/imgui.cpp b/src/imgui/imgui.cpp new file mode 100644 index 00000000..7ca66c79 --- /dev/null +++ b/src/imgui/imgui.cpp @@ -0,0 +1,9877 @@ +// dear imgui, v1.51 WIP +// (main code and documentation) + +// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. +// Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase. +// Get latest version at https://github.com/ocornut/imgui +// Releases change-log at https://github.com/ocornut/imgui/releases +// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/772 +// Developed by Omar Cornut and every direct or indirect contributors to the GitHub. +// This library is free but I need your support to sustain development and maintenance. +// If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui + +/* + + Index + - MISSION STATEMENT + - END-USER GUIDE + - PROGRAMMER GUIDE (read me!) + - API BREAKING CHANGES (read me when you update!) + - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS + - How can I help? + - How do I update to a newer version of ImGui? + - What is ImTextureID and how do I display an image? + - I integrated ImGui in my engine and the text or lines are blurry.. + - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. + - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + - How can I load a different font than the default? + - How can I easily use icons in my application? + - How can I load multiple fonts? + - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? + - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + - ISSUES & TODO-LIST + - CODE + + + MISSION STATEMENT + ================= + + - easy to use to create code-driven and data-driven tools + - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools + - easy to hack and improve + - minimize screen real-estate usage + - minimize setup and maintenance + - minimize state storage on user side + - portable, minimize dependencies, run on target (consoles, phones, etc.) + - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) + - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html + + Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: + - doesn't look fancy, doesn't animate + - limited layout features, intricate layouts are typically crafted in code + - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction. + + + END-USER GUIDE + ============== + + - double-click title bar to collapse window + - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin() + - click and drag on lower right corner to resize window + - click and drag on any empty space to move window + - double-click/double-tap on lower right corner grip to auto-fit to content + - TAB/SHIFT+TAB to cycle through keyboard editable fields + - use mouse wheel to scroll + - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) + - CTRL+Click on a slider or drag box to input value as text + - text editor: + - Hold SHIFT or use mouse to select text. + - CTRL+Left/Right to word jump + - CTRL+Shift+Left/Right to select words + - CTRL+A our Double-Click to select all + - CTRL+X,CTRL+C,CTRL+V to use OS clipboard + - CTRL+Z,CTRL+Y to undo/redo + - ESCAPE to revert text to its original value + - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) + + + PROGRAMMER GUIDE + ================ + + - read the FAQ below this section! + - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. + - call and read ImGui::ShowTestWindow() for demo code demonstrating most features. + - see examples/ folder for standalone sample applications. Prefer reading examples/opengl2_example/ first as it is the simplest. + you may be able to grab and copy a ready made imgui_impl_*** file from the examples/. + - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme). + + - getting started: + - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'. + - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory. + - every frame: + 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input' + 2/ call ImGui::NewFrame() as early as you can! + 3/ use any ImGui function you want between NewFrame() and Render() + 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure. + (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.) + - all rendering information are stored into command-lists until ImGui::Render() is called. + - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide. + - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. + - refer to the examples applications in the examples/ folder for instruction on how to setup your code. + - a typical application skeleton may be: + + // Application init + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize.x = 1920.0f; + io.DisplaySize.y = 1280.0f; + io.IniFilename = "imgui.ini"; + io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data. + // TODO: Fill others settings of the io structure + + // Load texture atlas + // There is a default font so you don't need to care about choosing a font yet + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); + // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system + // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID' + + // Application main loop + while (true) + { + // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.) + // TODO: fill all fields of IO structure and call NewFrame + ImGuiIO& io = ImGui::GetIO(); + io.DeltaTime = 1.0f/60.0f; + io.MousePos = mouse_pos; + io.MouseDown[0] = mouse_button_0; + io.MouseDown[1] = mouse_button_1; + io.KeysDown[i] = ... + + // 2) call NewFrame(), after this point you can use ImGui::* functions anytime + ImGui::NewFrame(); + + // 3) most of your application code here + MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); + MyGameRender(); // may use any ImGui functions + + // 4) render & swap video buffers + ImGui::Render(); + SwapBuffers(); + } + + - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your + inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information. + + + API BREAKING CHANGES + ==================== + + Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. + Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. + Also read releases logs https://github.com/ocornut/imgui/releases for more details. + + - 2017/07/20 (1.51) - Removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse + - 2017/05/26 (1.50) - Removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. + - 2017/05/01 (1.50) - Renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. + - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). + - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. + - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. + - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. + - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. + If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. + However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. + This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. + ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) + { + float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; + return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); + } + If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. + - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). + - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. + - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). + - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. + - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). + - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) + - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). + - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. + - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. + - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. + - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. + - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. + GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. + GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! + - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize + - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. + - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason + - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. + you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. + - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. + this necessary change will break your rendering function! the fix should be very easy. sorry for that :( + - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. + - the signature of the io.RenderDrawListsFn handler has changed! + ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) + became: + ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). + argument 'cmd_lists' -> 'draw_data->CmdLists' + argument 'cmd_lists_count' -> 'draw_data->CmdListsCount' + ImDrawList 'commands' -> 'CmdBuffer' + ImDrawList 'vtx_buffer' -> 'VtxBuffer' + ImDrawList n/a -> 'IdxBuffer' (new) + ImDrawCmd 'vtx_count' -> 'ElemCount' + ImDrawCmd 'clip_rect' -> 'ClipRect' + ImDrawCmd 'user_callback' -> 'UserCallback' + ImDrawCmd 'texture_id' -> 'TextureId' + - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. + - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! + - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! + - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. + - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). + - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. + - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence + - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! + - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). + - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). + - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. + - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. + - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). + - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. + - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API + - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. + - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. + - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. + - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing + - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. + - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) + - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. + - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. + - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. + - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior + - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() + - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) + - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. + - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. + (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. + this sequence: + const void* png_data; + unsigned int png_size; + ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); + // + became: + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + // + io.Fonts->TexID = (your_texture_identifier); + you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. + it is now recommended that you sample the font texture with bilinear interpolation. + (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. + (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) + (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets + - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) + - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) + - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility + - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() + - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) + - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) + - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() + - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn + - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) + - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite + - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes + + + FREQUENTLY ASKED QUESTIONS (FAQ), TIPS + ====================================== + + Q: How can I help? + A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help! + - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time. + + Q: How do I update to a newer version of ImGui? + A: Overwrite the following files: + imgui.cpp + imgui.h + imgui_demo.cpp + imgui_draw.cpp + imgui_internal.h + stb_rect_pack.h + stb_textedit.h + stb_truetype.h + Don't overwrite imconfig.h if you have made modification to your copy. + If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. + Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. + Please report any issue to the GitHub page! + + Q: What is ImTextureID and how do I display an image? + A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function. + ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry! + It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc. + At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render. + Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing. + (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!) + To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions. + ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use. + It is your responsibility to get textures uploaded to your GPU. + + Q: I integrated ImGui in my engine and the text or lines are blurry.. + A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). + Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. + + Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). + + Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes) + A: Yes. A primer on the use of labels/IDs in ImGui.. + + - Elements that are not clickable, such as Text() items don't need an ID. + + - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget). + to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer. + + Button("OK"); // Label = "OK", ID = hash of "OK" + Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel" + + - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows + or in two different locations of a tree. + + - If you have a same ID twice in the same location, you'll have a conflict: + + Button("OK"); + Button("OK"); // ID collision! Both buttons will be treated as the same. + + Fear not! this is easy to solve and there are many ways to solve it! + + - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. + use "##" to pass a complement to the ID that won't be visible to the end-user: + + Button("Play"); // Label = "Play", ID = hash of "Play" + Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above) + Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above) + + - If you want to completely hide the label, but still need an ID: + + Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!) + + - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. + For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously) + Use "###" to pass a label that isn't part of ID: + + Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" + Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) + + sprintf(buf, "My game (%f FPS)###MyGame"); + Begin(buf); // Variable label, ID = hash of "MyGame" + + - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. + This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements. + You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack! + + for (int i = 0; i < 100; i++) + { + PushID(i); + Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique) + PopID(); + } + + for (int i = 0; i < 100; i++) + { + MyObject* obj = Objects[i]; + PushID(obj); + Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique) + PopID(); + } + + for (int i = 0; i < 100; i++) + { + MyObject* obj = Objects[i]; + PushID(obj->Name); + Button("Click"); // Label = "Click", ID = hash of string + "label" (unique) + PopID(); + } + + - More example showing that you can stack multiple prefixes into the ID stack: + + Button("Click"); // Label = "Click", ID = hash of "Click" + PushID("node"); + Button("Click"); // Label = "Click", ID = hash of "node" + "Click" + PushID(my_ptr); + Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click" + PopID(); + PopID(); + + - Tree nodes implicitly creates a scope for you by calling PushID(). + + Button("Click"); // Label = "Click", ID = hash of "Click" + if (TreeNode("node")) + { + Button("Click"); // Label = "Click", ID = hash of "node" + "Click" + TreePop(); + } + + - When working with trees, ID are used to preserve the open/close state of each tree node. + Depending on your use cases you may want to use strings, indices or pointers as ID. + e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change. + e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense! + + Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine. + When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application. + When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available. + ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow(). + (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically have 'io.WantcaptureKeyboard=false'. + Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.) + + Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13) + A: Use the font atlas to load the TTF file you want: + + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + + Q: How can I easily use icons in my application? + A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. + Read 'How can I load multiple fonts?' and the file 'extra_fonts/README.txt' for instructions. + + Q: How can I load multiple fonts? + A: Use the font atlas to pack them into a single texture: + (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.) + + ImGuiIO& io = ImGui::GetIO(); + ImFont* font0 = io.Fonts->AddFontDefault(); + ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + // the first loaded font gets used by default + // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime + + // Options + ImFontConfig config; + config.OversampleH = 3; + config.OversampleV = 1; + config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up + config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config); + + // Combine multiple fonts into one (e.g. for icon fonts) + ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; + ImFontConfig config; + config.MergeMode = true; + io.Fonts->AddFontDefault(); + io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs + + Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? + A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. + All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will not work. + In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. + You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code. + + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application + + As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. + + Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha, + then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. + + - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. + - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" + - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) + - tip: you can call Render() multiple times (e.g for VR renders). + - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui! + + + ISSUES & TODO-LIST + ================== + Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues + The list below consist mostly of ideas noted down before they are requested/discussed by users (at which point it usually moves to the github) + + - doc: add a proper documentation+regression testing system (#435) + - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. + - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690) + - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. + - window: allow resizing of child windows (possibly given min/max for each axis?) + - window: background options for child windows, border option (disable rounding) + - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip) + - window: resizing from any sides? + mouse cursor directives for app. +!- window: begin with *p_open == false should return false. + - window: get size/pos helpers given names (see discussion in #249) + - window: a collapsed window can be stuck behind the main menu bar? + - window: when window is small, prioritize resize button over close button. + - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later. + - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. + - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd. + - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). +!- scrolling: allow immediately effective change of scroll if we haven't appended items yet + - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) + - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. + - widgets: clean up widgets internal toward exposing everything. + - widgets: add disabled and read-only modes (#211) + - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. +!- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows). + - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes + - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? + - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. + - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) + - input text: expose CursorPos in char filter event (#816) + - input text: flag to disable live update of the user buffer (also applies to float/int text input) + - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text? + - input text: add ImGuiInputTextFlags_EnterToApply? (off #218) + - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725) + - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). + - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200) + - input text multi-line: line numbers? status bar? (follow up on #200) + - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725) + - input text multi-line: better horizontal scrolling support (#383, #1224) + - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. + - input number: optional range min/max for Input*() functions + - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) + - input number: use mouse wheel to step up/down + - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. + - button: provide a button that looks framed. + - text: proper alignment options + - image/image button: misalignment on padded/bordered button? + - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? + - layout: horizontal layout helper (#97) + - layout: horizontal flow until no space left (#404) + - layout: more generic alignment state (left/right/centered) for single items? + - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. + - layout: BeginGroup() needs a border option. + - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125) + - columns: add a conditional parameter to SetColumnOffset() (#513, #125) + - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) + - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125) + - columns: user specify columns size (#513, #125) + - columns: flag to add horizontal separator above/below? + - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) + - combo: sparse combo boxes (via function call?) / iterators + - combo: contents should extends to fit label if combo widget is small + - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203) + - listbox: multiple selection + - listbox: user may want to initial scroll to focus on the one selected value? + - listbox: keyboard navigation. + - listbox: scrolling should track modified selection. +!- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) + - popups: add variant using global identifier similar to Begin/End (#402) + - popups: border options. richer api like BeginChild() perhaps? (#197) + - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred button" and may teleport when moving mouse + - menus: local shortcuts, global shortcuts (#456, #126) + - menus: icons + - menus: menubars: some sort of priority / effect of main menu-bar on desktop size? + - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely + - statusbar: add a per-window status bar helper similar to what menubar does. + - tabs (#261, #351) + - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y) +!- color: the color helpers/typing is a mess and needs sorting out. + - color: add a better color picker (#346) + - node/graph editor (#306) + - pie menus patterns (#434) + - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479) + - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals) + - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) + - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) + - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) + - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() + - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). + - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. + - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) + - slider & drag: int data passing through a float + - drag float: up/down axis + - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) + - tree node / optimization: avoid formatting when clipped. + - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling. + - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? + - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits? + - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) + - tree node: tweak color scheme to distinguish headers from selected tree node (#581) + - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) + - settings: write more decent code to allow saving/loading new fields + - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file + - style: add window shadows. + - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. + - style: color-box not always square? + - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc. + - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation). + - style: global scale setting. + - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle + - text: simple markup language for color change? + - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. + - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance + - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback. + - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) + - font: fix AddRemapChar() to work before font has been built. + - log: LogButtons() options for specifying depth and/or hiding depth slider + - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) + - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) + - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. + - filters: set a current filter that tree node can automatically query to hide themselves + - filters: handle wildcards (with implicit leading/trailing *), regexps + - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) +!- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing + - keyboard: full keyboard navigation and focus. (#323) + - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) + - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) + - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71) + - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style). + - input: support track pad style scrolling & slider edit. + - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) + - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? + - misc: provide HoveredTime and ActivatedTime to ease the creation of animations. + - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438) + - style editor: color child window height expressed in multiple of line height. + - remote: make a system like RemoteImGui first-class citizen/project (#75) + - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?) + - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. + - examples: directx9: save/restore device state more thoroughly. + - examples: window minimize, maximize (#583) + - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) + - optimization: use another hash function than crc32, e.g. FNV1a + - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? + - optimization: turn some the various stack vectors into statically-sized arrays + - optimization: better clipping for multi-component widgets +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + +#include // toupper, isprint +#include // NULL, malloc, free, qsort, atoi +#include // vsnprintf, sscanf, printf +#include // INT_MIN, INT_MAX +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#endif + +// Clang warnings with -Weverything +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. +#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' // +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers +#endif + +//------------------------------------------------------------------------- +// Forward Declarations +//------------------------------------------------------------------------- + +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); + +static void PushMultiItemsWidths(int components, float w_full = 0.0f); +static float GetDraggedColumnOffset(int column_index); + +static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); + +static ImFont* GetDefaultFont(); +static void SetCurrentFont(ImFont* font); +static void SetCurrentWindow(ImGuiWindow* window); +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond); +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond); +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond); +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); +static inline bool IsWindowContentHoverable(ImGuiWindow* window); +static void ClearSetNextWindowData(); +static void CheckStacksSize(ImGuiWindow* window, bool write); +static void Scrollbar(ImGuiWindow* window, bool horizontal); + +static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list); +static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window); +static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window); + +static ImGuiIniData* FindWindowSettings(const char* name); +static ImGuiIniData* AddWindowSettings(const char* name); +static void LoadIniSettingsFromDisk(const char* ini_filename); +static void SaveIniSettingsToDisk(const char* ini_filename); +static void MarkIniSettingsDirty(); + +static void PushColumnClipRect(int column_index = -1); +static ImRect GetVisibleRect(); + +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags); +static void CloseInactivePopups(); +static void ClosePopupToLevel(int remaining); +static void ClosePopup(ImGuiID id); +static bool IsPopupOpen(ImGuiID id); +static ImGuiWindow* GetFrontMostModalRootWindow(); +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid); + +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data); +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size); +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size); +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2); +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format); + +//----------------------------------------------------------------------------- +// Platform dependent default implementations +//----------------------------------------------------------------------------- + +static const char* GetClipboardTextFn_DefaultImpl(void* user_data); +static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +// Default font atlas storage . +// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable. +static ImFontAtlas GImDefaultFontAtlas; + +// Default context storage + current context pointer. +// Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext() +// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by: +// - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts) +// - or: Changing this variable to be TLS. You may #define GImGui in imconfig.h for further custom hackery. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 +#ifndef GImGui +static ImGuiContext GImDefaultContext; +ImGuiContext* GImGui = &GImDefaultContext; +#endif + +//----------------------------------------------------------------------------- +// User facing structures +//----------------------------------------------------------------------------- + +ImGuiStyle::ImGuiStyle() +{ + Alpha = 1.0f; // Global alpha applies to everything in ImGui + WindowPadding = ImVec2(8,8); // Padding within a window + WindowMinSize = ImVec2(32,32); // Minimum window size + WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text + ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows + FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). + ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns + ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar + GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. + DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. + DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. + AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + + Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); + Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); + Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); + Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f); + Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input + Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); + Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); + Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); + Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); + Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); + Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); + Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); + Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); + Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); + Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); + Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); + Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); + Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); + Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); + Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); + Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); + Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); + Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); + Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f); + Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f); + Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); + Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); + Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); + Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); + Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); + Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); + Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); + Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); + Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); + Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); +} + +ImGuiIO::ImGuiIO() +{ + // Most fields are initialized with zero + memset(this, 0, sizeof(*this)); + + DisplaySize = ImVec2(-1.0f, -1.0f); + DeltaTime = 1.0f/60.0f; + IniSavingRate = 5.0f; + IniFilename = "imgui.ini"; + LogFilename = "imgui_log.txt"; + Fonts = &GImDefaultFontAtlas; + FontGlobalScale = 1.0f; + FontDefault = NULL; + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); + MousePos = ImVec2(-1,-1); + MousePosPrev = ImVec2(-1,-1); + MouseDoubleClickTime = 0.30f; + MouseDoubleClickMaxDist = 6.0f; + MouseDragThreshold = 6.0f; + for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) + MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) + KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; + for (int i = 0; i < ImGuiKey_COUNT; i++) + KeyMap[i] = -1; + KeyRepeatDelay = 0.250f; + KeyRepeatRate = 0.050f; + UserData = NULL; + + // User functions + RenderDrawListsFn = NULL; + MemAllocFn = malloc; + MemFreeFn = free; + GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations + SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; + ClipboardUserData = NULL; + ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; + + // Set OS X style defaults based on __APPLE__ compile time flag +#ifdef __APPLE__ + OSXBehaviors = true; +#endif +} + +// Pass in translated ASCII characters for text input. +// - with glfw you can get those from the callback set in glfwSetCharCallback() +// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +void ImGuiIO::AddInputCharacter(ImWchar c) +{ + const int n = ImStrlenW(InputCharacters); + if (n + 1 < IM_ARRAYSIZE(InputCharacters)) + { + InputCharacters[n] = c; + InputCharacters[n+1] = '\0'; + } +} + +void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) +{ + // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more + const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar); + ImWchar wchars[wchars_buf_len]; + ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL); + for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++) + AddInputCharacter(wchars[i]); +} + +//----------------------------------------------------------------------------- +// HELPERS +//----------------------------------------------------------------------------- + +#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose +#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 + +// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" +#else +#define IM_NEWLINE "\n" +#endif + +bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c) +{ + bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + return ((b1 == b2) && (b2 == b3)); +} + +int ImStricmp(const char* str1, const char* str2) +{ + int d; + while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } + return d; +} + +int ImStrnicmp(const char* str1, const char* str2, int count) +{ + int d = 0; + while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } + return d; +} + +void ImStrncpy(char* dst, const char* src, int count) +{ + if (count < 1) return; + strncpy(dst, src, (size_t)count); + dst[count-1] = 0; +} + +char* ImStrdup(const char *str) +{ + size_t len = strlen(str) + 1; + void* buff = ImGui::MemAlloc(len); + return (char*)memcpy(buff, (const void*)str, len); +} + +int ImStrlenW(const ImWchar* str) +{ + int n = 0; + while (*str++) n++; + return n; +} + +const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line +{ + while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') + buf_mid_line--; + return buf_mid_line; +} + +const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) +{ + if (!needle_end) + needle_end = needle + strlen(needle); + + const char un0 = (char)toupper(*needle); + while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) + { + if (toupper(*haystack) == un0) + { + const char* b = needle + 1; + for (const char* a = haystack + 1; b < needle_end; a++, b++) + if (toupper(*a) != toupper(*b)) + break; + if (b == needle_end) + return haystack; + } + haystack++; + } + return NULL; +} + + +// MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). +// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. +int ImFormatString(char* buf, int buf_size, const char* fmt, ...) +{ + IM_ASSERT(buf_size > 0); + va_list args; + va_start(args, fmt); + int w = vsnprintf(buf, buf_size, fmt, args); + va_end(args); + if (w == -1 || w >= buf_size) + w = buf_size - 1; + buf[w] = 0; + return w; +} + +int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args) +{ + IM_ASSERT(buf_size > 0); + int w = vsnprintf(buf, buf_size, fmt, args); + if (w == -1 || w >= buf_size) + w = buf_size - 1; + buf[w] = 0; + return w; +} + +// Pass data_size==0 for zero-terminated strings +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImU32 ImHash(const void* data, int data_size, ImU32 seed) +{ + static ImU32 crc32_lut[256] = { 0 }; + if (!crc32_lut[1]) + { + const ImU32 polynomial = 0xEDB88320; + for (ImU32 i = 0; i < 256; i++) + { + ImU32 crc = i; + for (ImU32 j = 0; j < 8; j++) + crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); + crc32_lut[i] = crc; + } + } + + seed = ~seed; + ImU32 crc = seed; + const unsigned char* current = (const unsigned char*)data; + + if (data_size > 0) + { + // Known size + while (data_size--) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; + } + else + { + // Zero-terminated string + while (unsigned char c = *current++) + { + // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. + // Because this syntax is rarely used we are optimizing for the common case. + // - If we reach ### in the string we discard the hash so far and reset to the seed. + // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. + if (c == '#' && current[0] == '#' && current[1] == '#') + crc = seed; + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; + } + } + return ~crc; +} + +//----------------------------------------------------------------------------- +// ImText* helpers +//----------------------------------------------------------------------------- + +// Convert UTF-8 to 32-bits character, process single character input. +// Based on stb_from_utf8() from github.com/nothings/stb/ +// We handle UTF-8 decoding error by skipping forward. +int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) +{ + unsigned int c = (unsigned int)-1; + const unsigned char* str = (const unsigned char*)in_text; + if (!(*str & 0x80)) + { + c = (unsigned int)(*str++); + *out_char = c; + return 1; + } + if ((*str & 0xe0) == 0xc0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 2) return 1; + if (*str < 0xc2) return 2; + c = (unsigned int)((*str++ & 0x1f) << 6); + if ((*str & 0xc0) != 0x80) return 2; + c += (*str++ & 0x3f); + *out_char = c; + return 2; + } + if ((*str & 0xf0) == 0xe0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 3) return 1; + if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; + if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x0f) << 12); + if ((*str & 0xc0) != 0x80) return 3; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 3; + c += (*str++ & 0x3f); + *out_char = c; + return 3; + } + if ((*str & 0xf8) == 0xf0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 4) return 1; + if (*str > 0xf4) return 4; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; + if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x07) << 18); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 12); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 4; + c += (*str++ & 0x3f); + // utf-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xFFFFF800) == 0xD800) return 4; + *out_char = c; + return 4; + } + *out_char = 0; + return 0; +} + +int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) +{ + ImWchar* buf_out = buf; + ImWchar* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + if (in_text_remaining) + *in_text_remaining = in_text; + return (int)(buf_out - buf); +} + +int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c >= 0xdc00 && c < 0xe000) + { + return 0; + } + if (c >= 0xd800 && c < 0xdc00) + { + if (buf_size < 4) return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c ) & 0x3f)); + return 4; + } + //else if (c < 0x10000) + { + if (buf_size < 3) return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c ) & 0x3f)); + return 3; + } +} + +static inline int ImTextCountUtf8BytesFromChar(unsigned int c) +{ + if (c < 0x80) return 1; + if (c < 0x800) return 2; + if (c >= 0xdc00 && c < 0xe000) return 0; + if (c >= 0xd800 && c < 0xdc00) return 4; + return 3; +} + +int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) +{ + char* buf_out = buf; + const char* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + *buf_out++ = (char)c; + else + buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); + } + *buf_out = 0; + return (int)(buf_out - buf); +} + +int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + bytes_count++; + else + bytes_count += ImTextCountUtf8BytesFromChar(c); + } + return bytes_count; +} + +ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) +{ + float s = 1.0f/255.0f; + return ImVec4( + ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); +} + +ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) +{ + ImU32 out; + out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; + return out; +} + +ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) +{ + ImVec4 c = GImGui->Style.Colors[idx]; + c.w *= GImGui->Style.Alpha * alpha_mul; + return ColorConvertFloat4ToU32(c); +} + +ImU32 ImGui::GetColorU32(const ImVec4& col) +{ + ImVec4 c = col; + c.w *= GImGui->Style.Alpha; + return ColorConvertFloat4ToU32(c); +} + +// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv +void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) +{ + float K = 0.f; + if (g < b) + { + const float tmp = g; g = b; b = tmp; + K = -1.f; + } + if (r < g) + { + const float tmp = r; r = g; g = tmp; + K = -2.f / 6.f - K; + } + + const float chroma = r - (g < b ? g : b); + out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); + out_s = chroma / (r + 1e-20f); + out_v = r; +} + +// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +// also http://en.wikipedia.org/wiki/HSL_and_HSV +void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) +{ + if (s == 0.0f) + { + // gray + out_r = out_g = out_b = v; + return; + } + + h = fmodf(h, 1.0f) / (60.0f/360.0f); + int i = (int)h; + float f = h - (float)i; + float p = v * (1.0f - s); + float q = v * (1.0f - s * f); + float t = v * (1.0f - s * (1.0f - f)); + + switch (i) + { + case 0: out_r = v; out_g = t; out_b = p; break; + case 1: out_r = q; out_g = v; out_b = p; break; + case 2: out_r = p; out_g = v; out_b = t; break; + case 3: out_r = p; out_g = q; out_b = v; break; + case 4: out_r = t; out_g = p; out_b = v; break; + case 5: default: out_r = v; out_g = p; out_b = q; break; + } +} + +FILE* ImFileOpen(const char* filename, const char* mode) +{ +#if defined(_WIN32) && !defined(__CYGWIN__) + // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) + const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; + const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; + ImVector buf; + buf.resize(filename_wsize + mode_wsize); + ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); + ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); + return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); +#else + return fopen(filename, mode); +#endif +} + +// Load file content into memory +// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() +void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes) +{ + IM_ASSERT(filename && file_open_mode); + if (out_file_size) + *out_file_size = 0; + + FILE* f; + if ((f = ImFileOpen(filename, file_open_mode)) == NULL) + return NULL; + + long file_size_signed; + if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) + { + fclose(f); + return NULL; + } + + int file_size = (int)file_size_signed; + void* file_data = ImGui::MemAlloc(file_size + padding_bytes); + if (file_data == NULL) + { + fclose(f); + return NULL; + } + if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size) + { + fclose(f); + ImGui::MemFree(file_data); + return NULL; + } + if (padding_bytes > 0) + memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); + + fclose(f); + if (out_file_size) + *out_file_size = file_size; + + return file_data; +} + +//----------------------------------------------------------------------------- +// ImGuiStorage +//----------------------------------------------------------------------------- + +// Helper: Key->value storage +void ImGuiStorage::Clear() +{ + Data.clear(); +} + +// std::lower_bound but without the bullshit +static ImVector::iterator LowerBound(ImVector& data, ImGuiID key) +{ + ImVector::iterator first = data.begin(); + ImVector::iterator last = data.end(); + int count = (int)(last - first); + while (count > 0) + { + int count2 = count / 2; + ImVector::iterator mid = first + count2; + if (mid->key < key) + { + first = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } + } + return first; +} + +int ImGuiStorage::GetInt(ImGuiID key, int default_val) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_i; +} + +bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const +{ + return GetInt(key, default_val ? 1 : 0) != 0; +} + +float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_f; +} + +void* ImGuiStorage::GetVoidPtr(ImGuiID key) const +{ + ImVector::iterator it = LowerBound(const_cast&>(Data), key); + if (it == Data.end() || it->key != key) + return NULL; + return it->val_p; +} + +// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. +int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_i; +} + +bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) +{ + return (bool*)GetIntRef(key, default_val ? 1 : 0); +} + +float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_f; +} + +void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_p; +} + +// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) +void ImGuiStorage::SetInt(ImGuiID key, int val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_i = val; +} + +void ImGuiStorage::SetBool(ImGuiID key, bool val) +{ + SetInt(key, val ? 1 : 0); +} + +void ImGuiStorage::SetFloat(ImGuiID key, float val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_f = val; +} + +void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) +{ + ImVector::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + { + Data.insert(it, Pair(key, val)); + return; + } + it->val_p = val; +} + +void ImGuiStorage::SetAllInt(int v) +{ + for (int i = 0; i < Data.Size; i++) + Data[i].val_i = v; +} + +//----------------------------------------------------------------------------- +// ImGuiTextFilter +//----------------------------------------------------------------------------- + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) +{ + if (default_filter) + { + ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); + Build(); + } + else + { + InputBuf[0] = 0; + CountGrep = 0; + } +} + +bool ImGuiTextFilter::Draw(const char* label, float width) +{ + if (width != 0.0f) + ImGui::PushItemWidth(width); + bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + if (width != 0.0f) + ImGui::PopItemWidth(); + if (value_changed) + Build(); + return value_changed; +} + +void ImGuiTextFilter::TextRange::split(char separator, ImVector& out) +{ + out.resize(0); + const char* wb = b; + const char* we = wb; + while (we < e) + { + if (*we == separator) + { + out.push_back(TextRange(wb, we)); + wb = we + 1; + } + we++; + } + if (wb != we) + out.push_back(TextRange(wb, we)); +} + +void ImGuiTextFilter::Build() +{ + Filters.resize(0); + TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); + input_range.split(',', Filters); + + CountGrep = 0; + for (int i = 0; i != Filters.Size; i++) + { + Filters[i].trim_blanks(); + if (Filters[i].empty()) + continue; + if (Filters[i].front() != '-') + CountGrep += 1; + } +} + +bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const +{ + if (Filters.empty()) + return true; + + if (text == NULL) + text = ""; + + for (int i = 0; i != Filters.Size; i++) + { + const TextRange& f = Filters[i]; + if (f.empty()) + continue; + if (f.front() == '-') + { + // Subtract + if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) + return false; + } + else + { + // Grep + if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) + return true; + } + } + + // Implicit * grep + if (CountGrep == 0) + return true; + + return false; +} + +//----------------------------------------------------------------------------- +// ImGuiTextBuffer +//----------------------------------------------------------------------------- + +// On some platform vsnprintf() takes va_list by reference and modifies it. +// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. +#ifndef va_copy +#define va_copy(dest, src) (dest = src) +#endif + +// Helper: Text buffer for logging/accumulating text +void ImGuiTextBuffer::appendv(const char* fmt, va_list args) +{ + va_list args_copy; + va_copy(args_copy, args); + + int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. + if (len <= 0) + return; + + const int write_off = Buf.Size; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) + { + int double_capacity = Buf.Capacity * 2; + Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); + } + + Buf.resize(needed_sz); + ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy); +} + +void ImGuiTextBuffer::append(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + appendv(fmt, args); + va_end(args); +} + +//----------------------------------------------------------------------------- +// ImGuiSimpleColumns +//----------------------------------------------------------------------------- + +ImGuiSimpleColumns::ImGuiSimpleColumns() +{ + Count = 0; + Spacing = Width = NextWidth = 0.0f; + memset(Pos, 0, sizeof(Pos)); + memset(NextWidths, 0, sizeof(NextWidths)); +} + +void ImGuiSimpleColumns::Update(int count, float spacing, bool clear) +{ + IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); + Count = count; + Width = NextWidth = 0.0f; + Spacing = spacing; + if (clear) memset(NextWidths, 0, sizeof(NextWidths)); + for (int i = 0; i < Count; i++) + { + if (i > 0 && NextWidths[i] > 0.0f) + Width += Spacing; + Pos[i] = (float)(int)Width; + Width += NextWidths[i]; + NextWidths[i] = 0.0f; + } +} + +float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double +{ + NextWidth = 0.0f; + NextWidths[0] = ImMax(NextWidths[0], w0); + NextWidths[1] = ImMax(NextWidths[1], w1); + NextWidths[2] = ImMax(NextWidths[2], w2); + for (int i = 0; i < 3; i++) + NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); + return ImMax(Width, NextWidth); +} + +float ImGuiSimpleColumns::CalcExtraSpace(float avail_w) +{ + return ImMax(0.0f, avail_w - Width); +} + +//----------------------------------------------------------------------------- +// ImGuiListClipper +//----------------------------------------------------------------------------- + +static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) +{ + // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor. + // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions? + ImGui::SetCursorPosY(pos_y); + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage. + window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + if (window->DC.ColumnsCount > 1) + window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly +} + +// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 +// Use case B: Begin() called from constructor with items_height>0 +// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. +void ImGuiListClipper::Begin(int count, float items_height) +{ + StartPosY = ImGui::GetCursorPosY(); + ItemsHeight = items_height; + ItemsCount = count; + StepNo = 0; + DisplayEnd = DisplayStart = -1; + if (ItemsHeight > 0.0f) + { + ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display + if (DisplayStart > 0) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor + StepNo = 2; + } +} + +void ImGuiListClipper::End() +{ + if (ItemsCount < 0) + return; + // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. + if (ItemsCount < INT_MAX) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + ItemsCount = -1; + StepNo = 3; +} + +bool ImGuiListClipper::Step() +{ + if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) + { + ItemsCount = -1; + return false; + } + if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. + { + DisplayStart = 0; + DisplayEnd = 1; + StartPosY = ImGui::GetCursorPosY(); + StepNo = 1; + return true; + } + if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. + { + if (ItemsCount == 1) { ItemsCount = -1; return false; } + float items_height = ImGui::GetCursorPosY() - StartPosY; + IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically + Begin(ItemsCount-1, items_height); + DisplayStart++; + DisplayEnd++; + StepNo = 3; + return true; + } + if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + { + IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); + StepNo = 3; + return true; + } + if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. + End(); + return false; +} + +//----------------------------------------------------------------------------- +// ImGuiWindow +//----------------------------------------------------------------------------- + +ImGuiWindow::ImGuiWindow(const char* name) +{ + Name = ImStrdup(name); + ID = ImHash(name, 0); + IDStack.push_back(ID); + MoveId = GetID("#MOVE"); + + Flags = 0; + OrderWithinParent = 0; + PosFloat = Pos = ImVec2(0.0f, 0.0f); + Size = SizeFull = ImVec2(0.0f, 0.0f); + SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); + WindowPadding = ImVec2(0.0f, 0.0f); + Scroll = ImVec2(0.0f, 0.0f); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + ScrollbarX = ScrollbarY = false; + ScrollbarSizes = ImVec2(0.0f, 0.0f); + BorderSize = 0.0f; + Active = WasActive = false; + Accessed = false; + Collapsed = false; + SkipItems = false; + BeginCount = 0; + PopupId = 0; + AutoFitFramesX = AutoFitFramesY = -1; + AutoFitOnlyGrows = false; + AutoPosLastDirection = -1; + HiddenFrames = 0; + SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing; + SetWindowPosCenterWanted = false; + + LastFrameActive = -1; + ItemWidthDefault = 0.0f; + FontWindowScale = 1.0f; + + DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); + IM_PLACEMENT_NEW(DrawList) ImDrawList(); + DrawList->_OwnerName = Name; + RootWindow = NULL; + RootNonPopupWindow = NULL; + ParentWindow = NULL; + + FocusIdxAllCounter = FocusIdxTabCounter = -1; + FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; + FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; +} + +ImGuiWindow::~ImGuiWindow() +{ + DrawList->~ImDrawList(); + ImGui::MemFree(DrawList); + DrawList = NULL; + ImGui::MemFree(Name); + Name = NULL; +} + +ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed); + ImGui::KeepAliveID(id); + return id; +} + +ImGuiID ImGuiWindow::GetID(const void* ptr) +{ + ImGuiID seed = IDStack.back(); + ImGuiID id = ImHash(&ptr, sizeof(void*), seed); + ImGui::KeepAliveID(id); + return id; +} + +ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + return ImHash(str, str_end ? (int)(str_end - str) : 0, seed); +} + +//----------------------------------------------------------------------------- +// Internal API exposed in imgui_internal.h +//----------------------------------------------------------------------------- + +static void SetCurrentWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow = window; + if (window) + g.FontSize = window->CalcFontSize(); +} + +ImGuiWindow* ImGui::GetParentWindow() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentWindowStack.Size >= 2); + return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2]; +} + +void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.ActiveId = id; + g.ActiveIdAllowOverlap = false; + g.ActiveIdIsJustActivated = true; + if (id) + g.ActiveIdIsAlive = true; + g.ActiveIdWindow = window; +} + +void ImGui::ClearActiveID() +{ + SetActiveID(0, NULL); +} + +void ImGui::SetHoveredID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.HoveredId = id; + g.HoveredIdAllowOverlap = false; +} + +void ImGui::KeepAliveID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + g.ActiveIdIsAlive = true; +} + +// Advance cursor given item size for layout. +void ImGui::ItemSize(const ImVec2& size, float text_offset_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // Always align ourselves on pixel boundaries + ImGuiContext& g = *GImGui; + const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); + const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); + window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); + window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); + + //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug + + window->DC.PrevLineHeight = line_height; + window->DC.PrevLineTextBaseOffset = text_base_offset; + window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; +} + +void ImGui::ItemSize(const ImRect& bb, float text_offset_y) +{ + ItemSize(bb.GetSize(), text_offset_y); +} + +// Declare item bounding box for clipping and interaction. +// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +// declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). +bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.LastItemId = id ? *id : 0; + window->DC.LastItemRect = bb; + window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; + if (IsClippedEx(bb, id, false)) + return false; + + // This is a sensible default, but widgets are free to override it after calling ItemAdd() + ImGuiContext& g = *GImGui; + if (IsMouseHoveringRect(bb.Min, bb.Max)) + { + // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background) + // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() + window->DC.LastItemHoveredRect = true; + if (g.HoveredRootWindow == window->RootWindow) + if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId)) + if (IsWindowContentHoverable(window)) + window->DC.LastItemHoveredAndUsable = true; + } + + return true; +} + +bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + + if (!bb.Overlaps(window->ClipRect)) + if (!id || *id != GImGui->ActiveId) + if (clip_even_when_logged || !g.LogEnabled) + return true; + return false; +} + +// NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic. +bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs) +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap) + { + ImGuiWindow* window = GetCurrentWindowRead(); + if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow)) + if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max)) + if (IsWindowContentHoverable(g.HoveredRootWindow)) + return true; + } + return false; +} + +bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop) +{ + ImGuiContext& g = *GImGui; + + const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus; + window->FocusIdxAllCounter++; + if (allow_keyboard_focus) + window->FocusIdxTabCounter++; + + // Process keyboard input at this point: TAB, Shift-TAB switch focus + // We can always TAB out of a widget that doesn't allow tabbing in. + if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) + { + // Modulo on index will be applied at the end of frame once we've got the total counter of items. + window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); + } + + if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) + return true; + + if (allow_keyboard_focus) + if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) + return true; + + return false; +} + +void ImGui::FocusableItemUnregister(ImGuiWindow* window) +{ + window->FocusIdxAllCounter--; + window->FocusIdxTabCounter--; +} + +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) +{ + ImGuiContext& g = *GImGui; + ImVec2 content_max; + if (size.x < 0.0f || size.y < 0.0f) + content_max = g.CurrentWindow->Pos + GetContentRegionMax(); + if (size.x <= 0.0f) + size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; + if (size.y <= 0.0f) + size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; + return size; +} + +float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) +{ + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiWindow* window = GetCurrentWindowRead(); + if (wrap_pos_x == 0.0f) + wrap_pos_x = GetContentRegionMax().x + window->Pos.x; + else if (wrap_pos_x > 0.0f) + wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + + return ImMax(wrap_pos_x - pos.x, 1.0f); +} + +//----------------------------------------------------------------------------- + +void* ImGui::MemAlloc(size_t sz) +{ + GImGui->IO.MetricsAllocs++; + return GImGui->IO.MemAllocFn(sz); +} + +void ImGui::MemFree(void* ptr) +{ + if (ptr) GImGui->IO.MetricsAllocs--; + return GImGui->IO.MemFreeFn(ptr); +} + +const char* ImGui::GetClipboardText() +{ + return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; +} + +void ImGui::SetClipboardText(const char* text) +{ + if (GImGui->IO.SetClipboardTextFn) + GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); +} + +const char* ImGui::GetVersion() +{ + return IMGUI_VERSION; +} + +// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself +// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module +ImGuiContext* ImGui::GetCurrentContext() +{ + return GImGui; +} + +void ImGui::SetCurrentContext(ImGuiContext* ctx) +{ +#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC + IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. +#else + GImGui = ctx; +#endif +} + +ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*)) +{ + if (!malloc_fn) malloc_fn = malloc; + ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext)); + IM_PLACEMENT_NEW(ctx) ImGuiContext(); + ctx->IO.MemAllocFn = malloc_fn; + ctx->IO.MemFreeFn = free_fn ? free_fn : free; + return ctx; +} + +void ImGui::DestroyContext(ImGuiContext* ctx) +{ + void (*free_fn)(void*) = ctx->IO.MemFreeFn; + ctx->~ImGuiContext(); + free_fn(ctx); + if (GImGui == ctx) + SetCurrentContext(NULL); +} + +ImGuiIO& ImGui::GetIO() +{ + return GImGui->IO; +} + +ImGuiStyle& ImGui::GetStyle() +{ + return GImGui->Style; +} + +// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() +ImDrawData* ImGui::GetDrawData() +{ + return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL; +} + +float ImGui::GetTime() +{ + return GImGui->Time; +} + +int ImGui::GetFrameCount() +{ + return GImGui->FrameCount; +} + +void ImGui::NewFrame() +{ + ImGuiContext& g = *GImGui; + + // Check user data + IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues) + IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f); + IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting + + if (!g.Initialized) + { + // Initialize on first frame + g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); + IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer(); + + IM_ASSERT(g.Settings.empty()); + LoadIniSettingsFromDisk(g.IO.IniFilename); + g.Initialized = true; + } + + SetCurrentFont(GetDefaultFont()); + IM_ASSERT(g.Font->IsLoaded()); + + g.Time += g.IO.DeltaTime; + g.FrameCount += 1; + g.TooltipOverrideCount = 0; + g.OverlayDrawList.Clear(); + g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); + g.OverlayDrawList.PushClipRectFullScreen(); + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it + g.RenderDrawData.Valid = false; + g.RenderDrawData.CmdLists = NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0; + + // Update inputs state + if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) + g.IO.MousePos = ImVec2(-9999.0f, -9999.0f); + if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta + g.IO.MouseDelta = ImVec2(0.0f, 0.0f); + else + g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; + g.IO.MousePosPrev = g.IO.MousePos; + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + { + g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; + g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; + g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; + g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; + g.IO.MouseDoubleClicked[i] = false; + if (g.IO.MouseClicked[i]) + { + if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) + { + if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) + g.IO.MouseDoubleClicked[i] = true; + g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click + } + else + { + g.IO.MouseClickedTime[i] = g.Time; + } + g.IO.MouseClickedPos[i] = g.IO.MousePos; + g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; + } + else if (g.IO.MouseDown[i]) + { + g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i])); + } + } + memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) + g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; + + // Calculate frame-rate for the user, as a purely luxurious feature + g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; + g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; + g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); + g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); + + // Clear reference to active widget if the widget isn't alive anymore + g.HoveredIdPreviousFrame = g.HoveredId; + g.HoveredId = 0; + g.HoveredIdAllowOverlap = false; + if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) + ClearActiveID(); + g.ActiveIdPreviousFrame = g.ActiveId; + g.ActiveIdIsAlive = false; + g.ActiveIdIsJustActivated = false; + + // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. + if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId) + { + KeepAliveID(g.MovedWindowMoveId); + IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow); + IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId); + if (g.IO.MouseDown[0]) + { + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow->PosFloat += g.IO.MouseDelta; + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings) && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)) + MarkIniSettingsDirty(); + } + FocusWindow(g.MovedWindow); + } + else + { + ClearActiveID(); + g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } + } + else + { + g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } + + // Delay saving settings so we don't spam disk too much + if (g.SettingsDirtyTimer > 0.0f) + { + g.SettingsDirtyTimer -= g.IO.DeltaTime; + if (g.SettingsDirtyTimer <= 0.0f) + SaveIniSettingsToDisk(g.IO.IniFilename); + } + + // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow + g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false); + if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow)) + g.HoveredRootWindow = g.HoveredWindow->RootWindow; + else + g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true); + + if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow()) + { + g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f); + ImGuiWindow* window = g.HoveredRootWindow; + while (window && window != modal_window) + window = window->ParentWindow; + if (!window) + g.HoveredRootWindow = g.HoveredWindow = NULL; + } + else + { + g.ModalWindowDarkeningRatio = 0.0f; + } + + // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application. + // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership. + int mouse_earliest_button_down = -1; + bool mouse_any_down = false; + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + { + if (g.IO.MouseClicked[i]) + g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); + mouse_any_down |= g.IO.MouseDown[i]; + if (g.IO.MouseDown[i]) + if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i]) + mouse_earliest_button_down = i; + } + bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; + if (g.CaptureMouseNextFrame != -1) + g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0); + else + g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty()); + g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0); + g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId); + g.MouseCursor = ImGuiMouseCursor_Arrow; + g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1; + g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default + + // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + if (!mouse_avail_to_imgui) + g.HoveredWindow = g.HoveredRootWindow = NULL; + + // Scale & Scrolling + if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed) + { + ImGuiWindow* window = g.HoveredWindow; + if (g.IO.KeyCtrl) + { + if (g.IO.FontAllowUserScaling) + { + // Zoom / Scale window + float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); + float scale = new_font_scale / window->FontWindowScale; + window->FontWindowScale = new_font_scale; + + const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; + window->Pos += offset; + window->PosFloat += offset; + window->Size *= scale; + window->SizeFull *= scale; + } + } + else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) + { + // Scroll + const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; + SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines); + } + } + + // Pressing TAB activate widget focus + // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. + if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false)) + g.FocusedWindow->FocusIdxTabRequestNext = 0; + + // Mark all windows as not visible + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + window->WasActive = window->Active; + window->Active = false; + window->Accessed = false; + } + + // Closing the focused window restore focus to the first active root window in descending z-order + if (g.FocusedWindow && !g.FocusedWindow->WasActive) + for (int i = g.Windows.Size-1; i >= 0; i--) + if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow)) + { + FocusWindow(g.Windows[i]); + break; + } + + // No window should be open at the beginning of the frame. + // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. + g.CurrentWindowStack.resize(0); + g.CurrentPopupStack.resize(0); + CloseInactivePopups(); + + // Create implicit window - we will only render it if the user has added something to it. + ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Debug"); +} + +// NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. +void ImGui::Shutdown() +{ + ImGuiContext& g = *GImGui; + + // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky. + g.IO.Fonts->Clear(); + + // Cleanup of other data are conditional on actually having used ImGui. + if (!g.Initialized) + return; + + SaveIniSettingsToDisk(g.IO.IniFilename); + + for (int i = 0; i < g.Windows.Size; i++) + { + g.Windows[i]->~ImGuiWindow(); + ImGui::MemFree(g.Windows[i]); + } + g.Windows.clear(); + g.WindowsSortBuffer.clear(); + g.CurrentWindow = NULL; + g.CurrentWindowStack.clear(); + g.FocusedWindow = NULL; + g.HoveredWindow = NULL; + g.HoveredRootWindow = NULL; + g.ActiveIdWindow = NULL; + g.MovedWindow = NULL; + for (int i = 0; i < g.Settings.Size; i++) + ImGui::MemFree(g.Settings[i].Name); + g.Settings.clear(); + g.ColorModifiers.clear(); + g.StyleModifiers.clear(); + g.FontStack.clear(); + g.OpenPopupStack.clear(); + g.CurrentPopupStack.clear(); + g.SetNextWindowSizeConstraintCallback = NULL; + g.SetNextWindowSizeConstraintCallbackUserData = NULL; + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.RenderDrawLists[i].clear(); + g.OverlayDrawList.ClearFreeMemory(); + g.ColorEditModeStorage.Clear(); + if (g.PrivateClipboard) + { + ImGui::MemFree(g.PrivateClipboard); + g.PrivateClipboard = NULL; + } + g.InputTextState.Text.clear(); + g.InputTextState.InitialText.clear(); + g.InputTextState.TempTextBuffer.clear(); + + if (g.LogFile && g.LogFile != stdout) + { + fclose(g.LogFile); + g.LogFile = NULL; + } + if (g.LogClipboard) + { + g.LogClipboard->~ImGuiTextBuffer(); + ImGui::MemFree(g.LogClipboard); + } + + g.Initialized = false; +} + +static ImGuiIniData* FindWindowSettings(const char* name) +{ + ImGuiContext& g = *GImGui; + ImGuiID id = ImHash(name, 0); + for (int i = 0; i != g.Settings.Size; i++) + { + ImGuiIniData* ini = &g.Settings[i]; + if (ini->Id == id) + return ini; + } + return NULL; +} + +static ImGuiIniData* AddWindowSettings(const char* name) +{ + GImGui->Settings.resize(GImGui->Settings.Size + 1); + ImGuiIniData* ini = &GImGui->Settings.back(); + ini->Name = ImStrdup(name); + ini->Id = ImHash(name, 0); + ini->Collapsed = false; + ini->Pos = ImVec2(FLT_MAX,FLT_MAX); + ini->Size = ImVec2(0,0); + return ini; +} + +// Zero-tolerance, poor-man .ini parsing +// FIXME: Write something less rubbish +static void LoadIniSettingsFromDisk(const char* ini_filename) +{ + ImGuiContext& g = *GImGui; + if (!ini_filename) + return; + + int file_size; + char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_size, 1); + if (!file_data) + return; + + ImGuiIniData* settings = NULL; + const char* buf_end = file_data + file_size; + for (const char* line_start = file_data; line_start < buf_end; ) + { + const char* line_end = line_start; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + + if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') + { + char name[64]; + ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1); + settings = FindWindowSettings(name); + if (!settings) + settings = AddWindowSettings(name); + } + else if (settings) + { + float x, y; + int i; + if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) + settings->Pos = ImVec2(x, y); + else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) + settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); + else if (sscanf(line_start, "Collapsed=%d", &i) == 1) + settings->Collapsed = (i != 0); + } + + line_start = line_end+1; + } + + ImGui::MemFree(file_data); +} + +static void SaveIniSettingsToDisk(const char* ini_filename) +{ + ImGuiContext& g = *GImGui; + g.SettingsDirtyTimer = 0.0f; + if (!ini_filename) + return; + + // Gather data from windows that were active during this session + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + ImGuiIniData* settings = FindWindowSettings(window->Name); + settings->Pos = window->Pos; + settings->Size = window->SizeFull; + settings->Collapsed = window->Collapsed; + } + + // Write .ini file + // If a window wasn't opened in this session we preserve its settings + FILE* f = ImFileOpen(ini_filename, "wt"); + if (!f) + return; + for (int i = 0; i != g.Settings.Size; i++) + { + const ImGuiIniData* settings = &g.Settings[i]; + if (settings->Pos.x == FLT_MAX) + continue; + const char* name = settings->Name; + if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + name = p; + fprintf(f, "[%s]\n", name); + fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); + fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + fprintf(f, "Collapsed=%d\n", settings->Collapsed); + fprintf(f, "\n"); + } + + fclose(f); +} + +static void MarkIniSettingsDirty() +{ + ImGuiContext& g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + +// FIXME: Add a more explicit sort order in the window structure. +static int ChildWindowComparer(const void* lhs, const void* rhs) +{ + const ImGuiWindow* a = *(const ImGuiWindow**)lhs; + const ImGuiWindow* b = *(const ImGuiWindow**)rhs; + if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) + return d; + if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) + return d; + if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox)) + return d; + return (a->OrderWithinParent - b->OrderWithinParent); +} + +static void AddWindowToSortedBuffer(ImVector& out_sorted_windows, ImGuiWindow* window) +{ + out_sorted_windows.push_back(window); + if (window->Active) + { + int count = window->DC.ChildWindows.Size; + if (count > 1) + qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); + for (int i = 0; i < count; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (child->Active) + AddWindowToSortedBuffer(out_sorted_windows, child); + } + } +} + +static void AddDrawListToRenderList(ImVector& out_render_list, ImDrawList* draw_list) +{ + if (draw_list->CmdBuffer.empty()) + return; + + // Remove trailing command if unused + ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); + if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) + { + draw_list->CmdBuffer.pop_back(); + if (draw_list->CmdBuffer.empty()) + return; + } + + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly. + IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); + IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); + IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + + // Check that draw_list doesn't use more vertices than indexable in a single draw call (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per window) + // If this assert triggers because you are drawing lots of stuff manually, you can: + // A) Add '#define ImDrawIdx unsigned int' in imconfig.h to set the index size to 4 bytes. You'll need to handle the 4-bytes indices to your renderer. + // For example, the OpenGL example code detect index size at compile-time by doing: + // 'glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);' + // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API. + // B) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists. + IM_ASSERT(((ImU64)draw_list->_VtxCurrentIdx >> (sizeof(ImDrawIdx)*8)) == 0); // Too many vertices in same ImDrawList. See comment above. + + out_render_list.push_back(draw_list); + GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size; + GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size; +} + +static void AddWindowToRenderList(ImVector& out_render_list, ImGuiWindow* window) +{ + AddDrawListToRenderList(out_render_list, window->DrawList); + for (int i = 0; i < window->DC.ChildWindows.Size; i++) + { + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (!child->Active) // clipped children may have been marked not active + continue; + if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0) + continue; + AddWindowToRenderList(out_render_list, child); + } +} + +// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +void ImGui::PopClipRect() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PopClipRect(); + window->ClipRect = window->DrawList->_ClipRectStack.back(); +} + +// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +void ImGui::EndFrame() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again + + // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) + if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f) + { + g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y); + g.OsImePosSet = g.OsImePosRequest; + } + + // Hide implicit "Debug" window if it hasn't been used + IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls + if (g.CurrentWindow && !g.CurrentWindow->Accessed) + g.CurrentWindow->Active = false; + ImGui::End(); + + // Click to focus window and start moving (after we're done with all our widgets) + if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) + { + if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear + { + if (g.HoveredRootWindow != NULL) + { + FocusWindow(g.HoveredWindow); + if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow = g.HoveredWindow; + g.MovedWindowMoveId = g.HoveredRootWindow->MoveId; + SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow); + } + } + else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL) + { + // Clicking on void disable focus + FocusWindow(NULL); + } + } + } + + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because childs may not exist yet + g.WindowsSortBuffer.resize(0); + g.WindowsSortBuffer.reserve(g.Windows.Size); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it + continue; + AddWindowToSortedBuffer(g.WindowsSortBuffer, window); + } + IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong + g.Windows.swap(g.WindowsSortBuffer); + + // Clear Input data for next frame + g.IO.MouseWheel = 0.0f; + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + + g.FrameCountEnded = g.FrameCount; +} + +void ImGui::Render() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + + if (g.FrameCountEnded != g.FrameCount) + ImGui::EndFrame(); + g.FrameCountRendered = g.FrameCount; + + // Skip render altogether if alpha is 0.0 + // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false. + if (g.Style.Alpha > 0.0f) + { + // Gather windows to render + g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0; + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.RenderDrawLists[i].resize(0); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) + { + // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, .. + g.IO.MetricsActiveWindows++; + if (window->Flags & ImGuiWindowFlags_Popup) + AddWindowToRenderList(g.RenderDrawLists[1], window); + else if (window->Flags & ImGuiWindowFlags_Tooltip) + AddWindowToRenderList(g.RenderDrawLists[2], window); + else + AddWindowToRenderList(g.RenderDrawLists[0], window); + } + } + + // Flatten layers + int n = g.RenderDrawLists[0].Size; + int flattened_size = n; + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + flattened_size += g.RenderDrawLists[i].Size; + g.RenderDrawLists[0].resize(flattened_size); + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + { + ImVector& layer = g.RenderDrawLists[i]; + if (layer.empty()) + continue; + memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); + n += layer.Size; + } + + // Draw software mouse cursor if requested + if (g.IO.MouseDrawCursor) + { + const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor]; + const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset; + const ImVec2 size = cursor_data.Size; + const ImTextureID tex_id = g.IO.Fonts->TexID; + g.OverlayDrawList.PushTextureID(tex_id); + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill + g.OverlayDrawList.PopTextureID(); + } + if (!g.OverlayDrawList.VtxBuffer.empty()) + AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList); + + // Setup draw data + g.RenderDrawData.Valid = true; + g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size; + g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices; + g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices; + + // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() + if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) + g.IO.RenderDrawListsFn(&g.RenderDrawData); + } +} + +const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) +{ + const char* text_display_end = text; + if (!text_end) + text_end = (const char*)-1; + + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; + return text_display_end; +} + +// Pass text data straight to log (without being displayed) +void ImGui::LogText(const char* fmt, ...) +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + va_list args; + va_start(args, fmt); + if (g.LogFile) + { + vfprintf(g.LogFile, fmt, args); + } + else + { + g.LogClipboard->appendv(fmt, args); + } + va_end(args); +} + +// Internal version that takes a position to decide on newline placement and pad items according to their depth. +// We split text into individual lines to add current tree level padding +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); + + if (!text_end) + text_end = ImGui::FindRenderedTextEnd(text, text_end); + + const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1; + window->DC.LogLinePosY = ref_pos.y; + + const char* text_remaining = text; + if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth + g.LogStartDepth = window->DC.TreeDepth; + const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); + for (;;) + { + // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. + const char* line_end = text_remaining; + while (line_end < text_end) + if (*line_end == '\n') + break; + else + line_end++; + if (line_end >= text_end) + line_end = NULL; + + const bool is_first_line = (text == text_remaining); + bool is_last_line = false; + if (line_end == NULL) + { + is_last_line = true; + line_end = text_end; + } + if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) + { + const int char_count = (int)(line_end - text_remaining); + if (log_new_line || !is_first_line) + ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); + else + ImGui::LogText(" %.*s", char_count, text_remaining); + } + + if (is_last_line) + break; + text_remaining = line_end + 1; + } +} + +// Internal ImGui functions to render text +// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() +void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Hide anything after a '##' string + const char* text_display_end; + if (hide_text_after_hash) + { + text_display_end = FindRenderedTextEnd(text, text_end); + } + else + { + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + text_display_end = text_end; + } + + const int text_len = (int)(text_display_end - text); + if (text_len > 0) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); + if (g.LogEnabled) + LogRenderedText(pos, text, text_display_end); + } +} + +void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (!text_end) + text_end = text + strlen(text); // FIXME-OPT + + const int text_len = (int)(text_end - text); + if (text_len > 0) + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); + if (g.LogEnabled) + LogRenderedText(pos, text, text_end); + } +} + +// Default clip_rect uses (pos_min,pos_max) +// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) +void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) +{ + // Hide anything after a '##' string + const char* text_display_end = FindRenderedTextEnd(text, text_end); + const int text_len = (int)(text_display_end - text); + if (text_len == 0) + return; + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Perform CPU side clipping for single clipped element to avoid using scissor state + ImVec2 pos = pos_min; + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); + + const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; + const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; + bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min + need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); + + // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. + if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + + // Render + if (need_clipping) + { + ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + } + else + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); + } + if (g.LogEnabled) + LogRenderedText(pos, text, text_display_end); +} + +// Render a rectangle shaped with optional rounding and borders +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +{ + ImGuiWindow* window = GetCurrentWindow(); + + window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); + if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) + { + window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding); + } +} + +// Render a triangle to denote expanded/collapsed state +void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + const float h = g.FontSize * 1.00f; + const float r = h * 0.40f * scale; + ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); + + ImVec2 a, b, c; + if (is_open) + { + center.y -= r*0.25f; + a = center + ImVec2(0,1)*r; + b = center + ImVec2(-0.866f,-0.5f)*r; + c = center + ImVec2(0.866f,-0.5f)*r; + } + else + { + a = center + ImVec2(1,0)*r; + b = center + ImVec2(-0.500f,0.866f)*r; + c = center + ImVec2(-0.500f,-0.866f)*r; + } + + window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text)); +} + +void ImGui::RenderBullet(ImVec2 pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); +} + +void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + ImVec2 a, b, c; + float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f); + float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f); + a.x = pos.x + 0.5f + start_x; + b.x = a.x + rem_third; + c.x = a.x + rem_third * 3.0f; + b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y); + a.y = b.y - rem_third; + c.y = b.y - rem_third * 2.0f; + + window->DrawList->PathLineTo(a); + window->DrawList->PathLineTo(b); + window->DrawList->PathLineTo(c); + window->DrawList->PathStroke(col, false); +} + +// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) +ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) +{ + ImGuiContext& g = *GImGui; + + const char* text_display_end; + if (hide_text_after_double_hash) + text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string + else + text_display_end = text_end; + + ImFont* font = g.Font; + const float font_size = g.FontSize; + if (text == text_display_end) + return ImVec2(0.0f, font_size); + ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); + + // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field) + const float font_scale = font_size / font->FontSize; + const float character_spacing_x = 1.0f * font_scale; + if (text_size.x > 0.0f) + text_size.x -= character_spacing_x; + text_size.x = (float)(int)(text_size.x + 0.95f); + + return text_size; +} + +// Helper to calculate coarse clipping of large list of evenly sized items. +// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. +// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX +void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + if (g.LogEnabled) + { + // If logging is active, do not perform any clipping + *out_items_display_start = 0; + *out_items_display_end = items_count; + return; + } + if (window->SkipItems) + { + *out_items_display_start = *out_items_display_end = 0; + return; + } + + const ImVec2 pos = window->DC.CursorPos; + int start = (int)((window->ClipRect.Min.y - pos.y) / items_height); + int end = (int)((window->ClipRect.Max.y - pos.y) / items_height); + start = ImClamp(start, 0, items_count); + end = ImClamp(end + 1, start, items_count); + *out_items_display_start = start; + *out_items_display_end = end; +} + +// Find window given position, search front-to-back +// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected. +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) +{ + ImGuiContext& g = *GImGui; + for (int i = g.Windows.Size-1; i >= 0; i--) + { + ImGuiWindow* window = g.Windows[i]; + if (!window->Active) + continue; + if (window->Flags & ImGuiWindowFlags_NoInputs) + continue; + if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) + continue; + + // Using the clipped AABB so a child window will typically be clipped by its parent. + ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding); + if (bb.Contains(pos)) + return window; + } + return NULL; +} + +// Test if mouse cursor is hovering given rectangle +// NB- Rectangle is clipped by our current clip setting +// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) +bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + + // Clip + ImRect rect_clipped(r_min, r_max); + if (clip) + rect_clipped.Clip(window->ClipRect); + + // Expand for touch input + const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); + return rect_for_touch.Contains(g.IO.MousePos); +} + +bool ImGui::IsMouseHoveringWindow() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow; +} + +bool ImGui::IsMouseHoveringAnyWindow() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow != NULL; +} + +static bool IsKeyPressedMap(ImGuiKey key, bool repeat) +{ + const int key_index = GImGui->IO.KeyMap[key]; + return ImGui::IsKeyPressed(key_index, repeat); +} + +int ImGui::GetKeyIndex(ImGuiKey imgui_key) +{ + IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); + return GImGui->IO.KeyMap[imgui_key]; +} + +// Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]! +bool ImGui::IsKeyDown(int user_key_index) +{ + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); + return GImGui->IO.KeysDown[user_key_index]; +} + +bool ImGui::IsKeyPressed(int user_key_index, bool repeat) +{ + ImGuiContext& g = *GImGui; + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + const float t = g.IO.KeysDownDuration[user_key_index]; + if (t == 0.0f) + return true; + + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) + return true; + } + return false; +} + +bool ImGui::IsKeyReleased(int user_key_index) +{ + ImGuiContext& g = *GImGui; + if (user_key_index < 0) return false; + IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + if (g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index]) + return true; + return false; +} + +bool ImGui::IsMouseDown(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDown[button]; +} + +bool ImGui::IsMouseClicked(int button, bool repeat) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + const float t = g.IO.MouseDownDuration[button]; + if (t == 0.0f) + return true; + + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) + return true; + } + + return false; +} + +bool ImGui::IsMouseReleased(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseReleased[button]; +} + +bool ImGui::IsMouseDoubleClicked(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDoubleClicked[button]; +} + +bool ImGui::IsMouseDragging(int button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; +} + +ImVec2 ImGui::GetMousePos() +{ + return GImGui->IO.MousePos; +} + +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! +ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() +{ + ImGuiContext& g = *GImGui; + if (g.CurrentPopupStack.Size > 0) + return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen; + return g.IO.MousePos; +} + +ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (lock_threshold < 0.0f) + lock_threshold = g.IO.MouseDragThreshold; + if (g.IO.MouseDown[button]) + if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) + return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). + return ImVec2(0.0f, 0.0f); +} + +void ImGui::ResetMouseDragDelta(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr + g.IO.MouseClickedPos[button] = g.IO.MousePos; +} + +ImGuiMouseCursor ImGui::GetMouseCursor() +{ + return GImGui->MouseCursor; +} + +void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) +{ + GImGui->MouseCursor = cursor_type; +} + +void ImGui::CaptureKeyboardFromApp(bool capture) +{ + GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0; +} + +void ImGui::CaptureMouseFromApp(bool capture) +{ + GImGui->CaptureMouseNextFrame = capture ? 1 : 0; +} + +bool ImGui::IsItemHovered() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemHoveredAndUsable; +} + +bool ImGui::IsItemHoveredRect() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemHoveredRect; +} + +bool ImGui::IsItemActive() +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId) + { + ImGuiWindow* window = GetCurrentWindowRead(); + return g.ActiveId == window->DC.LastItemId; + } + return false; +} + +bool ImGui::IsItemClicked(int mouse_button) +{ + return IsMouseClicked(mouse_button) && IsItemHovered(); +} + +bool ImGui::IsAnyItemHovered() +{ + return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0; +} + +bool ImGui::IsAnyItemActive() +{ + return GImGui->ActiveId != 0; +} + +bool ImGui::IsItemVisible() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImRect r(window->ClipRect); + return r.Overlaps(window->DC.LastItemRect); +} + +// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. +void ImGui::SetItemAllowOverlap() +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == g.CurrentWindow->DC.LastItemId) + g.HoveredIdAllowOverlap = true; + if (g.ActiveId == g.CurrentWindow->DC.LastItemId) + g.ActiveIdAllowOverlap = true; +} + +ImVec2 ImGui::GetItemRectMin() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.Min; +} + +ImVec2 ImGui::GetItemRectMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.Max; +} + +ImVec2 ImGui::GetItemRectSize() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.LastItemRect.GetSize(); +} + +ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImRect rect = window->DC.LastItemRect; + rect.Expand(outward); + return rect.GetClosestPoint(pos, on_edge); +} + +static ImRect GetVisibleRect() +{ + ImGuiContext& g = *GImGui; + if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) + return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); + return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); +} + +// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first. +static void BeginTooltipEx(bool override_previous_tooltip) +{ + ImGuiContext& g = *GImGui; + char window_name[16]; + ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip%02d", g.TooltipOverrideCount); + if (override_previous_tooltip) + if (ImGuiWindow* window = ImGui::FindWindowByName(window_name)) + if (window->Active) + { + // Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one. + window->HiddenFrames = 1; + ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip%02d", ++g.TooltipOverrideCount); + } + ImGui::Begin(window_name, NULL, ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize); +} + +void ImGui::SetTooltipV(const char* fmt, va_list args) +{ + BeginTooltipEx(true); + TextV(fmt, args); + EndTooltip(); +} + +void ImGui::SetTooltip(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + SetTooltipV(fmt, args); + va_end(args); +} + +void ImGui::BeginTooltip() +{ + BeginTooltipEx(false); +} + +void ImGui::EndTooltip() +{ + IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls + ImGui::End(); +} + +static bool IsPopupOpen(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id; +} + +// Mark popup as open (toggle toward open state). +// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) +void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id); + int current_stack_size = g.CurrentPopupStack.Size; + ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here) + if (g.OpenPopupStack.Size < current_stack_size + 1) + g.OpenPopupStack.push_back(popup_ref); + else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id) + { + g.OpenPopupStack.resize(current_stack_size+1); + g.OpenPopupStack[current_stack_size] = popup_ref; + } +} + +void ImGui::OpenPopup(const char* str_id) +{ + ImGui::OpenPopupEx(str_id, false); +} + +static void CloseInactivePopups() +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.empty()) + return; + + // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. + // Don't close our own child popup windows + int n = 0; + if (g.FocusedWindow) + { + for (n = 0; n < g.OpenPopupStack.Size; n++) + { + ImGuiPopupRef& popup = g.OpenPopupStack[n]; + if (!popup.Window) + continue; + IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); + if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + + bool has_focus = false; + for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++) + has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow); + if (!has_focus) + break; + } + } + if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below + g.OpenPopupStack.resize(n); +} + +static ImGuiWindow* GetFrontMostModalRootWindow() +{ + ImGuiContext& g = *GImGui; + for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) + if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window) + if (front_most_popup->Flags & ImGuiWindowFlags_Modal) + return front_most_popup; + return NULL; +} + +static void ClosePopupToLevel(int remaining) +{ + ImGuiContext& g = *GImGui; + if (remaining > 0) + ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window); + else + ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow); + g.OpenPopupStack.resize(remaining); +} + +static void ClosePopup(ImGuiID id) +{ + if (!IsPopupOpen(id)) + return; + ImGuiContext& g = *GImGui; + ClosePopupToLevel(g.OpenPopupStack.Size - 1); +} + +// Close the popup we have begin-ed into. +void ImGui::CloseCurrentPopup() +{ + ImGuiContext& g = *GImGui; + int popup_idx = g.CurrentPopupStack.Size - 1; + if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) + return; + while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu)) + popup_idx--; + ClosePopupToLevel(popup_idx); +} + +static inline void ClearSetNextWindowData() +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0; + g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false; +} + +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(str_id); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; + + char name[20]; + if (flags & ImGuiWindowFlags_ChildMenu) + ImFormatString(name, IM_ARRAYSIZE(name), "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth + else + ImFormatString(name, IM_ARRAYSIZE(name), "##popup_%08x", id); // Not recycling, so we can close/open during the same frame + + bool is_open = ImGui::Begin(name, NULL, flags); + if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) + g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; + if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + ImGui::EndPopup(); + + return is_open; +} + +bool ImGui::BeginPopup(const char* str_id) +{ + if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders); +} + +bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings; + bool is_open = ImGui::Begin(name, p_open, flags); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { + ImGui::EndPopup(); + if (is_open) + ClosePopup(id); + return false; + } + + return is_open; +} + +void ImGui::EndPopup() +{ + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls + IM_ASSERT(GImGui->CurrentPopupStack.Size > 0); + ImGui::End(); + if (!(window->Flags & ImGuiWindowFlags_Modal)) + ImGui::PopStyleVar(); +} + +// This is a helper to handle the most simple case of associating one named popup to one given widget. +// 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling +// this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers. +// 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect() +// and passing true to the OpenPopupEx(). +// Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that +// the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu +// driven by click position. +bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) +{ + if (IsItemHovered() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, false); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "window_context_menu"; + if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button)) + if (also_over_items || !IsAnyItemHovered()) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "void_context_menu"; + if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); +} + +static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; + + const ImVec2 content_avail = ImGui::GetContentRegionAvail(); + ImVec2 size = ImFloor(size_arg); + if (size.x <= 0.0f) + { + if (size.x == 0.0f) + flags |= ImGuiWindowFlags_ChildWindowAutoFitX; + size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues) + } + if (size.y <= 0.0f) + { + if (size.y == 0.0f) + flags |= ImGuiWindowFlags_ChildWindowAutoFitY; + size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y); + } + if (border) + flags |= ImGuiWindowFlags_ShowBorders; + flags |= extra_flags; + + char title[256]; + if (name) + ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s.%08X", window->Name, name, id); + else + ImFormatString(title, IM_ARRAYSIZE(title), "%s.%08X", window->Name, id); + + bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags); + + if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) + ImGui::GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; + + return ret; +} + +bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); +} + +bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) +{ + return BeginChildEx(NULL, id, size_arg, border, extra_flags); +} + +void ImGui::EndChild() +{ + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss + if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1) + { + ImGui::End(); + } + else + { + // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. + ImVec2 sz = GetWindowSize(); + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f + sz.x = ImMax(4.0f, sz.x); + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) + sz.y = ImMax(4.0f, sz.y); + + ImGui::End(); + + window = GetCurrentWindow(); + ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz); + ItemSize(sz); + ItemAdd(bb, NULL); + } +} + +// Helper to create a child window / scrolling region that looks like a normal widget frame. +bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]); + ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); +} + +void ImGui::EndChildFrame() +{ + ImGui::EndChild(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); +} + +// Save and compare stack sizes on Begin()/End() to detect usage errors +static void CheckStacksSize(ImGuiWindow* window, bool write) +{ + // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) + ImGuiContext& g = *GImGui; + int* p_backup = &window->DC.StackSizesBackup[0]; + { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() + { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() + { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() + { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() + { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() + { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() + IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); +} + +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner) +{ + const ImGuiStyle& style = GImGui->Style; + + // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it. + ImVec2 safe_padding = style.DisplaySafeAreaPadding; + ImRect r_outer(GetVisibleRect()); + r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f)); + ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size); + + for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction). + { + const int dir = (n == -1) ? *last_dir : n; + ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y); + if (rect.GetWidth() < size.x || rect.GetHeight() < size.y) + continue; + *last_dir = dir; + return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y); + } + + // Fallback, try to keep within display + *last_dir = -1; + ImVec2 pos = base_pos; + pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); + pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); + return pos; +} + +ImGuiWindow* ImGui::FindWindowByName(const char* name) +{ + // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block + ImGuiContext& g = *GImGui; + ImGuiID id = ImHash(name, 0); + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i]->ID == id) + return g.Windows[i]; + return NULL; +} + +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + + // Create window the first time + ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); + IM_PLACEMENT_NEW(window) ImGuiWindow(name); + window->Flags = flags; + + if (flags & ImGuiWindowFlags_NoSavedSettings) + { + // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. + window->Size = window->SizeFull = size; + } + else + { + // Retrieve settings from .ini file + // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. + window->PosFloat = ImVec2(60, 60); + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + + ImGuiIniData* settings = FindWindowSettings(name); + if (!settings) + { + settings = AddWindowSettings(name); + } + else + { + window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver; + window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver; + window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver; + } + + if (settings->Pos.x != FLT_MAX) + { + window->PosFloat = settings->Pos; + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + window->Collapsed = settings->Collapsed; + } + + if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize)) + size = settings->Size; + window->Size = window->SizeFull = size; + } + + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) + { + window->AutoFitFramesX = window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } + else + { + if (window->Size.x <= 0.0f) + window->AutoFitFramesX = 2; + if (window->Size.y <= 0.0f) + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); + } + + if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) + g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once + else + g.Windows.push_back(window); + return window; +} + +static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size) +{ + ImGuiContext& g = *GImGui; + if (g.SetNextWindowSizeConstraint) + { + // Using -1,-1 on either X/Y axis to preserve the current size. + ImRect cr = g.SetNextWindowSizeConstraintRect; + new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; + new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; + if (g.SetNextWindowSizeConstraintCallback) + { + ImGuiSizeConstraintCallbackData data; + data.UserData = g.SetNextWindowSizeConstraintCallbackUserData; + data.Pos = window->Pos; + data.CurrentSize = window->SizeFull; + data.DesiredSize = new_size; + g.SetNextWindowSizeConstraintCallback(&data); + new_size = data.DesiredSize; + } + } + if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) + new_size = ImMax(new_size, g.Style.WindowMinSize); + window->SizeFull = new_size; +} + +// Push a new ImGui window to add widgets to. +// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +// - Begin/End can be called multiple times during the frame with the same window name to append content. +// - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. +// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. +// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. +// - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). +bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) +{ + return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags); +} + +bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + IM_ASSERT(name != NULL); // Window name required + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet + + if (flags & ImGuiWindowFlags_NoInputs) + flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; + + // Find or create + bool window_is_new = false; + ImGuiWindow* window = FindWindowByName(name); + if (!window) + { + window = CreateNewWindow(name, size_on_first_use, flags); + window_is_new = true; + } + + const int current_frame = ImGui::GetFrameCount(); + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + if (first_begin_of_the_frame) + window->Flags = (ImGuiWindowFlags)flags; + else + flags = window->Flags; + + // Add to stack + ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL; + g.CurrentWindowStack.push_back(window); + SetCurrentWindow(window); + CheckStacksSize(window, true); + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + + bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; + window_was_active &= (window->PopupId == popup_ref.PopupId); + window_was_active &= (window == popup_ref.Window); + popup_ref.Window = window; + g.CurrentPopupStack.push_back(popup_ref); + window->PopupId = popup_ref.PopupId; + } + + const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1); + + // Process SetNextWindow***() calls + bool window_pos_set_by_api = false, window_size_set_by_api = false; + if (g.SetNextWindowPosCond) + { + const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that. + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing; + window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0; + if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f) + { + window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size + window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + } + else + { + SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond); + } + window->DC.CursorPos = backup_cursor_pos; + g.SetNextWindowPosCond = 0; + } + if (g.SetNextWindowSizeCond) + { + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing; + window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0; + SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); + g.SetNextWindowSizeCond = 0; + } + if (g.SetNextWindowContentSizeCond) + { + window->SizeContentsExplicit = g.SetNextWindowContentSizeVal; + g.SetNextWindowContentSizeCond = 0; + } + else if (first_begin_of_the_frame) + { + window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); + } + if (g.SetNextWindowCollapsedCond) + { + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing; + SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); + g.SetNextWindowCollapsedCond = 0; + } + if (g.SetNextWindowFocus) + { + ImGui::SetWindowFocus(); + g.SetNextWindowFocus = false; + } + + // Update known root window (if we are a child window, otherwise window == window->RootWindow) + int root_idx, root_non_popup_idx; + for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--) + if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow)) + break; + for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--) + if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) + break; + window->ParentWindow = parent_window; + window->RootWindow = g.CurrentWindowStack[root_idx]; + window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color. + + // When reusing window again multiple times a frame, just append content (don't need to setup again) + if (first_begin_of_the_frame) + { + window->Active = true; + window->OrderWithinParent = 0; + window->BeginCount = 0; + window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); + window->LastFrameActive = current_frame; + window->IDStack.resize(1); + + // Clear draw list, setup texture, outer clipping rectangle + window->DrawList->Clear(); + window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + ImRect fullscreen_rect(GetVisibleRect()); + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup))) + PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); + else + PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true); + + if (!window_was_active) + { + // Popup first latch mouse position, will position itself when it appears next frame + window->AutoPosLastDirection = -1; + if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + window->PosFloat = g.IO.MousePos; + } + + // Collapse window by double-clicking on title bar + // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) + { + ImRect title_bar_rect = window->TitleBarRect(); + if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) + { + window->Collapsed = !window->Collapsed; + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + FocusWindow(window); + } + } + else + { + window->Collapsed = false; + } + + // SIZE + + // Save contents size from last frame for auto-fitting (unless explicitly specified) + window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x)); + window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y)); + + // Hide popup/tooltip window when first appearing while we measure size (because we recycle them) + if (window->HiddenFrames > 0) + window->HiddenFrames--; + if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active) + { + window->HiddenFrames = 1; + if (flags & ImGuiWindowFlags_AlwaysAutoResize) + { + if (!window_size_set_by_api) + window->Size = window->SizeFull = ImVec2(0.f, 0.f); + window->SizeContents = ImVec2(0.f, 0.f); + } + } + + // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects. + window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding; + + // Calculate auto-fit size + ImVec2 size_auto_fit; + if ((flags & ImGuiWindowFlags_Tooltip) != 0) + { + // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. + size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); + } + else + { + size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding)); + + // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. + if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)) + size_auto_fit.y += style.ScrollbarSize; + if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar)) + size_auto_fit.x += style.ScrollbarSize; + size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f); + } + + // Handle automatic resize + if (window->Collapsed) + { + // We still process initial auto-fit on collapsed windows to get a window width, + // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + } + else + { + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api) + { + window->SizeFull = size_auto_fit; + } + else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api) + { + // Auto-fit only grows during the first few frames + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + } + } + + // Apply minimum/maximum window size constraints and final size + ApplySizeFullWithConstraint(window, window->SizeFull); + window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull; + + // POSITION + + // Position child window + if (flags & ImGuiWindowFlags_ChildWindow) + { + window->OrderWithinParent = parent_window->DC.ChildWindows.Size; + parent_window->DC.ChildWindows.push_back(window); + } + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) + { + window->Pos = window->PosFloat = parent_window->DC.CursorPos; + window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin(). + } + + bool window_pos_center = false; + window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0); + window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden); + if (window_pos_center) + { + // Center (any sort of window) + SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f), 0); + } + else if (flags & ImGuiWindowFlags_ChildMenu) + { + // Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds. + // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. + IM_ASSERT(window_pos_set_by_api); + float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value). + ImRect rect_to_avoid; + if (parent_window->DC.MenuBarAppending) + rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); + else + rect_to_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + } + else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden) + { + ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1); + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + } + + // Position tooltip (always follows mouse) + if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api) + { + ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead? + window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + if (window->AutoPosLastDirection == -1) + window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. + } + + // Clamp position so it stays visible + if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) + { + if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + { + ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size; + window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding); + } + } + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + + // Default item width. Make it proportional to window size if window manually resizes + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) + window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); + else + window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); + + // Prepare for focus requests + window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); + window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); + window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; + window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; + + // Apply scrolling + if (window->ScrollTarget.x < FLT_MAX) + { + window->Scroll.x = window->ScrollTarget.x; + window->ScrollTarget.x = FLT_MAX; + } + if (window->ScrollTarget.y < FLT_MAX) + { + float center_ratio = window->ScrollTargetCenterRatio.y; + window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y); + window->ScrollTarget.y = FLT_MAX; + } + window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f)); + if (!window->Collapsed && !window->SkipItems) + window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes)); + + // Modal window darkens what is behind them + if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow()) + window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio)); + + // Draw window + handle manual resize + ImRect title_bar_rect = window->TitleBarRect(); + const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; + if (window->Collapsed) + { + // Draw title bar only + RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding); + } + else + { + ImU32 resize_col = 0; + const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize)) + { + // Manual resize + const ImVec2 br = window->Rect().GetBR(); + const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br); + const ImGuiID resize_id = window->GetID("#RESIZE"); + bool hovered, held; + ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds); + resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); + + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; + + if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) + { + // Manual auto-fit when double-clicking + ApplySizeFullWithConstraint(window, size_auto_fit); + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + ClearActiveID(); + } + else if (held) + { + // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position + ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos); + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkIniSettingsDirty(); + } + + window->Size = window->SizeFull; + title_bar_rect = window->TitleBarRect(); + } + + // Scrollbars + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f; + + // Window background, Default Alpha + ImGuiCol bg_color_idx = ImGuiCol_WindowBg; + if ((flags & ImGuiWindowFlags_ComboBox) != 0) + bg_color_idx = ImGuiCol_ComboBg; + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0) + bg_color_idx = ImGuiCol_PopupBg; + else if ((flags & ImGuiWindowFlags_ChildWindow) != 0) + bg_color_idx = ImGuiCol_ChildWindowBg; + ImVec4 bg_color = style.Colors[bg_color_idx]; + if (bg_alpha >= 0.0f) + bg_color.w = bg_alpha; + bg_color.w *= style.Alpha; + if (bg_color.w > 0.0f) + window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImGuiCorner_All : ImGuiCorner_BottomLeft|ImGuiCorner_BottomRight); + + // Title bar + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); + + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) + { + ImRect menu_bar_rect = window->MenuBarRect(); + if (flags & ImGuiWindowFlags_ShowBorders) + window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border)); + window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImGuiCorner_TopLeft|ImGuiCorner_TopRight); + } + + // Scrollbars + if (window->ScrollbarX) + Scrollbar(window, true); + if (window->ScrollbarY) + Scrollbar(window, false); + + // Render resize grip + // (after the input handling so we don't have a frame of latency) + if (!(flags & ImGuiWindowFlags_NoResize)) + { + const ImVec2 br = window->Rect().GetBR(); + window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize)); + window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size)); + window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3); + window->DrawList->PathFillConvex(resize_col); + } + + // Borders + if (flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding); + window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding); + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border)); + } + } + + // Update ContentsRegionMax. All the variable it depends on are set above in this function. + window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x; + window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); + window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); + + // Setup drawing context + window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x; + window->DC.GroupOffsetX = 0.0f; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); + window->DC.CursorPos = window->DC.CursorStartPos; + window->DC.CursorPosPrevLine = window->DC.CursorPos; + window->DC.CursorMaxPos = window->DC.CursorStartPos; + window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; + window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.MenuBarAppending = false; + window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x); + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; + window->DC.ChildWindows.resize(0); + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.ItemWidth = window->ItemWidthDefault; + window->DC.TextWrapPos = -1.0f; // disabled + window->DC.AllowKeyboardFocus = true; + window->DC.ButtonRepeat = false; + window->DC.ItemWidthStack.resize(0); + window->DC.AllowKeyboardFocusStack.resize(0); + window->DC.ButtonRepeatStack.resize(0); + window->DC.TextWrapPosStack.resize(0); + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsCount = 1; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY; + window->DC.TreeDepth = 0; + window->DC.StateStorage = &window->StateStorage; + window->DC.GroupStack.resize(0); + window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; + window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active); + + if (window->AutoFitFramesX > 0) + window->AutoFitFramesX--; + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; + + // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) + if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) + FocusWindow(window); + + // Title bar + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + { + if (p_open != NULL) + { + const float pad = 2.0f; + const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f; + if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad)) + *p_open = false; + } + + const ImVec2 text_size = CalcTextSize(name, NULL, true); + if (!(flags & ImGuiWindowFlags_NoCollapse)) + RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f); + + ImVec2 text_min = window->Pos; + ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y); + ImRect clip_rect; + clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton() + float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; + float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x; + if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); + text_min.x += pad_left; + text_max.x -= pad_right; + clip_rect.Min = ImVec2(text_min.x, window->Pos.y); + RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); + } + + // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() + window->WindowRectClipped = window->Rect(); + window->WindowRectClipped.Clip(window->ClipRect); + + // Pressing CTRL+C while holding on a window copy its content to the clipboard + // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. + // Maybe we can support CTRL+C on every element? + /* + if (g.ActiveId == move_id) + if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) + ImGui::LogToClipboard(); + */ + } + + // Inner clipping rectangle + // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame + // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior. + const ImRect title_bar_rect = window->TitleBarRect(); + const float border_size = window->BorderSize; + ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size); + clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size); + PushClipRect(clip_rect.Min, clip_rect.Max, true); + + // Clear 'accessed' flag last thing + if (first_begin_of_the_frame) + window->Accessed = false; + window->BeginCount++; + g.SetNextWindowSizeConstraint = false; + + // Child window can be out of sight and have "negative" clip windows. + // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). + if (flags & ImGuiWindowFlags_ChildWindow) + { + IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); + window->Collapsed = parent_window && parent_window->Collapsed; + + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y); + + // We also hide the window from rendering because we've already added its border to the command list. + // (we could perform the check earlier in the function but it is simpler at this point) + if (window->Collapsed) + window->Active = false; + } + if (style.Alpha <= 0.0f) + window->Active = false; + + // Return false if we don't intend to display anything to allow user to perform an early out optimization + window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0; + return !window->SkipItems; +} + +void ImGui::End() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + + if (window->DC.ColumnsCount != 1) // close columns set if any is open + Columns(1, "#CLOSECOLUMNS"); + PopClipRect(); // inner window clip rectangle + + // Stop logging + if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging + LogFinish(); + + // Pop + // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin(). + g.CurrentWindowStack.pop_back(); + if (window->Flags & ImGuiWindowFlags_Popup) + g.CurrentPopupStack.pop_back(); + CheckStacksSize(window, false); + SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); +} + +// Vertical scrollbar +// The entire piece of code below is rather confusing because: +// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar +// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. +static void Scrollbar(ImGuiWindow* window, bool horizontal) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); + + // Render background + bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); + float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; + const ImRect window_rect = window->Rect(); + const float border_size = window->BorderSize; + ImRect bb = horizontal + ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) + : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); + if (!horizontal) + bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); + if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f) + return; + + float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; + int window_rounding_corners; + if (horizontal) + window_rounding_corners = ImGuiCorner_BottomLeft | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); + else + window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImGuiCorner_TopRight : 0) | (other_scrollbar ? 0 : ImGuiCorner_BottomRight); + window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners); + bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); + + // V denote the main axis of the scrollbar + float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); + float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; + float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w; + float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; + + // The grabable box size generally represent the amount visible (vs the total scrollable amount) + // But we maintain a minimum size in pixel to allow for the user to still aim inside. + const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v); + const float grab_h_norm = grab_h_pixels / scrollbar_size_v; + + // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). + bool held = false; + bool hovered = false; + const bool previously_held = (g.ActiveId == id); + ImGui::ButtonBehavior(bb, id, &hovered, &held); + + float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); + float scroll_ratio = ImSaturate(scroll_v / scroll_max); + float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + if (held && grab_h_norm < 1.0f) + { + float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; + float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; + + // Click position in scrollbar normalized space (0.0f->1.0f) + const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); + ImGui::SetHoveredID(id); + + bool seek_absolute = false; + if (!previously_held) + { + // On initial click calculate the distance between mouse and the center of the grab + if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) + { + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; + } + else + { + seek_absolute = true; + *click_delta_to_grab_center_v = 0.0f; + } + } + + // Apply scroll + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position + const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); + scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); + if (horizontal) + window->Scroll.x = scroll_v; + else + window->Scroll.y = scroll_v; + + // Update values for rendering + scroll_ratio = ImSaturate(scroll_v / scroll_max); + grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + + // Update distance to grab now that we have seeked and saturated + if (seek_absolute) + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; + } + + // Render + const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); + if (horizontal) + window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding); + else + window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding); +} + +// Moving window to front of display (which happens to be back of our sorted list) +void ImGui::FocusWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + + // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing. + g.FocusedWindow = window; + + // Passing NULL allow to disable keyboard focus + if (!window) + return; + + // And move its root window to the top of the pile + if (window->RootWindow) + window = window->RootWindow; + + // Steal focus on active widgets + if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) + ClearActiveID(); + + // Bring to front + if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window) + return; + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i] == window) + { + g.Windows.erase(g.Windows.begin() + i); + break; + } + g.Windows.push_back(window); +} + +void ImGui::PushItemWidth(float item_width) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); +} + +static void PushMultiItemsWidths(int components, float w_full) +{ + ImGuiWindow* window = ImGui::GetCurrentWindow(); + const ImGuiStyle& style = GImGui->Style; + if (w_full <= 0.0f) + w_full = ImGui::CalcItemWidth(); + const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + window->DC.ItemWidthStack.push_back(w_item_last); + for (int i = 0; i < components-1; i++) + window->DC.ItemWidthStack.push_back(w_item_one); + window->DC.ItemWidth = window->DC.ItemWidthStack.back(); +} + +void ImGui::PopItemWidth() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ItemWidthStack.pop_back(); + window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); +} + +float ImGui::CalcItemWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + float w = window->DC.ItemWidth; + if (w < 0.0f) + { + // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. + float width_to_right_edge = GetContentRegionAvail().x; + w = ImMax(1.0f, width_to_right_edge + w); + } + w = (float)(int)w; + return w; +} + +static ImFont* GetDefaultFont() +{ + ImGuiContext& g = *GImGui; + return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; +} + +static void SetCurrentFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(font->Scale > 0.0f); + g.Font = font; + g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; + g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; + g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel; +} + +void ImGui::PushFont(ImFont* font) +{ + ImGuiContext& g = *GImGui; + if (!font) + font = GetDefaultFont(); + SetCurrentFont(font); + g.FontStack.push_back(font); + g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); +} + +void ImGui::PopFont() +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow->DrawList->PopTextureID(); + g.FontStack.pop_back(); + SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); +} + +void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.AllowKeyboardFocus = allow_keyboard_focus; + window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus); +} + +void ImGui::PopAllowKeyboardFocus() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.AllowKeyboardFocusStack.pop_back(); + window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back(); +} + +void ImGui::PushButtonRepeat(bool repeat) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ButtonRepeat = repeat; + window->DC.ButtonRepeatStack.push_back(repeat); +} + +void ImGui::PopButtonRepeat() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ButtonRepeatStack.pop_back(); + window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back(); +} + +void ImGui::PushTextWrapPos(float wrap_pos_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPos = wrap_pos_x; + window->DC.TextWrapPosStack.push_back(wrap_pos_x); +} + +void ImGui::PopTextWrapPos() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPosStack.pop_back(); + window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); +} + +void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) +{ + ImGuiContext& g = *GImGui; + ImGuiColMod backup; + backup.Col = idx; + backup.BackupValue = g.Style.Colors[idx]; + g.ColorModifiers.push_back(backup); + g.Style.Colors[idx] = col; +} + +void ImGui::PopStyleColor(int count) +{ + ImGuiContext& g = *GImGui; + while (count > 0) + { + ImGuiColMod& backup = g.ColorModifiers.back(); + g.Style.Colors[backup.Col] = backup.BackupValue; + g.ColorModifiers.pop_back(); + count--; + } +} + +struct ImGuiStyleVarInfo +{ + ImGuiDataType Type; + ImU32 Offset; + void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); } +}; + +static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] = +{ + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) }, // ImGuiStyleVar_ChildWindowRounding + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign +}; + +static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) +{ + IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_); + return &GStyleVarInfo[idx]; +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) +{ + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float) + { + float* pvar = (float*)var_info->GetVarPtr(); + GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a float. +} + +void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) +{ + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float2) + { + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(); + GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2. +} + +void ImGui::PopStyleVar(int count) +{ + ImGuiContext& g = *GImGui; + while (count > 0) + { + ImGuiStyleMod& backup = g.StyleModifiers.back(); + const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); + if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0]; + else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]); + else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0]; + g.StyleModifiers.pop_back(); + count--; + } +} + +const char* ImGui::GetStyleColName(ImGuiCol idx) +{ + // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; + switch (idx) + { + case ImGuiCol_Text: return "Text"; + case ImGuiCol_TextDisabled: return "TextDisabled"; + case ImGuiCol_WindowBg: return "WindowBg"; + case ImGuiCol_ChildWindowBg: return "ChildWindowBg"; + case ImGuiCol_PopupBg: return "PopupBg"; + case ImGuiCol_Border: return "Border"; + case ImGuiCol_BorderShadow: return "BorderShadow"; + case ImGuiCol_FrameBg: return "FrameBg"; + case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; + case ImGuiCol_FrameBgActive: return "FrameBgActive"; + case ImGuiCol_TitleBg: return "TitleBg"; + case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; + case ImGuiCol_TitleBgActive: return "TitleBgActive"; + case ImGuiCol_MenuBarBg: return "MenuBarBg"; + case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; + case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; + case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; + case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; + case ImGuiCol_ComboBg: return "ComboBg"; + case ImGuiCol_CheckMark: return "CheckMark"; + case ImGuiCol_SliderGrab: return "SliderGrab"; + case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; + case ImGuiCol_Button: return "Button"; + case ImGuiCol_ButtonHovered: return "ButtonHovered"; + case ImGuiCol_ButtonActive: return "ButtonActive"; + case ImGuiCol_Header: return "Header"; + case ImGuiCol_HeaderHovered: return "HeaderHovered"; + case ImGuiCol_HeaderActive: return "HeaderActive"; + case ImGuiCol_Column: return "Column"; + case ImGuiCol_ColumnHovered: return "ColumnHovered"; + case ImGuiCol_ColumnActive: return "ColumnActive"; + case ImGuiCol_ResizeGrip: return "ResizeGrip"; + case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; + case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; + case ImGuiCol_CloseButton: return "CloseButton"; + case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered"; + case ImGuiCol_CloseButtonActive: return "CloseButtonActive"; + case ImGuiCol_PlotLines: return "PlotLines"; + case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; + case ImGuiCol_PlotHistogram: return "PlotHistogram"; + case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; + case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; + case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening"; + } + IM_ASSERT(0); + return "Unknown"; +} + +bool ImGui::IsWindowHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow); +} + +bool ImGui::IsWindowFocused() +{ + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow; +} + +bool ImGui::IsRootWindowFocused() +{ + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow->RootWindow; +} + +bool ImGui::IsRootWindowOrAnyChildFocused() +{ + ImGuiContext& g = *GImGui; + return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow; +} + +bool ImGui::IsRootWindowOrAnyChildHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow); +} + +float ImGui::GetWindowWidth() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.x; +} + +float ImGui::GetWindowHeight() +{ + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.y; +} + +ImVec2 ImGui::GetWindowPos() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + return window->Pos; +} + +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) +{ + window->DC.CursorMaxPos.y += window->Scroll.y; + window->Scroll.y = new_scroll_y; + window->DC.CursorMaxPos.y -= window->Scroll.y; +} + +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowPosAllowFlags & cond) == 0) + return; + window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + window->SetWindowPosCenterWanted = false; + + // Set + const ImVec2 old_pos = window->Pos; + window->PosFloat = pos; + window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); + window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. +} + +void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + SetWindowPos(window, pos, cond); +} + +void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond) +{ + if (ImGuiWindow* window = FindWindowByName(name)) + SetWindowPos(window, pos, cond); +} + +ImVec2 ImGui::GetWindowSize() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->Size; +} + +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) + return; + window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + + // Set + if (size.x > 0.0f) + { + window->AutoFitFramesX = 0; + window->SizeFull.x = size.x; + } + else + { + window->AutoFitFramesX = 2; + window->AutoFitOnlyGrows = false; + } + if (size.y > 0.0f) + { + window->AutoFitFramesY = 0; + window->SizeFull.y = size.y; + } + else + { + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = false; + } +} + +void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond) +{ + SetWindowSize(GImGui->CurrentWindow, size, cond); +} + +void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond) +{ + ImGuiWindow* window = FindWindowByName(name); + if (window) + SetWindowSize(window, size, cond); +} + +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond) +{ + // Test condition (NB: bit 0 is always true) and clear flags for next time + if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) + return; + window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + + // Set + window->Collapsed = collapsed; +} + +void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond) +{ + SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); +} + +bool ImGui::IsWindowCollapsed() +{ + return GImGui->CurrentWindow->Collapsed; +} + +void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond) +{ + ImGuiWindow* window = FindWindowByName(name); + if (window) + SetWindowCollapsed(window, collapsed, cond); +} + +void ImGui::SetWindowFocus() +{ + FocusWindow(GImGui->CurrentWindow); +} + +void ImGui::SetWindowFocus(const char* name) +{ + if (name) + { + if (ImGuiWindow* window = FindWindowByName(name)) + FocusWindow(window); + } + else + { + FocusWindow(NULL); + } +} + +void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosVal = pos; + g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX); + g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowSizeVal = size; + g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowSizeConstraint = true; + g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max); + g.SetNextWindowSizeConstraintCallback = custom_callback; + g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data; +} + +void ImGui::SetNextWindowContentSize(const ImVec2& size) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = size; + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowContentWidth(float width) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f); + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowCollapsedVal = collapsed; + g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowFocus() +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowFocus = true; +} + +// In window space (not screen space!) +ImVec2 ImGui::GetContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImVec2 mx = window->ContentsRegionRect.Max; + if (window->DC.ColumnsCount != 1) + mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x; + return mx; +} + +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); +} + +float ImGui::GetContentRegionAvailWidth() +{ + return GetContentRegionAvail().x; +} + +// In window space (not screen space!) +ImVec2 ImGui::GetWindowContentRegionMin() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Min; +} + +ImVec2 ImGui::GetWindowContentRegionMax() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max; +} + +float ImGui::GetWindowContentRegionWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x; +} + +float ImGui::GetTextLineHeight() +{ + ImGuiContext& g = *GImGui; + return g.FontSize; +} + +float ImGui::GetTextLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.ItemSpacing.y; +} + +float ImGui::GetItemsLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; +} + +ImDrawList* ImGui::GetWindowDrawList() +{ + ImGuiWindow* window = GetCurrentWindow(); + return window->DrawList; +} + +ImFont* ImGui::GetFont() +{ + return GImGui->Font; +} + +float ImGui::GetFontSize() +{ + return GImGui->FontSize; +} + +ImVec2 ImGui::GetFontTexUvWhitePixel() +{ + return GImGui->FontTexUvWhitePixel; +} + +void ImGui::SetWindowFontScale(float scale) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->FontWindowScale = scale; + g.FontSize = window->CalcFontSize(); +} + +// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. +ImVec2 ImGui::GetCursorPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos - window->Pos + window->Scroll; +} + +float ImGui::GetCursorPosX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; +} + +float ImGui::GetCursorPosY() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; +} + +void ImGui::SetCursorPos(const ImVec2& local_pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = window->Pos - window->Scroll + local_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +void ImGui::SetCursorPosX(float x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); +} + +void ImGui::SetCursorPosY(float y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); +} + +ImVec2 ImGui::GetCursorStartPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorStartPos - window->Pos; +} + +ImVec2 ImGui::GetCursorScreenPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos; +} + +void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.CursorPos = screen_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); +} + +float ImGui::GetScrollX() +{ + return GImGui->CurrentWindow->Scroll.x; +} + +float ImGui::GetScrollY() +{ + return GImGui->CurrentWindow->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x; +} + +float ImGui::GetScrollMaxY() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y; +} + +void ImGui::SetScrollX(float scroll_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY + window->ScrollTargetCenterRatio.y = 0.0f; +} + +void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); + if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y) + window->ScrollTarget.y = 0.0f; + window->ScrollTargetCenterRatio.y = center_y_ratio; +} + +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHere(float center_y_ratio) +{ + ImGuiWindow* window = GetCurrentWindow(); + float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. + SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio); +} + +void ImGui::SetKeyboardFocusHere(int offset) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; + window->FocusIdxTabRequestNext = INT_MAX; +} + +void ImGui::SetStateStorage(ImGuiStorage* tree) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.StateStorage = tree ? tree : &window->StateStorage; +} + +ImGuiStorage* ImGui::GetStateStorage() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.StateStorage; +} + +void ImGui::TextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + TextUnformatted(g.TempBuffer, text_end); +} + +void ImGui::Text(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextV(fmt, args); + va_end(args); +} + +void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, col); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextColoredV(col, fmt, args); + va_end(args); +} + +void ImGui::TextDisabledV(const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextDisabled(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextDisabledV(fmt, args); + va_end(args); +} + +void ImGui::TextWrappedV(const char* fmt, va_list args) +{ + bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set + if (need_wrap) PushTextWrapPos(0.0f); + TextV(fmt, args); + if (need_wrap) PopTextWrapPos(); +} + +void ImGui::TextWrapped(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextWrappedV(fmt, args); + va_end(args); +} + +void ImGui::TextUnformatted(const char* text, const char* text_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + IM_ASSERT(text != NULL); + const char* text_begin = text; + if (text_end == NULL) + text_end = text + strlen(text); // FIXME-OPT + + const float wrap_pos_x = window->DC.TextWrapPos; + const bool wrap_enabled = wrap_pos_x >= 0.0f; + if (text_end - text > 2000 && !wrap_enabled) + { + // Long text! + // Perform manual coarse clipping to optimize for long multi-line text + // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. + const char* line = text; + const float line_height = GetTextLineHeight(); + const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset); + const ImRect clip_rect = window->ClipRect; + ImVec2 text_size(0,0); + + if (text_pos.y <= clip_rect.Max.y) + { + ImVec2 pos = text_pos; + + // Lines to skip (can't skip when logging text) + if (!g.LogEnabled) + { + int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); + if (lines_skippable > 0) + { + int lines_skipped = 0; + while (line < text_end && lines_skipped < lines_skippable) + { + const char* line_end = strchr(line, '\n'); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + } + + // Lines to render + if (line < text_end) + { + ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); + while (line < text_end) + { + const char* line_end = strchr(line, '\n'); + if (IsClippedEx(line_rect, NULL, false)) + break; + + const ImVec2 line_size = CalcTextSize(line, line_end, false); + text_size.x = ImMax(text_size.x, line_size.x); + RenderText(pos, line, line_end, false); + if (!line_end) + line_end = text_end; + line = line_end + 1; + line_rect.Min.y += line_height; + line_rect.Max.y += line_height; + pos.y += line_height; + } + + // Count remaining lines + int lines_skipped = 0; + while (line < text_end) + { + const char* line_end = strchr(line, '\n'); + if (!line_end) + line_end = text_end; + line = line_end + 1; + lines_skipped++; + } + pos.y += lines_skipped * line_height; + } + + text_size.y += (pos - text_pos).y; + } + + ImRect bb(text_pos, text_pos + text_size); + ItemSize(bb); + ItemAdd(bb, NULL); + } + else + { + const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; + const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); + + // Account of baseline offset + ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); + ImRect bb(text_pos, text_pos + text_size); + ItemSize(text_size); + if (!ItemAdd(bb, NULL)) + return; + + // Render (we don't hide text after ## in this end-user function) + RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); + } +} + +void ImGui::AlignFirstTextHeightToWidgets() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. + ImGuiContext& g = *GImGui; + ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y); + SameLine(0, 0); +} + +// Add a label+text combo aligned to other label+value widgets +void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); + const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, NULL)) + return; + + // Render + const char* value_text_begin = &g.TempBuffer[0]; + const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); +} + +void ImGui::LabelText(const char* label, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + LabelTextV(label, fmt, args); + va_end(args); +} + +static inline bool IsWindowContentHoverable(ImGuiWindow* window) +{ + // An active popup disable hovering on other windows (apart from its own children) + ImGuiContext& g = *GImGui; + if (ImGuiWindow* focused_window = g.FocusedWindow) + if (ImGuiWindow* focused_root_window = focused_window->RootWindow) + if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow) + return false; + + return true; +} + +bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (flags & ImGuiButtonFlags_Disabled) + { + if (out_hovered) *out_hovered = false; + if (out_held) *out_held = false; + if (g.ActiveId == id) ClearActiveID(); + return false; + } + + if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) + flags |= ImGuiButtonFlags_PressedOnClickRelease; + + bool pressed = false; + bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0); + if (hovered) + { + SetHoveredID(id); + if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) + { + // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat + // PressedOnClickRelease | * | .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds + // PressedOnClick | | .. + // PressedOnRelease | | .. (NOT on release) + // PressedOnDoubleClick | | .. + if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) + { + SetActiveID(id, window); // Hold on ID + FocusWindow(window); + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; + } + if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) + { + pressed = true; + ClearActiveID(); + FocusWindow(window); + } + if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) + { + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + pressed = true; + ClearActiveID(); + } + + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) + pressed = true; + } + } + + bool held = false; + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + held = true; + } + else + { + if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps + pressed = true; + ClearActiveID(); + } + } + + // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. + if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) + hovered = pressed = held = false; + + if (out_hovered) *out_hovered = hovered; + if (out_held) *out_held = held; + + return pressed; +} + +bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + ImVec2 pos = window->DC.CursorPos; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; + ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, &id)) + return false; + + if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + + // Render + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); + + // Automatically close popups + //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // CloseCurrentPopup(); + + return pressed; +} + +bool ImGui::Button(const char* label, const ImVec2& size_arg) +{ + return ButtonEx(label, size_arg, 0); +} + +// Small buttons fits within text without additional vertical spacing. +bool ImGui::SmallButton(const char* label) +{ + ImGuiContext& g = *GImGui; + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine); + g.Style.FramePadding.y = backup_padding_y; + return pressed; +} + +// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. +// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiID id = window->GetID(str_id); + ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + if (!ItemAdd(bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + return pressed; +} + +// Upper-right button to close a window. +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) +{ + ImGuiWindow* window = GetCurrentWindow(); + + const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); + const ImVec2 center = bb.GetCenter(); + window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12); + + const float cross_extent = (radius * 0.7071f) - 1.0f; + if (hovered) + { + window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text)); + window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text)); + } + + return pressed; +} + +void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + if (border_col.w > 0.0f) + bb.Max += ImVec2(2,2); + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + return; + + if (border_col.w > 0.0f) + { + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); + window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col)); + } + else + { + window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); + } +} + +// frame_padding < 0: uses FramePadding from style (default) +// frame_padding = 0: no framing +// frame_padding > 0: set framing size +// The color used are the button colors. +bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // Default to using texture ID as ID. User can still push string/integer prefixes. + // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. + PushID((void *)user_texture_id); + const ImGuiID id = window->GetID("#image"); + PopID(); + + const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2); + const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); + ItemSize(bb); + if (!ItemAdd(bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + + // Render + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); + if (bg_col.w > 0.0f) + window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); + window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); + + return pressed; +} + +// Start logging ImGui output to TTY +void ImGui::LogToTTY(int max_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = GetCurrentWindowRead(); + + g.LogEnabled = true; + g.LogFile = stdout; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to given file +void ImGui::LogToFile(int max_depth, const char* filename) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = GetCurrentWindowRead(); + + if (!filename) + { + filename = g.IO.LogFilename; + if (!filename) + return; + } + + g.LogFile = ImFileOpen(filename, "ab"); + if (!g.LogFile) + { + IM_ASSERT(g.LogFile != NULL); // Consider this an error + return; + } + g.LogEnabled = true; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +// Start logging ImGui output to clipboard +void ImGui::LogToClipboard(int max_depth) +{ + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + return; + ImGuiWindow* window = GetCurrentWindowRead(); + + g.LogEnabled = true; + g.LogFile = NULL; + g.LogStartDepth = window->DC.TreeDepth; + if (max_depth >= 0) + g.LogAutoExpandMaxDepth = max_depth; +} + +void ImGui::LogFinish() +{ + ImGuiContext& g = *GImGui; + if (!g.LogEnabled) + return; + + LogText(IM_NEWLINE); + g.LogEnabled = false; + if (g.LogFile != NULL) + { + if (g.LogFile == stdout) + fflush(g.LogFile); + else + fclose(g.LogFile); + g.LogFile = NULL; + } + if (g.LogClipboard->size() > 1) + { + SetClipboardText(g.LogClipboard->begin()); + g.LogClipboard->clear(); + } +} + +// Helper to display logging buttons +void ImGui::LogButtons() +{ + ImGuiContext& g = *GImGui; + + PushID("LogButtons"); + const bool log_to_tty = Button("Log To TTY"); SameLine(); + const bool log_to_file = Button("Log To File"); SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); + PushItemWidth(80.0f); + PushAllowKeyboardFocus(false); + SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); + PopAllowKeyboardFocus(); + PopItemWidth(); + PopID(); + + // Start logging at the end of the function so that the buttons don't appear in the log + if (log_to_tty) + LogToTTY(g.LogAutoExpandMaxDepth); + if (log_to_file) + LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); + if (log_to_clipboard) + LogToClipboard(g.LogAutoExpandMaxDepth); +} + +bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) +{ + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; + + // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiStorage* storage = window->DC.StateStorage; + + bool is_open; + if (g.SetNextTreeNodeOpenCond != 0) + { + if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always) + { + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); + } + else + { + // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently. + const int stored_value = storage->GetInt(id, -1); + if (stored_value == -1) + { + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); + } + else + { + is_open = stored_value != 0; + } + } + g.SetNextTreeNodeOpenCond = 0; + } + else + { + is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; + } + + // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) + is_open = true; + + return is_open; +} + +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; + const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); + + if (!label_end) + label_end = FindRenderedTextEnd(label); + const ImVec2 label_size = CalcTextSize(label, label_end, false); + + // We vertically grow up to current line height up the typical widget height. + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it + const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); + if (display_frame) + { + // Framed header expand a little outside the default padding + bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; + bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; + } + + const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser + ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); + + // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing + // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not) + const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y); + bool is_open = TreeNodeBehaviorIsOpen(id, flags); + if (!ItemAdd(interact_bb, &id)) + { + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; + } + + // Flags that affects opening behavior: + // - 0(default) ..................... single-click anywhere to open + // - OpenOnDoubleClick .............. double-click anywhere to open + // - OpenOnArrow .................... single-click on arrow to open + // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open + ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); + bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf)) + { + bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)); + if (flags & ImGuiTreeNodeFlags_OpenOnArrow) + toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + toggled |= g.IO.MouseDoubleClicked[0]; + if (toggled) + { + is_open = !is_open; + window->DC.StateStorage->SetInt(id, is_open); + } + } + if (flags & ImGuiTreeNodeFlags_AllowOverlapMode) + SetItemAllowOverlap(); + + // Render + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y); + if (display_frame) + { + // Framed type + RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f); + if (g.LogEnabled) + { + // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. + const char log_prefix[] = "\n##"; + const char log_suffix[] = "##"; + LogRenderedText(text_pos, log_prefix, log_prefix+3); + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); + LogRenderedText(text_pos, log_suffix+1, log_suffix+3); + } + else + { + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); + } + } + else + { + // Unframed typed for tree nodes + if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) + RenderFrame(bb.Min, bb.Max, col, false); + + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); + else if (!(flags & ImGuiTreeNodeFlags_Leaf)) + RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f); + if (g.LogEnabled) + LogRenderedText(text_pos, ">"); + RenderText(text_pos, label, label_end, false); + } + + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; +} + +// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). +// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). +bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label); +} + +bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + if (p_open && !*p_open) + return false; + + ImGuiID id = window->GetID(label); + bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label); + if (p_open) + { + // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + ImGuiContext& g = *GImGui; + float button_sz = g.FontSize * 0.5f; + if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz)) + *p_open = false; + } + + return is_open; +} + +bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + return TreeNodeBehavior(window->GetID(label), flags, label, NULL); +} + +bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); +} + +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + return TreeNodeExV(str_id, 0, fmt, args); +} + +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + return TreeNodeExV(ptr_id, 0, fmt, args); +} + +bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + return TreeNodeBehavior(window->GetID(label), 0, label, NULL); +} + +void ImGui::TreeAdvanceToLabelPos() +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); +} + +// Horizontal distance preceding label when using TreeNode() or Bullet() +float ImGui::GetTreeNodeToLabelSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + (g.Style.FramePadding.x * 2.0f); +} + +void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextTreeNodeOpenVal = is_open; + g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always; +} + +void ImGui::PushID(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(str_id)); +} + +void ImGui::PushID(const char* str_id_begin, const char* str_id_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(str_id_begin, str_id_end)); +} + +void ImGui::PushID(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(ptr_id)); +} + +void ImGui::PushID(int int_id) +{ + const void* ptr_id = (void*)(intptr_t)int_id; + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(ptr_id)); +} + +void ImGui::PopID() +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.pop_back(); +} + +ImGuiID ImGui::GetID(const char* str_id) +{ + return GImGui->CurrentWindow->GetID(str_id); +} + +ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) +{ + return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end); +} + +ImGuiID ImGui::GetID(const void* ptr_id) +{ + return GImGui->CurrentWindow->GetID(ptr_id); +} + +void ImGui::Bullet() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + { + SameLine(0, style.FramePadding.x*2); + return; + } + + // Render and stay on same line + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + SameLine(0, style.FramePadding.x*2); +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const char* text_begin = g.TempBuffer; + const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + return; + + // Render + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + ImFormatString(buf, buf_size, display_format, *(int*)data_ptr); + else if (data_type == ImGuiDataType_Float) + ImFormatString(buf, buf_size, display_format, *(float*)data_ptr); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%d", *(int*)data_ptr); + else + ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr); + } + else if (data_type == ImGuiDataType_Float) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? + else + ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr); + } +} + +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1 +{ + if (data_type == ImGuiDataType_Int) + { + if (op == '+') + *(int*)value1 = *(int*)value1 + *(const int*)value2; + else if (op == '-') + *(int*)value1 = *(int*)value1 - *(const int*)value2; + } + else if (data_type == ImGuiDataType_Float) + { + if (op == '+') + *(float*)value1 = *(float*)value1 + *(const float*)value2; + else if (op == '-') + *(float*)value1 = *(float*)value1 - *(const float*)value2; + } +} + +// User can input math operators (e.g. +100) to edit a numerical values. +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format) +{ + while (ImCharIsSpace(*buf)) + buf++; + + // We don't support '-' op because it would conflict with inputing negative value. + // Instead you can use +-100 to subtract from an existing value + char op = buf[0]; + if (op == '+' || op == '*' || op == '/') + { + buf++; + while (ImCharIsSpace(*buf)) + buf++; + } + else + { + op = 0; + } + if (!buf[0]) + return false; + + if (data_type == ImGuiDataType_Int) + { + if (!scalar_format) + scalar_format = "%d"; + int* v = (int*)data_ptr; + const int old_v = *v; + int arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; + + // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision + float arg1 = 0.0f; + if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract) + else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply + else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide + else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant + return (old_v != *v); + } + else if (data_type == ImGuiDataType_Float) + { + // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in + scalar_format = "%f"; + float* v = (float*)data_ptr; + const float old_v = *v; + float arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; + + float arg1 = 0.0f; + if (sscanf(buf, scalar_format, &arg1) < 1) + return false; + if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract) + else if (op == '*') { *v = arg0 * arg1; } // Multiply + else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide + else { *v = arg1; } // Assign constant + return (old_v != *v); + } + + return false; +} + +// Create text input in place of a slider (when CTRL+Clicking on slider) +bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) + SetActiveID(g.ScalarAsInputTextId, window); + SetHoveredID(0); + FocusableItemUnregister(window); + + char buf[32]; + DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf)); + bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); + if (g.ScalarAsInputTextId == 0) + { + // First frame + IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible) + g.ScalarAsInputTextId = g.ActiveId; + SetHoveredID(id); + } + else if (g.ActiveId != g.ScalarAsInputTextId) + { + // Release + g.ScalarAsInputTextId = 0; + } + if (text_value_changed) + return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL); + return false; +} + +// Parse display precision back from the display format string +int ImGui::ParseFormatPrecision(const char* fmt, int default_precision) +{ + int precision = default_precision; + while ((fmt = strchr(fmt, '%')) != NULL) + { + fmt++; + if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%" + while (*fmt >= '0' && *fmt <= '9') + fmt++; + if (*fmt == '.') + { + precision = atoi(fmt + 1); + if (precision < 0 || precision > 10) + precision = default_precision; + } + break; + } + return precision; +} + +float ImGui::RoundScalar(float value, int decimal_precision) +{ + // Round past decimal precision + // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 + // FIXME: Investigate better rounding methods + static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; + float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision); + bool negative = value < 0.0f; + value = fabsf(value); + float remainder = fmodf(value, min_step); + if (remainder <= min_step*0.5f) + value -= remainder; + else + value += (min_step - remainder); + return negative ? -value : value; +} + +static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos) +{ + if (v_min == v_max) + return 0.0f; + + const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); + const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); + if (is_non_linear) + { + if (v_clamped < 0.0f) + { + const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min); + return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos; + } + else + { + const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min)); + return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos); + } + } + + // Linear slider + return (v_clamped - v_min) / (v_max - v_min); +} + +bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + const ImGuiStyle& style = g.Style; + + // Draw frame + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f); + const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0; + + const float grab_padding = 2.0f; + const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f); + float grab_sz; + if (decimal_precision > 0) + grab_sz = ImMin(style.GrabMinSize, slider_sz); + else + grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit + const float slider_usable_sz = slider_sz - grab_sz; + const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f; + const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f; + + // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f + float linear_zero_pos = 0.0f; // 0.0->1.0f + if (v_min * v_max < 0.0f) + { + // Different sign + const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power); + const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power); + linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0); + } + else + { + // Same sign + linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; + } + + // Process clicking on the slider + bool value_changed = false; + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + float clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; + if (!is_horizontal) + clicked_t = 1.0f - clicked_t; + + float new_value; + if (is_non_linear) + { + // Account for logarithmic scale on both sides of the zero + if (clicked_t < linear_zero_pos) + { + // Negative: rescale to the negative range before powering + float a = 1.0f - (clicked_t / linear_zero_pos); + a = powf(a, power); + new_value = ImLerp(ImMin(v_max,0.0f), v_min, a); + } + else + { + // Positive: rescale to the positive range before powering + float a; + if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f) + a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); + else + a = clicked_t; + a = powf(a, power); + new_value = ImLerp(ImMax(v_min,0.0f), v_max, a); + } + } + else + { + // Linear slider + new_value = ImLerp(v_min, v_max, clicked_t); + } + + // Round past decimal precision + new_value = RoundScalar(new_value, decimal_precision); + if (*v != new_value) + { + *v = new_value; + value_changed = true; + } + } + else + { + ClearActiveID(); + } + } + + // Calculate slider grab positioning + float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos); + + // Draw + if (!is_horizontal) + grab_t = 1.0f - grab_t; + const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); + ImRect grab_bb; + if (is_horizontal) + grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding)); + else + grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f)); + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); + + return value_changed; +} + +// Use power!=1.0 for logarithmic sliders. +// Adjust display_format to decorate the value with a prefix or a suffix. +// "%.3f" 1.234 +// "%5.2f secs" 01.23 secs +// "Gold: %.0f" Gold: 1 +bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + // NB- we don't call ItemSize() yet because we may turn into a text edit box below + if (!ItemAdd(total_bb, &id)) + { + ItemSize(total_bb, style.FramePadding.y); + return false; + } + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + SetHoveredID(id); + + if (!display_format) + display_format = "%.3f"; + int decimal_precision = ParseFormatPrecision(display_format, 3); + + // Tabbing or CTRL-clicking on Slider turns it into an input box + bool start_text_input = false; + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); + if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) + { + SetActiveID(id, window); + FocusWindow(window); + + if (tab_focus_requested || g.IO.KeyCtrl) + { + start_text_input = true; + g.ScalarAsInputTextId = 0; + } + } + if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); + + ItemSize(total_bb, style.FramePadding.y); + + // Actual slider behavior + render grab + const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(frame_bb, &id)) + return false; + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + SetHoveredID(id); + + if (!display_format) + display_format = "%.3f"; + int decimal_precision = ParseFormatPrecision(display_format, 3); + + if (hovered && g.IO.MouseClicked[0]) + { + SetActiveID(id, window); + FocusWindow(window); + } + + // Actual slider behavior + render grab + bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + // For the vertical slider we allow centered text to overlap the frame padding + char value_buf[64]; + char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + return value_changed; +} + +bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max) +{ + float v_deg = (*v_rad) * 360.0f / (2*IM_PI); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); + *v_rad = v_deg * (2*IM_PI) / 360.0f; + return value_changed; +} + +bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format) +{ + if (!display_format) + display_format = "%.0f"; + float v_f = (float)*v; + bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + *v = (int)v_f; + return value_changed; +} + +bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format) +{ + if (!display_format) + display_format = "%.0f"; + float v_f = (float)*v; + bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + *v = (int)v_f; + return value_changed; +} + +// Add multiple sliders on 1 line for compact edition of multiple components +bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 2, v_min, v_max, display_format, power); +} + +bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 3, v_min, v_max, display_format, power); +} + +bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power) +{ + return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); +} + +bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format) +{ + return SliderIntN(label, v, 2, v_min, v_max, display_format); +} + +bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format) +{ + return SliderIntN(label, v, 3, v_min, v_max, display_format); +} + +bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format) +{ + return SliderIntN(label, v, 4, v_min, v_max, display_format); +} + +bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) +{ + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + // Draw frame + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); + + bool value_changed = false; + + // Process clicking on the drag + if (g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + if (g.ActiveIdIsJustActivated) + { + // Lock current value on click + g.DragCurrentValue = *v; + g.DragLastMouseDelta = ImVec2(0.f, 0.f); + } + + float v_cur = g.DragCurrentValue; + const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f); + if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f) + { + float speed = v_speed; + if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX) + speed = (v_max - v_min) * g.DragSpeedDefaultRatio; + if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f) + speed = speed * g.DragSpeedScaleFast; + if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) + speed = speed * g.DragSpeedScaleSlow; + + float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed; + if (fabsf(power - 1.0f) > 0.001f) + { + // Logarithmic curve on both side of 0.0 + float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur; + float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f; + float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign); + float v1_abs = v1 >= 0.0f ? v1 : -v1; + float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line + v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign + } + else + { + v_cur += delta; + } + g.DragLastMouseDelta.x = mouse_drag_delta.x; + + // Clamp + if (v_min < v_max) + v_cur = ImClamp(v_cur, v_min, v_max); + g.DragCurrentValue = v_cur; + } + + // Round to user desired precision, then apply + v_cur = RoundScalar(v_cur, decimal_precision); + if (*v != v_cur) + { + *v = v_cur; + value_changed = true; + } + } + else + { + ClearActiveID(); + } + } + + return value_changed; +} + +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + + // NB- we don't call ItemSize() yet because we may turn into a text edit box below + if (!ItemAdd(total_bb, &id)) + { + ItemSize(total_bb, style.FramePadding.y); + return false; + } + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + SetHoveredID(id); + + if (!display_format) + display_format = "%.3f"; + int decimal_precision = ParseFormatPrecision(display_format, 3); + + // Tabbing or CTRL-clicking on Drag turns it into an input box + bool start_text_input = false; + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); + if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0]))) + { + SetActiveID(id, window); + FocusWindow(window); + + if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0]) + { + start_text_input = true; + g.ScalarAsInputTextId = 0; + } + } + if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); + + // Actual drag behavior + ItemSize(total_bb, style.FramePadding.y); + const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); + + // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + char value_buf[64]; + const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + + return value_changed; +} + +bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +// NB: v_speed is float to allow adjusting the drag speed with more precision +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format) +{ + if (!display_format) + display_format = "%.0f"; + float v_f = (float)*v; + bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); + *v = (int)v_f; + return value_changed; +} + +bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + if (graph_size.x == 0.0f) + graph_size.x = CalcItemWidth(); + if (graph_size.y == 0.0f) + graph_size.y = label_size.y + (style.FramePadding.y * 2); + + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); + const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, NULL)) + return; + + // Determine scale from values if not specified + if (scale_min == FLT_MAX || scale_max == FLT_MAX) + { + float v_min = FLT_MAX; + float v_max = -FLT_MAX; + for (int i = 0; i < values_count; i++) + { + const float v = values_getter(data, i); + v_min = ImMin(v_min, v); + v_max = ImMax(v_max, v); + } + if (scale_min == FLT_MAX) + scale_min = v_min; + if (scale_max == FLT_MAX) + scale_max = v_max; + } + + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + if (values_count > 0) + { + int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + + // Tooltip on hover + int v_hovered = -1; + if (IsHovered(inner_bb, 0)) + { + const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); + const int v_idx = (int)(t * item_count); + IM_ASSERT(v_idx >= 0 && v_idx < values_count); + + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); + const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); + if (plot_type == ImGuiPlotType_Lines) + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + else if (plot_type == ImGuiPlotType_Histogram) + SetTooltip("%d: %8.4g", v_idx, v0); + v_hovered = v_idx; + } + + const float t_step = 1.0f / (float)res_w; + + float v0 = values_getter(data, (0 + values_offset) % values_count); + float t0 = 0.0f; + ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle + + const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + + for (int n = 0; n < res_w; n++) + { + const float t1 = t0 + t_step; + const int v1_idx = (int)(t0 * item_count + 0.5f); + IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); + const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); + const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); + + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); + ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f)); + if (plot_type == ImGuiPlotType_Lines) + { + window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } + else if (plot_type == ImGuiPlotType_Histogram) + { + if (pos1.x >= pos0.x + 2.0f) + pos1.x -= 1.0f; + window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } + + t0 = t1; + tp0 = tp1; + } + } + + // Text overlay + if (overlay_text) + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); + + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); +} + +struct ImGuiPlotArrayGetterData +{ + const float* Values; + int Stride; + + ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } +}; + +static float Plot_ArrayGetter(void* data, int idx) +{ + ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; + const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); + return v; +} + +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) +{ + ImGuiPlotArrayGetterData data(values, stride); + PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) +{ + PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, NULL)) + return; + + // Render + fraction = ImSaturate(fraction); + RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + bb.Reduce(ImVec2(window->BorderSize, window->BorderSize)); + const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); + RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding); + + // Default displaying the fraction as percentage string, but user can override it + char overlay_buf[32]; + if (!overlay) + { + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); + overlay = overlay_buf; + } + + ImVec2 overlay_size = CalcTextSize(overlay, NULL); + if (overlay_size.x > 0.0f) + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); +} + +bool ImGui::Checkbox(const char* label, bool* v) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); + ItemSize(check_bb, style.FramePadding.y); + + ImRect total_bb = check_bb; + if (label_size.x > 0) + SameLine(0, style.ItemInnerSpacing.x); + const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); + if (label_size.x > 0) + { + ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); + total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); + } + + if (!ItemAdd(total_bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + if (pressed) + *v = !(*v); + + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + if (*v) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding); + } + + if (g.LogEnabled) + LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); + + return pressed; +} + +bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) +{ + bool v = ((*flags & flags_value) == flags_value); + bool pressed = Checkbox(label, &v); + if (pressed) + { + if (v) + *flags |= flags_value; + else + *flags &= ~flags_value; + } + + return pressed; +} + +bool ImGui::RadioButton(const char* label, bool active) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); + ItemSize(check_bb, style.FramePadding.y); + + ImRect total_bb = check_bb; + if (label_size.x > 0) + SameLine(0, style.ItemInnerSpacing.x); + const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); + if (label_size.x > 0) + { + ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); + total_bb.Add(text_bb); + } + + if (!ItemAdd(total_bb, &id)) + return false; + + ImVec2 center = check_bb.GetCenter(); + center.x = (float)(int)center.x + 0.5f; + center.y = (float)(int)center.y + 0.5f; + const float radius = check_bb.GetHeight() * 0.5f; + + bool hovered, held; + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + + window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); + if (active) + { + const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); + } + + if (window->Flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16); + window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16); + } + + if (g.LogEnabled) + LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); + + return pressed; +} + +bool ImGui::RadioButton(const char* label, int* v, int v_button) +{ + const bool pressed = RadioButton(label, *v == v_button); + if (pressed) + { + *v = v_button; + } + return pressed; +} + +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) +{ + int line_count = 0; + const char* s = text_begin; + while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding + if (c == '\n') + line_count++; + s--; + if (s[0] != '\n' && s[0] != '\r') + line_count++; + *out_text_end = s; + return line_count; +} + +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) +{ + ImFont* font = GImGui->Font; + const float line_height = GImGui->FontSize; + const float scale = line_height / font->FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const ImWchar* s = text_begin; + while (s < text_end) + { + unsigned int c = (unsigned int)(*s++); + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + if (stop_on_new_line) + break; + continue; + } + if (c == '\r') + continue; + + const float char_width = font->GetCharAdvance((unsigned short)c) * scale; + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (out_offset) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) +namespace ImGuiStb +{ + +static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } +static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } +static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } +static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; +static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) +{ + const ImWchar* text = obj->Text.Data; + const ImWchar* text_remaining = NULL; + const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); + r->x0 = 0.0f; + r->x1 = size.x; + r->baseline_y_delta = size.y; + r->ymin = 0.0f; + r->ymax = size.y; + r->num_chars = (int)(text_remaining - (text + line_start_idx)); +} + +static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } +static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } +#ifdef __APPLE__ // FIXME: Move setting to IO structure +static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } +#else +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } +#endif +#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL + +static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) +{ + ImWchar* dst = obj->Text.Data + pos; + + // We maintain our buffer length in both UTF-8 and wchar formats + obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); + obj->CurLenW -= n; + + // Offset remaining text + const ImWchar* src = obj->Text.Data + pos + n; + while (ImWchar c = *src++) + *dst++ = c; + *dst = '\0'; +} + +static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) +{ + const int text_len = obj->CurLenW; + IM_ASSERT(pos <= text_len); + if (new_text_len + text_len + 1 > obj->Text.Size) + return false; + + const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); + if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) + return false; + + ImWchar* text = obj->Text.Data; + if (pos != text_len) + memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); + memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + + obj->CurLenW += new_text_len; + obj->CurLenA += new_text_len_utf8; + obj->Text[obj->CurLenW] = '\0'; + + return true; +} + +// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) +#define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left +#define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right +#define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up +#define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down +#define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line +#define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line +#define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text +#define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text +#define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor +#define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor +#define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo +#define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo +#define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word +#define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word +#define STB_TEXTEDIT_K_SHIFT 0x20000 + +#define STB_TEXTEDIT_IMPLEMENTATION +#include "stb_textedit.h" + +} + +void ImGuiTextEditState::OnKeyPressed(int key) +{ + stb_textedit_key(this, &StbState, key); + CursorFollow = true; + CursorAnimReset(); +} + +// Public API to manipulate UTF-8 text +// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) +// FIXME: The existence of this rarely exercised code path is a bit of a nuisance. +void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) +{ + IM_ASSERT(pos + bytes_count <= BufTextLen); + char* dst = Buf + pos; + const char* src = Buf + pos + bytes_count; + while (char c = *src++) + *dst++ = c; + *dst = '\0'; + + if (CursorPos + bytes_count >= pos) + CursorPos -= bytes_count; + else if (CursorPos >= pos) + CursorPos = pos; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen -= bytes_count; +} + +void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) +{ + const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + if (new_text_len + BufTextLen + 1 >= BufSize) + return; + + if (BufTextLen != pos) + memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); + memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + Buf[BufTextLen + new_text_len] = '\0'; + + if (CursorPos >= pos) + CursorPos += new_text_len; + SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen += new_text_len; +} + +// Return false to discard a character. +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + unsigned int c = *p_char; + + if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) + { + bool pass = false; + pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); + pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); + if (!pass) + return false; + } + + if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. + return false; + + if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank)) + { + if (flags & ImGuiInputTextFlags_CharsDecimal) + if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) + return false; + + if (flags & ImGuiInputTextFlags_CharsHexadecimal) + if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) + return false; + + if (flags & ImGuiInputTextFlags_CharsUppercase) + if (c >= 'a' && c <= 'z') + *p_char = (c += (unsigned int)('A'-'a')); + + if (flags & ImGuiInputTextFlags_CharsNoBlank) + if (ImCharIsSpace(c)) + return false; + } + + if (flags & ImGuiInputTextFlags_CallbackCharFilter) + { + ImGuiTextEditCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); + callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; + callback_data.EventChar = (ImWchar)c; + callback_data.Flags = flags; + callback_data.UserData = user_data; + if (callback(&callback_data) != 0) + return false; + *p_char = callback_data.EventChar; + if (!callback_data.EventChar) + return false; + } + + return true; +} + +// Edit a string of text +// NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect. +// FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188 +bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) + + ImGuiContext& g = *GImGui; + const ImGuiIO& io = g.IO; + const ImGuiStyle& style = g.Style; + + const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; + const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; + const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; + + if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn + BeginGroup(); + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); + + ImGuiWindow* draw_window = window; + if (is_multiline) + { + if (!BeginChildFrame(id, frame_bb.GetSize())) + { + EndChildFrame(); + EndGroup(); + return false; + } + draw_window = GetCurrentWindow(); + size.x -= draw_window->ScrollbarSizes.x; + } + else + { + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, &id)) + return false; + } + + // Password pushes a temporary font with only a fallback glyph + if (is_password) + { + const ImFont::Glyph* glyph = g.Font->FindGlyph('*'); + ImFont* password_font = &g.InputTextPasswordFont; + password_font->FontSize = g.Font->FontSize; + password_font->Scale = g.Font->Scale; + password_font->DisplayOffset = g.Font->DisplayOffset; + password_font->Ascent = g.Font->Ascent; + password_font->Descent = g.Font->Descent; + password_font->ContainerAtlas = g.Font->ContainerAtlas; + password_font->FallbackGlyph = glyph; + password_font->FallbackXAdvance = glyph->XAdvance; + IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty()); + PushFont(password_font); + } + + // NB: we are only allowed to access 'edit_state' if we are the active widget. + ImGuiTextEditState& edit_state = g.InputTextState; + + const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing + const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); + const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; + + const bool hovered = IsHovered(frame_bb, id); + if (hovered) + { + SetHoveredID(id); + g.MouseCursor = ImGuiMouseCursor_TextInput; + } + const bool user_clicked = hovered && io.MouseClicked[0]; + const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY"); + + bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; + if (focus_requested || user_clicked || user_scrolled) + { + if (g.ActiveId != id) + { + // Start edition + // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) + // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int prev_len_w = edit_state.CurLenW; + edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. + edit_state.CursorAnimReset(); + + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). + const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW); + if (recycle_state) + { + // Recycle existing cursor/selection/undo stack but clamp position + // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. + edit_state.CursorClamp(); + } + else + { + edit_state.Id = id; + edit_state.ScrollX = 0.0f; + stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); + if (!is_multiline && focus_requested_by_code) + select_all = true; + } + if (flags & ImGuiInputTextFlags_AlwaysInsertMode) + edit_state.StbState.insert_mode = true; + if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) + select_all = true; + } + SetActiveID(id, window); + FocusWindow(window); + } + else if (io.MouseClicked[0]) + { + // Release focus when we click outside + if (g.ActiveId == id) + ClearActiveID(); + } + + bool value_changed = false; + bool enter_pressed = false; + + if (g.ActiveId == id) + { + if (!is_editable && !g.ActiveIdIsJustActivated) + { + // When read-only we always use the live data passed to the function + edit_state.Text.resize(buf_size+1); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); + edit_state.CursorClamp(); + } + + edit_state.BufSizeA = buf_size; + + // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. + // Down the line we should have a cleaner library-wide concept of Selected vs Active. + g.ActiveIdAllowOverlap = !io.MouseDown[0]; + + // Edit in progress + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; + const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); + + const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text + if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0])) + { + edit_state.SelectAll(); + edit_state.SelectedAllMouseLock = true; + } + else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0]) + { + // Select a word only, OS X style (by simulating keystrokes) + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + } + else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) + { + stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + edit_state.CursorAnimReset(); + } + else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + { + stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); + edit_state.CursorAnimReset(); + edit_state.CursorFollow = true; + } + if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) + edit_state.SelectedAllMouseLock = false; + + if (io.InputCharacters[0]) + { + // Process text input (before we check for Return because using some IME will effectively send a Return?) + // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters. + if (!(io.KeyCtrl && !io.KeyAlt) && is_editable) + { + for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++) + if (unsigned int c = (unsigned int)io.InputCharacters[n]) + { + // Insert character if they pass filtering + if (!InputTextFilterCharacter(&c, flags, callback, user_data)) + continue; + edit_state.OnKeyPressed((int)c); + } + } + + // Consume characters + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + } + + // Handle various key-presses + bool cancel_edit = false; + const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); + const bool is_shortcut_key_only = (io.OSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl + const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl + const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End + + if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) + { + if (!edit_state.HasSelection()) + { + if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); + else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); + } + edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); + } + else if (IsKeyPressedMap(ImGuiKey_Enter)) + { + bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; + if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) + { + ClearActiveID(); + enter_pressed = true; + } + else if (is_editable) + { + unsigned int c = '\n'; // Insert new line + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + } + else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + else if (IsKeyPressedMap(ImGuiKey_Escape)) { ClearActiveID(); cancel_edit = true; } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; } + else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection())) + { + // Cut, Copy + const bool cut = IsKeyPressedMap(ImGuiKey_X); + if (cut && !edit_state.HasSelection()) + edit_state.SelectAll(); + + if (io.SetClipboardTextFn) + { + const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; + const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; + edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie); + SetClipboardText(edit_state.TempTextBuffer.Data); + } + + if (cut) + { + edit_state.CursorFollow = true; + stb_textedit_cut(&edit_state, &edit_state.StbState); + } + } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable) + { + // Paste + if (const char* clipboard = GetClipboardText()) + { + // Filter pasted buffer + const int clipboard_len = (int)strlen(clipboard); + ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); + int clipboard_filtered_len = 0; + for (const char* s = clipboard; *s; ) + { + unsigned int c; + s += ImTextCharFromUtf8(&c, s, NULL); + if (c == 0) + break; + if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data)) + continue; + clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; + } + clipboard_filtered[clipboard_filtered_len] = 0; + if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation + { + stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); + edit_state.CursorFollow = true; + } + ImGui::MemFree(clipboard_filtered); + } + } + + if (cancel_edit) + { + // Restore initial value + if (is_editable) + { + ImStrncpy(buf, edit_state.InitialText.Data, buf_size); + value_changed = true; + } + } + else + { + // Apply new value immediately - copy modified buffer back + // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer + // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. + // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. + if (is_editable) + { + edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL); + } + + // User callback + if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) + { + IM_ASSERT(callback != NULL); + + // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + ImGuiInputTextFlags event_flag = 0; + ImGuiKey event_key = ImGuiKey_COUNT; + if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) + { + event_flag = ImGuiInputTextFlags_CallbackCompletion; + event_key = ImGuiKey_Tab; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_UpArrow; + } + else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) + { + event_flag = ImGuiInputTextFlags_CallbackHistory; + event_key = ImGuiKey_DownArrow; + } + else if (flags & ImGuiInputTextFlags_CallbackAlways) + event_flag = ImGuiInputTextFlags_CallbackAlways; + + if (event_flag) + { + ImGuiTextEditCallbackData callback_data; + memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); + callback_data.EventFlag = event_flag; + callback_data.Flags = flags; + callback_data.UserData = user_data; + callback_data.ReadOnly = !is_editable; + + callback_data.EventKey = event_key; + callback_data.Buf = edit_state.TempTextBuffer.Data; + callback_data.BufTextLen = edit_state.CurLenA; + callback_data.BufSize = edit_state.BufSizeA; + callback_data.BufDirty = false; + + // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) + ImWchar* text = edit_state.Text.Data; + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); + + // Call user code + callback(&callback_data); + + // Read back what user may have modified + IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields + IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA); + IM_ASSERT(callback_data.Flags == flags); + if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); + if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); + if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); + if (callback_data.BufDirty) + { + IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL); + edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() + edit_state.CursorAnimReset(); + } + } + } + + // Copy back to user buffer + if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0) + { + ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size); + value_changed = true; + } + } + } + + // Render + // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on. + const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL; + + if (!is_multiline) + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size + ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.f, 0.f); + const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY")); + if (g.ActiveId == id || is_currently_scrolling) + { + edit_state.CursorAnim += io.DeltaTime; + + // This is going to be messy. We need to: + // - Display the text (this alone can be more easily clipped) + // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + // - Measure text height (for scrollbar) + // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) + // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. + const ImWchar* text_begin = edit_state.Text.Data; + ImVec2 cursor_offset, select_start_offset; + + { + // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. + const ImWchar* searches_input_ptr[2]; + searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; + searches_input_ptr[1] = NULL; + int searches_remaining = 1; + int searches_result_line_number[2] = { -1, -999 }; + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + searches_result_line_number[1] = -1; + searches_remaining++; + } + + // Iterate all lines to find our line numbers + // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. + searches_remaining += is_multiline ? 1 : 0; + int line_count = 0; + for (const ImWchar* s = text_begin; *s != 0; s++) + if (*s == '\n') + { + line_count++; + if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } + } + line_count++; + if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; + if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; + + // Calculate 2d position by finding the beginning of the line and measuring distance + cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; + cursor_offset.y = searches_result_line_number[0] * g.FontSize; + if (searches_result_line_number[1] >= 0) + { + select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; + select_start_offset.y = searches_result_line_number[1] * g.FontSize; + } + + // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) + if (is_multiline) + text_size = ImVec2(size.x, line_count * g.FontSize); + } + + // Scroll + if (edit_state.CursorFollow) + { + // Horizontal scroll in chunks of quarter width + if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) + { + const float scroll_increment_x = size.x * 0.25f; + if (cursor_offset.x < edit_state.ScrollX) + edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); + else if (cursor_offset.x - size.x >= edit_state.ScrollX) + edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); + } + else + { + edit_state.ScrollX = 0.0f; + } + + // Vertical scroll + if (is_multiline) + { + float scroll_y = draw_window->Scroll.y; + if (cursor_offset.y - g.FontSize < scroll_y) + scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + else if (cursor_offset.y - size.y >= scroll_y) + scroll_y = cursor_offset.y - size.y; + draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag + draw_window->Scroll.y = scroll_y; + render_pos.y = draw_window->DC.CursorPos.y; + } + } + edit_state.CursorFollow = false; + const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); + + // Draw selection + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); + + float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); + ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; + for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) + { + if (rect_pos.y > clip_rect.w + g.FontSize) + break; + if (rect_pos.y < clip_rect.y) + { + while (p < text_selected_end) + if (*p++ == '\n') + break; + } + else + { + ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); + if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines + ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); + rect.Clip(clip_rect); + if (rect.Overlaps(clip_rect)) + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } + rect_pos.x = render_pos.x - render_scroll.x; + rect_pos.y += g.FontSize; + } + } + + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect); + + // Draw blinking cursor + bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + if (is_editable) + g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); + } + else + { + // Render text only + const char* buf_end = NULL; + if (is_multiline) + text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); + } + + if (is_multiline) + { + Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line + EndChildFrame(); + EndGroup(); + } + + if (is_password) + PopFont(); + + // Log as text + if (g.LogEnabled && !is_password) + LogRenderedText(render_pos, buf_display, NULL); + + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) + return enter_pressed; + else + return value_changed; +} + +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); +} + +bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); +} + +// NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument) +bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + BeginGroup(); + PushID(label); + const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f; + if (step_ptr) + PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2)); + + char buf[64]; + DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf)); + + bool value_changed = false; + if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal)) + extra_flags |= ImGuiInputTextFlags_CharsDecimal; + extra_flags |= ImGuiInputTextFlags_AutoSelectAll; + if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view + value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format); + + // Step buttons + if (step_ptr) + { + PopItemWidth(); + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; + } + } + PopID(); + + if (label_size.x > 0) + { + SameLine(0, style.ItemInnerSpacing.x); + RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); + ItemSize(label_size, style.FramePadding.y); + } + EndGroup(); + + return value_changed; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char display_format[16]; + if (decimal_precision < 0) + strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1 + else + ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision); + return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags); +} + +bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags) +{ + // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. + const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; + return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags); +} + +bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + return InputFloatN(label, v, 2, decimal_precision, extra_flags); +} + +bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + return InputFloatN(label, v, 3, decimal_precision, extra_flags); +} + +bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + return InputFloatN(label, v, 4, decimal_precision, extra_flags); +} + +bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags) +{ + return InputIntN(label, v, 2, extra_flags); +} + +bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags) +{ + return InputIntN(label, v, 3, extra_flags); +} + +bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags) +{ + return InputIntN(label, v, 4, extra_flags); +} + +static bool Items_ArrayGetter(void* data, int idx, const char** out_text) +{ + const char* const* items = (const char* const*)data; + if (out_text) + *out_text = items[idx]; + return true; +} + +static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) +{ + // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. + const char* items_separated_by_zeros = (const char*)data; + int items_count = 0; + const char* p = items_separated_by_zeros; + while (*p) + { + if (idx == items_count) + break; + p += strlen(p) + 1; + items_count++; + } + if (!*p) + return false; + if (out_text) + *out_text = p; + return true; +} + +// Combo box helper allowing to pass an array of strings. +bool ImGui::Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items) +{ + const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); + return value_changed; +} + +// Combo box helper allowing to pass all items in a single string. +bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) +{ + int items_count = 0; + const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open + while (*p) + { + p += strlen(p) + 1; + items_count++; + } + bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); + return value_changed; +} + +// Combo box function. +bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w = CalcItemWidth(); + + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, &id)) + return false; + + const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f); + const bool hovered = IsHovered(frame_bb, id); + bool popup_open = IsPopupOpen(id); + bool popup_opened_now = false; + + const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING + RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); + + if (*current_item >= 0 && *current_item < items_count) + { + const char* item_text; + if (items_getter(data, *current_item, &item_text)) + RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL, ImVec2(0.0f,0.0f)); + } + + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + if (hovered) + { + SetHoveredID(id); + if (g.IO.MouseClicked[0]) + { + ClearActiveID(); + if (IsPopupOpen(id)) + { + ClosePopup(id); + } + else + { + FocusWindow(window); + OpenPopup(label); + popup_open = popup_opened_now = true; + } + } + } + + bool value_changed = false; + if (IsPopupOpen(id)) + { + // Size default to hold ~7 items + if (height_in_items < 0) + height_in_items = 7; + + float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); + float popup_y1 = frame_bb.Max.y; + float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y); + if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y)) + { + // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement) + popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y); + popup_y2 = frame_bb.Min.y; + } + ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2)); + SetNextWindowPos(popup_rect.Min); + SetNextWindowSize(popup_rect.GetSize()); + PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + + const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); + if (BeginPopupEx(label, flags)) + { + // Display items + Spacing(); + for (int i = 0; i < items_count; i++) + { + PushID((void*)(intptr_t)i); + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + if (Selectable(item_text, item_selected)) + { + ClearActiveID(); + value_changed = true; + *current_item = i; + } + if (item_selected && popup_opened_now) + SetScrollHere(); + PopID(); + } + EndPopup(); + } + PopStyleVar(); + } + return value_changed; +} + +// Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image. +// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID. +bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PopClipRect(); + + ImGuiID id = window->GetID(label); + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrentLineTextBaseOffset; + ImRect bb(pos, pos + size); + ItemSize(bb); + + // Fill horizontal space. + ImVec2 window_padding = window->WindowPadding; + float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; + float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); + ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); + ImRect bb_with_spacing(pos, pos + size_draw); + if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) + bb_with_spacing.Max.x += window_padding.x; + + // Selectables are tightly packed together, we extend the box to cover spacing between selectable. + float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); + float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); + float spacing_R = style.ItemSpacing.x - spacing_L; + float spacing_D = style.ItemSpacing.y - spacing_U; + bb_with_spacing.Min.x -= spacing_L; + bb_with_spacing.Min.y -= spacing_U; + bb_with_spacing.Max.x += spacing_R; + bb_with_spacing.Max.y += spacing_D; + if (!ItemAdd(bb_with_spacing, &id)) + { + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PushColumnClipRect(); + return false; + } + + ImGuiButtonFlags button_flags = 0; + if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick; + if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease; + if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; + if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; + bool hovered, held; + bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags); + if (flags & ImGuiSelectableFlags_Disabled) + selected = false; + + // Render + if (hovered || selected) + { + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f); + } + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + { + PushColumnClipRect(); + bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x); + } + + if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f)); + if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); + + // Automatically close popups + if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + CloseCurrentPopup(); + return pressed; +} + +bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) +{ + if (Selectable(label, *p_selected, flags, size_arg)) + { + *p_selected = !*p_selected; + return true; + } + return false; +} + +// Helper to calculate the size of a listbox and display a label on the right. +// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty" +bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + const ImGuiStyle& style = GetStyle(); + const ImGuiID id = GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + window->DC.LastItemRect = bb; + + BeginGroup(); + if (label_size.x > 0) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); + + BeginChildFrame(id, frame_bb.GetSize()); + return true; +} + +bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) +{ + // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. + // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. + // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. + if (height_in_items < 0) + height_in_items = ImMin(items_count, 7); + float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f); + + // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). + ImVec2 size; + size.x = 0.0f; + size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y; + return ListBoxHeader(label, size); +} + +void ImGui::ListBoxFooter() +{ + ImGuiWindow* parent_window = GetParentWindow(); + const ImRect bb = parent_window->DC.LastItemRect; + const ImGuiStyle& style = GetStyle(); + + EndChildFrame(); + + // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) + // We call SameLine() to restore DC.CurrentLine* data + SameLine(); + parent_window->DC.CursorPos = bb.Min; + ItemSize(bb, style.FramePadding.y); + EndGroup(); +} + +bool ImGui::ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_items) +{ + const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); + return value_changed; +} + +bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) +{ + if (!ListBoxHeader(label, items_count, height_in_items)) + return false; + + // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. + bool value_changed = false; + ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + { + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + + PushID(i); + if (Selectable(item_text, item_selected)) + { + *current_item = i; + value_changed = true; + } + PopID(); + } + ListBoxFooter(); + return value_changed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImVec2 pos = window->DC.CursorPos; + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); + float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + + bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f)); + if (shortcut_size.x > 0.0f) + { + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); + PopStyleColor(); + } + + if (selected) + RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled)); + + return pressed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) +{ + if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) + { + if (p_selected) + *p_selected = !*p_selected; + return true; + } + return false; +} + +bool ImGui::BeginMainMenuBar() +{ + ImGuiContext& g = *GImGui; + SetNextWindowPos(ImVec2(0.0f, 0.0f)); + SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f)); + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); + if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar) + || !BeginMenuBar()) + { + End(); + PopStyleVar(2); + return false; + } + g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x; + return true; +} + +void ImGui::EndMainMenuBar() +{ + EndMenuBar(); + End(); + PopStyleVar(2); +} + +bool ImGui::BeginMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + if (!(window->Flags & ImGuiWindowFlags_MenuBar)) + return false; + + IM_ASSERT(!window->DC.MenuBarAppending); + BeginGroup(); // Save position + PushID("##menubar"); + ImRect rect = window->MenuBarRect(); + PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false); + window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y); + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.MenuBarAppending = true; + AlignFirstTextHeightToWidgets(); + return true; +} + +void ImGui::EndMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + PopClipRect(); + PopID(); + window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x; + window->DC.GroupStack.back().AdvanceCursor = false; + EndGroup(); + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.MenuBarAppending = false; +} + +bool ImGui::BeginMenu(const char* label, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImGuiWindow* backed_focused_window = g.FocusedWindow; + + bool pressed; + bool menu_is_open = IsPopupOpen(id); + bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus")); + if (menuset_is_open) + g.FocusedWindow = window; + + // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos). + ImVec2 popup_pos, pos = window->DC.CursorPos; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) + { + popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight()); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + float w = label_size.x; + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + PopStyleVar(); + SameLine(); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + } + else + { + popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); + float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false); + if (!enabled) PopStyleColor(); + } + + bool hovered = enabled && IsHovered(window->DC.LastItemRect, id); + if (menuset_is_open) + g.FocusedWindow = backed_focused_window; + + bool want_open = false, want_close = false; + if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + { + // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. + bool moving_within_opened_triangle = false; + if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window) + { + if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window) + { + ImRect next_window_rect = next_window->Rect(); + ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; + ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. + ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? + tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); + moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc); + //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug + } + } + + want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); + want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); + } + else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close + { + want_close = true; + want_open = menu_is_open = false; + } + else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others + want_open = true; + if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' + want_close = true; + if (want_close && IsPopupOpen(id)) + ClosePopupToLevel(GImGui->CurrentPopupStack.Size); + + if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size) + { + // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. + OpenPopup(label); + return false; + } + + menu_is_open |= want_open; + if (want_open) + OpenPopup(label); + + if (menu_is_open) + { + SetNextWindowPos(popup_pos, ImGuiSetCond_Always); + ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu); + menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + } + + return menu_is_open; +} + +void ImGui::EndMenu() +{ + EndPopup(); +} + +// A little colored square. Return true when clicked. +// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID("#colorbutton"); + const float square_size = g.FontSize; + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); + ItemSize(bb, small_height ? 0.0f : style.FramePadding.y); + if (!ItemAdd(bb, &id)) + return false; + + bool hovered, held; + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding); + + if (hovered) + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.w)); + + return pressed; +} + +bool ImGui::ColorEdit3(const char* label, float col[3]) +{ + float col4[4]; + col4[0] = col[0]; + col4[1] = col[1]; + col4[2] = col[2]; + col4[3] = 1.0f; + const bool value_changed = ColorEdit4(label, col4, false); + col[0] = col4[0]; + col[1] = col4[1]; + col[2] = col4[2]; + return value_changed; +} + +// Edit colors components (each component in 0.0f..1.0f range +// Use CTRL-Click to input value and TAB to go to next item. +bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + const float w_full = CalcItemWidth(); + const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f); + + ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; + if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton) + edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; + + float f[4] = { col[0], col[1], col[2], col[3] }; + if (edit_mode == ImGuiColorEditMode_HSV) + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + + int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; + + int components = alpha ? 4 : 3; + bool value_changed = false; + + BeginGroup(); + PushID(label); + + const bool hsv = (edit_mode == 1); + switch (edit_mode) + { + case ImGuiColorEditMode_RGB: + case ImGuiColorEditMode_HSV: + { + // RGB/HSV 0..255 Sliders + const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); + const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + + const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x); + const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; + const char* fmt_table[3][4] = + { + { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, + { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, + { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } + }; + const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; + + PushItemWidth(w_item_one); + for (int n = 0; n < components; n++) + { + if (n > 0) + SameLine(0, style.ItemInnerSpacing.x); + if (n + 1 == components) + PushItemWidth(w_item_last); + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); + } + PopItemWidth(); + PopItemWidth(); + } + break; + case ImGuiColorEditMode_HEX: + { + // RGB Hexadecimal Input + const float w_slider_all = w_full - square_sz; + char buf[64]; + if (alpha) + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]); + else + ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]); + PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); + if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) + { + value_changed |= true; + char* p = buf; + while (*p == '#' || ImCharIsSpace(*p)) + p++; + i[0] = i[1] = i[2] = i[3] = 0; + if (alpha) + sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) + else + sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + } + PopItemWidth(); + } + break; + } + + SameLine(0, style.ItemInnerSpacing.x); + + const ImVec4 col_display(col[0], col[1], col[2], 1.0f); + if (ColorButton(col_display)) + g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! + + // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here + if (IsItemHovered()) + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3])); + + if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) + { + SameLine(0, style.ItemInnerSpacing.x); + const char* button_titles[3] = { "RGB", "HSV", "HEX" }; + if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups)) + g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! + } + + const char* label_display_end = FindRenderedTextEnd(label); + if (label != label_display_end) + { + SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x); + TextUnformatted(label, label_display_end); + } + + // Convert back + for (int n = 0; n < 4; n++) + f[n] = i[n] / 255.0f; + if (edit_mode == 1) + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + + if (value_changed) + { + col[0] = f[0]; + col[1] = f[1]; + col[2] = f[2]; + if (alpha) + col[3] = f[3]; + } + + PopID(); + EndGroup(); + + return value_changed; +} + +void ImGui::ColorEditMode(ImGuiColorEditMode mode) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ColorEditMode = mode; +} + +// Horizontal separating line. +void ImGui::Separator() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + if (window->DC.ColumnsCount > 1) + PopClipRect(); + + float x1 = window->Pos.x; + float x2 = window->Pos.x + window->Size.x; + if (!window->DC.GroupStack.empty()) + x1 += window->DC.IndentX; + + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); + ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. + if (!ItemAdd(bb, NULL)) + { + if (window->DC.ColumnsCount > 1) + PushColumnClipRect(); + return; + } + + window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Border)); + + ImGuiContext& g = *GImGui; + if (g.LogEnabled) + LogText(IM_NEWLINE "--------------------------------"); + + if (window->DC.ColumnsCount > 1) + { + PushColumnClipRect(); + window->DC.ColumnsCellMinY = window->DC.CursorPos.y; + } +} + +void ImGui::Spacing() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + ItemSize(ImVec2(0,0)); +} + +void ImGui::Dummy(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + ItemAdd(bb, NULL); +} + +bool ImGui::IsRectVisible(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); +} + +bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); +} + +// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) +void ImGui::BeginGroup() +{ + ImGuiWindow* window = GetCurrentWindow(); + + window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); + ImGuiGroupData& group_data = window->DC.GroupStack.back(); + group_data.BackupCursorPos = window->DC.CursorPos; + group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; + group_data.BackupIndentX = window->DC.IndentX; + group_data.BackupGroupOffsetX = window->DC.GroupOffsetX; + group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight; + group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; + group_data.BackupLogLinePosY = window->DC.LogLinePosY; + group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive; + group_data.AdvanceCursor = true; + + window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX; + window->DC.IndentX = window->DC.GroupOffsetX; + window->DC.CursorMaxPos = window->DC.CursorPos; + window->DC.CurrentLineHeight = 0.0f; + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; +} + +void ImGui::EndGroup() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls + + ImGuiGroupData& group_data = window->DC.GroupStack.back(); + + ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); + group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves. + group_bb.Max = ImMax(group_bb.Min, group_bb.Max); + + window->DC.CursorPos = group_data.BackupCursorPos; + window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); + window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight; + window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; + window->DC.IndentX = group_data.BackupIndentX; + window->DC.GroupOffsetX = group_data.BackupGroupOffsetX; + window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; + + if (group_data.AdvanceCursor) + { + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); + ItemAdd(group_bb, NULL); + } + + // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will function on the entire group. + // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context. + const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow); + if (active_id_within_group) + window->DC.LastItemId = g.ActiveId; + if (active_id_within_group && g.HoveredId == g.ActiveId) + window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true; + + window->DC.GroupStack.pop_back(); + + //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // Debug +} + +// Gets back to previous line and continue with horizontal layout +// pos_x == 0 : follow right after previous item +// pos_x != 0 : align to specified x position (relative to window/group left) +// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 +// spacing_w >= 0 : enforce spacing amount +void ImGui::SameLine(float pos_x, float spacing_w) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + if (pos_x != 0.0f) + { + if (spacing_w < 0.0f) spacing_w = 0.0f; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + else + { + if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; + window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; + } + window->DC.CurrentLineHeight = window->DC.PrevLineHeight; + window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; +} + +void ImGui::NewLine() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + ItemSize(ImVec2(0,0)); + else + ItemSize(ImVec2(0.0f, GImGui->FontSize)); +} + +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.ColumnsCount <= 1) + return; + + ImGuiContext& g = *GImGui; + PopItemWidth(); + PopClipRect(); + + window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); + if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) + { + // Columns 1+ cancel out IndentX + window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x; + window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent); + } + else + { + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; + window->DrawList->ChannelsSetCurrent(0); + } + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); + window->DC.CursorPos.y = window->DC.ColumnsCellMinY; + window->DC.CurrentLineHeight = 0.0f; + window->DC.CurrentLineTextBaseOffset = 0.0f; + + PushColumnClipRect(); + PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup +} + +int ImGui::GetColumnIndex() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.ColumnsCurrent; +} + +int ImGui::GetColumnsCount() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.ColumnsCount; +} + +static float GetDraggedColumnOffset(int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); + IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets. + IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x; + x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing); + + return (float)(int)x; +} + +float ImGui::GetColumnOffset(int column_index) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + if (g.ActiveId) + { + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + if (g.ActiveId == column_id) + return GetDraggedColumnOffset(column_index); + } + + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = window->DC.ColumnsData[column_index].OffsetNorm; + const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + return (float)(int)x_offset; +} + +void ImGui::SetColumnOffset(int column_index, float offset) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + window->DC.ColumnsData[column_index].OffsetNorm = t; + + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + window->DC.StateStorage->SetFloat(column_id, t); +} + +float ImGui::GetColumnWidth(int column_index) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); + return w; +} + +static void PushColumnClipRect(int column_index) +{ + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (column_index < 0) + column_index = window->DC.ColumnsCurrent; + + float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f); + float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f); + ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true); +} + +void ImGui::Columns(int columns_count, const char* id, bool border) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); + + if (window->DC.ColumnsCount != 1) + { + if (window->DC.ColumnsCurrent != 0) + ItemSize(ImVec2(0,0)); // Advance to column 0 + PopItemWidth(); + PopClipRect(); + window->DrawList->ChannelsMerge(); + + window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); + window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; + } + + // Draw columns borders and handle resize at the time of "closing" a columns set + if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems) + { + const float y1 = window->DC.ColumnsStartPosY; + const float y2 = window->DC.CursorPos.y; + for (int i = 1; i < window->DC.ColumnsCount; i++) + { + float x = window->Pos.x + GetColumnOffset(i); + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i); + const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2)); + if (IsClippedEx(column_rect, &column_id, false)) + continue; + + bool hovered, held; + ButtonBehavior(column_rect, column_id, &hovered, &held); + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeEW; + + // Draw before resize so our items positioning are in sync with the line being drawn + const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); + const float xi = (float)(int)x; + window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col); + + if (held) + { + if (g.ActiveIdIsJustActivated) + g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking) + x = GetDraggedColumnOffset(i); + SetColumnOffset(i, x); + } + } + } + + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (id ? 0 : columns_count)); + window->DC.ColumnsSetId = window->GetID(id ? id : "columns"); + PopID(); + + // Set state for first column + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsCount = columns_count; + window->DC.ColumnsShowBorders = border; + + const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x; + window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range + window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); + + if (window->DC.ColumnsCount != 1) + { + // Cache column offsets + window->DC.ColumnsData.resize(columns_count + 1); + for (int column_index = 0; column_index < columns_count + 1; column_index++) + { + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + KeepAliveID(column_id); + const float default_t = column_index / (float)window->DC.ColumnsCount; + const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store a union into the map?) + window->DC.ColumnsData[column_index].OffsetNorm = t; + } + window->DrawList->ChannelsSplit(window->DC.ColumnsCount); + PushColumnClipRect(); + PushItemWidth(GetColumnWidth() * 0.65f); + } + else + { + window->DC.ColumnsData.resize(0); + } +} + +void ImGui::Indent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; +} + +void ImGui::Unindent(float indent_w) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; +} + +void ImGui::TreePush(const char* str_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(str_id ? str_id : "#TreePush"); +} + +void ImGui::TreePush(const void* ptr_id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); +} + +void ImGui::TreePushRawID(ImGuiID id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + window->IDStack.push_back(id); +} + +void ImGui::TreePop() +{ + ImGuiWindow* window = GetCurrentWindow(); + Unindent(); + window->DC.TreeDepth--; + PopID(); +} + +void ImGui::Value(const char* prefix, bool b) +{ + Text("%s: %s", prefix, (b ? "true" : "false")); +} + +void ImGui::Value(const char* prefix, int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, unsigned int v) +{ + Text("%s: %d", prefix, v); +} + +void ImGui::Value(const char* prefix, float v, const char* float_format) +{ + if (float_format) + { + char fmt[64]; + ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); + Text(fmt, prefix, v); + } + else + { + Text("%s: %.3f", prefix, v); + } +} + +// FIXME: May want to remove those helpers? +void ImGui::ValueColor(const char* prefix, const ImVec4& v) +{ + Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); + SameLine(); + ColorButton(v, true); +} + +void ImGui::ValueColor(const char* prefix, ImU32 v) +{ + Text("%s: %08X", prefix, v); + SameLine(); + ColorButton(ColorConvertU32ToFloat4(v), true); +} + +//----------------------------------------------------------------------------- +// PLATFORM DEPENDENT HELPERS +//----------------------------------------------------------------------------- + +#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)) +#undef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#include +#endif + +// Win32 API clipboard implementation +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) + +#ifdef _MSC_VER +#pragma comment(lib, "user32") +#endif + +static const char* GetClipboardTextFn_DefaultImpl(void*) +{ + static ImVector buf_local; + buf_local.clear(); + if (!OpenClipboard(NULL)) + return NULL; + HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); + if (wbuf_handle == NULL) + return NULL; + if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) + { + int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; + buf_local.resize(buf_len); + ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); + } + GlobalUnlock(wbuf_handle); + CloseClipboard(); + return buf_local.Data; +} + +static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +{ + if (!OpenClipboard(NULL)) + return; + const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; + HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); + if (wbuf_handle == NULL) + return; + ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); + ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); + GlobalUnlock(wbuf_handle); + EmptyClipboard(); + SetClipboardData(CF_UNICODETEXT, wbuf_handle); + CloseClipboard(); +} + +#else + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static const char* GetClipboardTextFn_DefaultImpl(void*) +{ + return GImGui->PrivateClipboard; +} + +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static void SetClipboardTextFn_DefaultImpl(void*, const char* text) +{ + ImGuiContext& g = *GImGui; + if (g.PrivateClipboard) + { + ImGui::MemFree(g.PrivateClipboard); + g.PrivateClipboard = NULL; + } + const char* text_end = text + strlen(text); + g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); + memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); + g.PrivateClipboard[(int)(text_end - text)] = 0; +} + +#endif + +// Win32 API IME support (for Asian languages, etc.) +#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) + +#include +#ifdef _MSC_VER +#pragma comment(lib, "imm32") +#endif + +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) +{ + // Notify OS Input Method Editor of text input position + if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) + if (HIMC himc = ImmGetContext(hwnd)) + { + COMPOSITIONFORM cf; + cf.ptCurrentPos.x = x; + cf.ptCurrentPos.y = y; + cf.dwStyle = CFS_FORCE_POSITION; + ImmSetCompositionWindow(himc, &cf); + } +} + +#else + +static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} + +#endif + +//----------------------------------------------------------------------------- +// HELP +//----------------------------------------------------------------------------- + +void ImGui::ShowMetricsWindow(bool* p_open) +{ + if (ImGui::Begin("ImGui Metrics", p_open)) + { + ImGui::Text("ImGui %s", ImGui::GetVersion()); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3); + ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs); + static bool show_clip_rects = true; + ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects); + ImGui::Separator(); + + struct Funcs + { + static void NodeDrawList(ImDrawList* draw_list, const char* label) + { + bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); + if (draw_list == ImGui::GetWindowDrawList()) + { + ImGui::SameLine(); + ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + if (node_open) ImGui::TreePop(); + return; + } + if (!node_open) + return; + + ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list + overlay_draw_list->PushClipRectFullScreen(); + int elem_offset = 0; + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) + { + if (pcmd->UserCallback) + { + ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + if (show_clip_rects && ImGui::IsItemHovered()) + { + ImRect clip_rect = pcmd->ClipRect; + ImRect vtxs_rect; + for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) + vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); + clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); + vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); + } + if (!pcmd_node_open) + continue; + ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) + { + char buf[300], *buf_p = buf; + ImVec2 triangles_pos[3]; + for (int n = 0; n < 3; n++, vtx_i++) + { + ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; + triangles_pos[n] = v.pos; + buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + ImGui::Selectable(buf, false); + if (ImGui::IsItemHovered()) + overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle + } + ImGui::TreePop(); + } + overlay_draw_list->PopClipRect(); + ImGui::TreePop(); + } + + static void NodeWindows(ImVector& windows, const char* label) + { + if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) + return; + for (int i = 0; i < windows.Size; i++) + Funcs::NodeWindow(windows[i], "Window"); + ImGui::TreePop(); + } + + static void NodeWindow(ImGuiWindow* window, const char* label) + { + if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) + return; + NodeDrawList(window->DrawList, "DrawList"); + ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y); + ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); + ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y); + if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); + if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); + ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); + ImGui::TreePop(); + } + }; + + ImGuiContext& g = *GImGui; // Access private state + Funcs::NodeWindows(g.Windows, "Windows"); + if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size)) + { + for (int i = 0; i < g.RenderDrawLists[0].Size; i++) + Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size)) + { + for (int i = 0; i < g.OpenPopupStack.Size; i++) + { + ImGuiWindow* window = g.OpenPopupStack[i].Window; + ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); + } + ImGui::TreePop(); + } + if (ImGui::TreeNode("Basic state")) + { + ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL"); + ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame); + ImGui::TreePop(); + } + } + ImGui::End(); +} + +//----------------------------------------------------------------------------- + +// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. +// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. +#ifdef IMGUI_INCLUDE_IMGUI_USER_INL +#include "imgui_user.inl" +#endif + +//----------------------------------------------------------------------------- diff --git a/src/imgui/imgui.h b/src/imgui/imgui.h new file mode 100644 index 00000000..2b37c5be --- /dev/null +++ b/src/imgui/imgui.h @@ -0,0 +1,1412 @@ +// dear imgui, v1.51 WIP +// (headers) + +// See imgui.cpp file for documentation. +// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. +// Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase. +// Get latest version at https://github.com/ocornut/imgui + +#pragma once + +#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) +#include "imconfig.h" // User-editable configuration file +#endif +#include // FLT_MAX +#include // va_list +#include // ptrdiff_t, NULL +#include // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp + +#define IMGUI_VERSION "1.51 WIP" + +// Define attributes of all API symbols declarations, e.g. for DLL under Windows. +#ifndef IMGUI_API +#define IMGUI_API +#endif + +// Define assertion handler. +#ifndef IM_ASSERT +#include +#define IM_ASSERT(_EXPR) assert(_EXPR) +#endif + +// Some compilers support applying printf-style warnings to user functions. +#if defined(__clang__) || defined(__GNUC__) +#define IM_PRINTFARGS(FMT) __attribute__((format(printf, FMT, (FMT+1)))) +#else +#define IM_PRINTFARGS(FMT) +#endif + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + +// Forward declarations +struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) +struct ImDrawData; // All draw command lists required to render the frame +struct ImDrawList; // A single draw command list (generally one per window) +struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF font loader +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiOnceUponAFrame; // Simple helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro +struct ImGuiStorage; // Simple custom key value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextBuffer; // Text buffer for logging/accumulating text +struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use) +struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use) +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiContext; // ImGui context (opaque) + +// Typedefs and Enumerations (declared as int for compatibility and to not pollute the top of this file) +typedef unsigned int ImU32; // 32-bit unsigned integer (typically used to store packed colors) +typedef unsigned int ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) +typedef unsigned short ImWchar; // character for keyboard input/display +typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) +typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_ +typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_ +typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_ +typedef int ImGuiColorEditMode; // color edit mode for ColorEdit*() // enum ImGuiColorEditMode_ +typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_ +typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_ +typedef int ImGuiSetCond; // condition flags for Set*() // enum ImGuiSetCond_ +typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_ +typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_ +typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_ +typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); +typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data); +#ifdef _MSC_VER +typedef unsigned __int64 ImU64; // 64-bit unsigned integer +#else +typedef unsigned long long ImU64; // 64-bit unsigned integer +#endif + +// Others helpers at bottom of the file: +// class ImVector<> // Lightweight std::vector like class. +// IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) + +struct ImVec2 +{ + float x, y; + ImVec2() { x = y = 0.0f; } + ImVec2(float _x, float _y) { x = _x; y = _y; } +#ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2. + IM_VEC2_CLASS_EXTRA +#endif +}; + +struct ImVec4 +{ + float x, y, z, w; + ImVec4() { x = y = z = w = 0.0f; } + ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } +#ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec4. + IM_VEC4_CLASS_EXTRA +#endif +}; + +// ImGui end-user API +// In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types) +namespace ImGui +{ + // Main + IMGUI_API ImGuiIO& GetIO(); + IMGUI_API ImGuiStyle& GetStyle(); + IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() + IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render(). + IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set. + IMGUI_API void Shutdown(); + + // Demo/Debug/Info + IMGUI_API void ShowTestWindow(bool* p_open = NULL); // create demo/test window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display ImGui internals: browse window list, draw commands, individual vertices, basic internal state, etc. + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). + + // Window + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false). + IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually. + IMGUI_API void End(); // finish appending to current window, pop it off the window stack. + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " + IMGUI_API void EndChild(); + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API float GetContentRegionAvailWidth(); // + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates + IMGUI_API float GetWindowContentRegionWidth(); // + IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList api) + IMGUI_API ImVec2 GetWindowSize(); // get current window size + IMGUI_API float GetWindowWidth(); + IMGUI_API float GetWindowHeight(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows + + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position. call before Begin() + IMGUI_API void SetNextWindowPosCenter(ImGuiSetCond cond = 0); // set next window position to be centered on screen. call before Begin() + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (enforce the range of scrollbars). set axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. + + IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] + IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. + IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use negative 'offset' to access previous widgets. + IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it) + IMGUI_API ImGuiStorage* GetStateStorage(); + + // Parameters stacks (shared) + IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + IMGUI_API void PopFont(); + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied + + // Parameters stacks (current window) + IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) + IMGUI_API void PopItemWidth(); + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position + IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space + IMGUI_API void PopTextWrapPos(); + IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (uses io.KeyRepeatDelay/io.KeyRepeatRate for now). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); + + // Cursor / Layout + IMGUI_API void Separator(); // horizontal line + IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally + IMGUI_API void NewLine(); // undo a SameLine() + IMGUI_API void Spacing(); // add vertical spacing + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if >0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if >0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API void EndGroup(); + IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position + IMGUI_API float GetCursorPosX(); // " + IMGUI_API float GetCursorPosY(); // " + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // " + IMGUI_API void SetCursorPosX(float x); // " + IMGUI_API void SetCursorPosY(float y); // " + IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] + IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets + IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() + IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y + IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y + + // Columns + // You can also use SameLine(pos_x) for simplified columning. The columns API is still work-in-progress and rather lacking. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1). + IMGUI_API void NextColumn(); // next column + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset()) + IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns()) + + // ID scopes + // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them. + // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details. + IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the *entire* stack! + IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); + IMGUI_API void PushID(const void* ptr_id); + IMGUI_API void PushID(int int_id); + IMGUI_API void PopID(); + IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). useful if you want to query into ImGuiStorage yourself. otherwise rarely needed + IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(const void* ptr_id); + + // Widgets + IMGUI_API void Text(const char* fmt, ...) IM_PRINTFARGS(1); + IMGUI_API void TextV(const char* fmt, va_list args); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_PRINTFARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). + IMGUI_API void TextWrappedV(const char* fmt, va_list args); + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_PRINTFARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args); + IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + IMGUI_API void BulletText(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for Bullet()+Text() + IMGUI_API void BulletTextV(const char* fmt, va_list args); + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); + IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); + IMGUI_API bool Combo(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0 + IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true); + IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x + IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // " + IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and will be obsoleted/replaced. + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); + + // Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds) + // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", const char* display_format_max = NULL, float power = 1.0f); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f", const char* display_format_max = NULL); + + // Widgets: Input with Keyboard + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); + + // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds) + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format = "%.0f"); + + // Widgets: Trees + IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop(). + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_PRINTFARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose + IMGUI_API void TreePush(const void* ptr_id = NULL); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond = 0); // set next TreeNode/CollapsingHeader open state. + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header + + // Widgets: Selectable / Lists + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); + IMGUI_API bool ListBox(const char* label, int* current_item, const char* const* items, int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards. + IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " + IMGUI_API void ListBoxFooter(); // terminate the scrolling region + + // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + IMGUI_API void ValueColor(const char* prefix, const ImVec4& v); + IMGUI_API void ValueColor(const char* prefix, ImU32 v); + + // Tooltips + IMGUI_API void SetTooltip(const char* fmt, ...) IM_PRINTFARGS(1); // set text tooltip under mouse-cursor, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip(). + IMGUI_API void SetTooltipV(const char* fmt, va_list args); + IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of contents). + IMGUI_API void EndTooltip(); + + // Menus + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true! + IMGUI_API void EndMainMenuBar(); + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set). only call EndMenuBar() if this returns true! + IMGUI_API void EndMenuBar(); + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Popups + IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). + IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true! + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (block interactions behind the modal window, can't close the modal window by clicking outside) + IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window). + IMGUI_API void EndPopup(); + IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. + + // Logging: all text output from interface is redirected to tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty + IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard + IMGUI_API void LogFinish(); // stop logging (close file, etc.) + IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard + IMGUI_API void LogText(const char* fmt, ...) IM_PRINTFARGS(1); // pass text data straight to log (without being displayed) + + // Clipping + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + + // Utilities + IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse? + IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this + IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false) + IMGUI_API bool IsItemClicked(int mouse_button = 0); // was the last item clicked? (e.g. button/node just clicked on) + IMGUI_API bool IsItemVisible(); // was the last item visible? (aka not out of sight due to clipping/scrolling.) + IMGUI_API bool IsAnyItemHovered(); + IMGUI_API bool IsAnyItemActive(); + IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space + IMGUI_API ImVec2 GetItemRectMax(); // " + IMGUI_API ImVec2 GetItemRectSize(); // " + IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. + IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others) + IMGUI_API bool IsWindowFocused(); // is current window focused + IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self) + IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused + IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup) + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. + IMGUI_API float GetTime(); + IMGUI_API int GetFrameCount(); + IMGUI_API const char* GetStyleColName(ImGuiCol idx); + IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can. + + IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame + IMGUI_API void EndChildFrame(); + + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); + IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); + IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); + IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); + + // Inputs + IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] + IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your backend/engine stored them into KeyDown[]! + IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down).. + IMGUI_API bool IsMouseDown(int button); // is mouse button held + IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) + IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. + IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) + IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window). disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup) + IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any visible window + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup. + IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into + IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API void ResetMouseDragDelta(int button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type + IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered. + IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle). + + // Helpers functions to access functions pointers in ImGui::GetIO() + IMGUI_API void* MemAlloc(size_t sz); + IMGUI_API void MemFree(void* ptr); + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); + + // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default. + // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context. + IMGUI_API const char* GetVersion(); + IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx); + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); + + // Obsolete functions (Will be removed! Also see 'API BREAKING CHANGES' section in imgui.cpp) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // OBSOLETE 1.51+. This was partly broken. You probably wanted to use ImGui::GetIO().WantCaptureMouse instead. + static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+ + static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+ + static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+ + static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+ + static inline bool GetWindowCollapsed() { return ImGui::IsWindowCollapsed(); } // OBSOLETE 1.39+ + static inline bool IsRectClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.39+ +#endif + +} // namespace ImGui + +// Flags for ImGui::Begin() +enum ImGuiWindowFlags_ +{ + // Default: 0 + ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar + ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip + ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame + ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items + ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) + // [Internal] + ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 22, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox() + ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu() +}; + +// Flags for ImGui::InputText() +enum ImGuiInputTextFlags_ +{ + // Default: 0 + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z + ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs + ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) + ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. + ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally + ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode + ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' + // [Internal] + ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + // Default: 0 + ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too +}; + +// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array +enum ImGuiKey_ +{ + ImGuiKey_Tab, // for tabbing through fields + ImGuiKey_LeftArrow, // for text edit + ImGuiKey_RightArrow,// for text edit + ImGuiKey_UpArrow, // for text edit + ImGuiKey_DownArrow, // for text edit + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, // for text edit + ImGuiKey_End, // for text edit + ImGuiKey_Delete, // for text edit + ImGuiKey_Backspace, // for text edit + ImGuiKey_Enter, // for text edit + ImGuiKey_Escape, // for text edit + ImGuiKey_A, // for text edit CTRL+A: select all + ImGuiKey_C, // for text edit CTRL+C: copy + ImGuiKey_V, // for text edit CTRL+V: paste + ImGuiKey_X, // for text edit CTRL+X: cut + ImGuiKey_Y, // for text edit CTRL+Y: redo + ImGuiKey_Z, // for text edit CTRL+Z: undo + ImGuiKey_COUNT +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildWindowBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_TitleBgActive, + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_ComboBg, + ImGuiCol_CheckMark, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Column, + ImGuiCol_ColumnHovered, + ImGuiCol_ColumnActive, + ImGuiCol_ResizeGrip, + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_CloseButton, + ImGuiCol_CloseButtonHovered, + ImGuiCol_CloseButtonActive, + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TextSelectedBg, + ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active + ImGuiCol_COUNT +}; + +// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +// NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/poped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly. +// NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. +enum ImGuiStyleVar_ +{ + // Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + ImGuiStyleVar_Alpha, // float Alpha + ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding + ImGuiStyleVar_WindowRounding, // float WindowRounding + ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize + ImGuiStyleVar_ChildWindowRounding, // float ChildWindowRounding + ImGuiStyleVar_FramePadding, // ImVec2 FramePadding + ImGuiStyleVar_FrameRounding, // float FrameRounding + ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing + ImGuiStyleVar_IndentSpacing, // float IndentSpacing + ImGuiStyleVar_GrabMinSize, // float GrabMinSize + ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign + ImGuiStyleVar_Count_ +}; + +// Enumeration for ColorEditMode() +// FIXME-OBSOLETE: Will be replaced by future color/picker api +enum ImGuiColorEditMode_ +{ + ImGuiColorEditMode_UserSelect = -2, + ImGuiColorEditMode_UserSelectShowButton = -1, + ImGuiColorEditMode_RGB = 0, + ImGuiColorEditMode_HSV = 1, + ImGuiColorEditMode_HEX = 2 +}; + +// Enumeration for GetMouseCursor() +enum ImGuiMouseCursor_ +{ + ImGuiMouseCursor_None = -1, + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. + ImGuiMouseCursor_Move, // Unused + ImGuiMouseCursor_ResizeNS, // Unused + ImGuiMouseCursor_ResizeEW, // When hovering over a column + ImGuiMouseCursor_ResizeNESW, // Unused + ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window + ImGuiMouseCursor_Count_ +}; + +// Condition flags for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions +// All those functions treat 0 as a shortcut to ImGuiSetCond_Always +enum ImGuiSetCond_ +{ + ImGuiSetCond_Always = 1 << 0, // Set the variable + ImGuiSetCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) + ImGuiSetCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file) + ImGuiSetCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time) +}; + +struct ImGuiStyle +{ + float Alpha; // Global alpha applies to everything in ImGui + ImVec2 WindowPadding; // Padding within a window + ImVec2 WindowMinSize; // Minimum window size + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) + float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar + float ScrollbarRounding; // Radius of grab corners for scrollbar + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. + ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. + ImVec2 DisplaySafeAreaPadding; // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. + bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + ImVec4 Colors[ImGuiCol_COUNT]; + + IMGUI_API ImGuiStyle(); +}; + +// This is where your app communicate with ImGui. Access via ImGui::GetIO(). +// Read 'Programmer guide' section in .cpp file for general usage. +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Settings (fill once) // Default value: + //------------------------------------------------------------------ + + ImVec2 DisplaySize; // // Display size, in pixels. For clamping windows positions. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. + float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds. + const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving. + const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified). + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging + int KeyMap[ImGuiKey_COUNT]; // // Map of indices into the KeysDown[512] entries array + float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds. + void* UserData; // = NULL // Store your own data for retrieval by callbacks. + + ImFontAtlas* Fonts; // // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. + float FontGlobalScale; // = 1.0f // Global scale all fonts + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. + ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. + ImVec2 DisplayVisibleMin; // (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. + ImVec2 DisplayVisibleMax; // (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize + + // Advanced/subtle behaviors + bool OSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl + + //------------------------------------------------------------------ + // User Functions + //------------------------------------------------------------------ + + // Rendering function, will be called in Render(). + // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer. + // See example applications if you are unsure of how to implement this. + void (*RenderDrawListsFn)(ImDrawData* data); + + // Optional: access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*GetClipboardTextFn)(void* user_data); + void (*SetClipboardTextFn)(void* user_data, const char* text); + void* ClipboardUserData; + + // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer. + // (default to posix malloc/free) + void* (*MemAllocFn)(size_t sz); + void (*MemFreeFn)(void* ptr); + + // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows) + // (default to use native imm32 api on Windows) + void (*ImeSetInputScreenPosFn)(int x, int y); + void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning. + + //------------------------------------------------------------------ + // Input - Fill before calling NewFrame() + //------------------------------------------------------------------ + + ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) + bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. + bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). + bool KeyCtrl; // Keyboard modifier pressed: Control + bool KeyShift; // Keyboard modifier pressed: Shift + bool KeyAlt; // Keyboard modifier pressed: Alt + bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows + bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) + ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. + + // Functions + IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[] + IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string + inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually + + //------------------------------------------------------------------ + // Output - Retrieve after calling NewFrame() + //------------------------------------------------------------------ + + bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input). Use to hide mouse from the rest of your application + bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input). Use to hide keyboard from the rest of your application + bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. Use to activate on screen keyboard if your system needs one + float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames + int MetricsAllocs; // Number of active memory allocations + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 + int MetricsActiveWindows; // Number of visible root windows (exclude child windows) + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative, so a disappearing/reappearing mouse won't have a huge delta for one frame. + + //------------------------------------------------------------------ + // [Private] ImGui will maintain those fields. Forward compatibility not guaranteed! + //------------------------------------------------------------------ + + ImVec2 MousePosPrev; // Previous mouse position temporary storage (nb: not for public use, set to MousePos in NewFrame()) + bool MouseClicked[5]; // Mouse button went from !Down to Down + ImVec2 MouseClickedPos[5]; // Position at time of clicking + float MouseClickedTime[5]; // Time of last click (used to figure out double-click) + bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? + bool MouseReleased[5]; // Mouse button went from Down to !Down + bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click point + float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed) + float KeysDownDurationPrev[512]; // Previous duration the key has been down + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +// Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). +// Our implementation does NOT call c++ constructors because we don't use them in ImGui. Don't use this class as a straight std::vector replacement in your code! +template +class ImVector +{ +public: + int Size; + int Capacity; + T* Data; + + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + ImVector() { Size = Capacity = 0; Data = NULL; } + ~ImVector() { if (Data) ImGui::MemFree(Data); } + + inline bool empty() const { return Size == 0; } + inline int size() const { return Size; } + inline int capacity() const { return Capacity; } + + inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } + inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } + + inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } + inline iterator begin() { return Data; } + inline const_iterator begin() const { return Data; } + inline iterator end() { return Data + Size; } + inline const_iterator end() const { return Data + Size; } + inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; } + inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } + inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; } + inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; } + inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline int _grow_capacity(int new_size) { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > new_size ? new_capacity : new_size; } + + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void reserve(int new_capacity) + { + if (new_capacity <= Capacity) return; + T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type)); + if (Data) + memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); + ImGui::MemFree(Data); + Data = new_data; + Capacity = new_capacity; + } + + inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + + inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } + inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } +}; + +// Helper: execute a block of code at maximum once a frame +// Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. +// Usage: +// IMGUI_ONCE_UPON_A_FRAME +// { +// // code block will be executed one per frame +// } +// Attention! the macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. +#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf##__LINE__; if (imgui_oaf##__LINE__) +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + struct TextRange + { + const char* b; + const char* e; + + TextRange() { b = e = NULL; } + TextRange(const char* _b, const char* _e) { b = _b; e = _e; } + const char* begin() const { return b; } + const char* end() const { return e; } + bool empty() const { return b == e; } + char front() const { return *b; } + static bool is_blank(char c) { return c == ' ' || c == '\t'; } + void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; } + IMGUI_API void split(char separator, ImVector& out); + }; + + char InputBuf[256]; + ImVector Filters; + int CountGrep; + + ImGuiTextFilter(const char* default_filter = ""); + ~ImGuiTextFilter() {} + void Clear() { InputBuf[0] = 0; Build(); } + bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + bool PassFilter(const char* text, const char* text_end = NULL) const; + bool IsActive() const { return !Filters.empty(); } + IMGUI_API void Build(); +}; + +// Helper: Text buffer for logging/accumulating text +struct ImGuiTextBuffer +{ + ImVector Buf; + + ImGuiTextBuffer() { Buf.push_back(0); } + inline char operator[](int i) { return Buf.Data[i]; } + const char* begin() const { return &Buf.front(); } + const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator + int size() const { return Buf.Size - 1; } + bool empty() { return Buf.Size <= 1; } + void clear() { Buf.clear(); Buf.push_back(0); } + const char* c_str() const { return Buf.Data; } + IMGUI_API void append(const char* fmt, ...) IM_PRINTFARGS(2); + IMGUI_API void appendv(const char* fmt, va_list args); +}; + +// Helper: Simple Key->value storage +// Typically you don't have to worry about this since a storage is held within each Window. +// We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options. +// This is optimized for efficient reading (dichotomy into a contiguous buffer), rare writing (typically tied to user interactions) +// You can use it as custom user storage for temporary values. Declare your own storage if, for example: +// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). +// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. +struct ImGuiStorage +{ + struct Pair + { + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + }; + ImVector Data; + + // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) + // - Set***() functions find pair, insertion on demand if missing. + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + IMGUI_API void Clear(); + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. + // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) + // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + + // Use on your own storage if you know only integer are being stored (open/close all tree nodes) + IMGUI_API void SetAllInt(int val); +}; + +// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered. +struct ImGuiTextEditCallbackData +{ + ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + void* UserData; // What user passed to InputText() // Read-only + bool ReadOnly; // Read-only mode // Read-only + + // CharFilter event: + ImWchar EventChar; // Character input // Read-write (replace character or set to zero) + + // Completion,History,Always events: + // If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true. + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only + char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer) + int BufTextLen; // Current text length in bytes // Read-write + int BufSize; // Maximum text length in bytes // Read-only + bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write + int CursorPos; // // Read-write + int SelectionStart; // // Read-write (== to SelectionEnd when no selection) + int SelectionEnd; // // Read-write + + // NB: Helper functions for text manipulation. Calling those function loses selection. + IMGUI_API void DeleteChars(int pos, int bytes_count); + IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); + bool HasSelection() const { return SelectionStart != SelectionEnd; } +}; + +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeConstraintCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// Helpers macros to generate 32-bits encoded colors +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#define IM_COL32_A_MASK 0xFF000000 +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } + ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } + ImColor(const ImVec4& col) { Value = col; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } + + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } +}; + +// Helper: Manually clip large list of items. +// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. +// Usage: +// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). +// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. +// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) +// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. +struct ImGuiListClipper +{ + float StartPosY; + float ItemsHeight; + int ItemsCount, StepNo, DisplayStart, DisplayEnd; + + // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetItemsLineHeightWithSpacing(). + // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). + ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). + ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. + + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. +}; + +//----------------------------------------------------------------------------- +// Draw List +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. +//----------------------------------------------------------------------------- + +// Draw callbacks for advanced uses. +// NB- You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) +// Draw callback may be useful for example, A) Change your GPU render state, B) render a complex 3D scene inside a UI element (without an intermediate texture/render target), etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) cmd.UserCallback(parent_list, cmd); else RenderTriangles()' +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); + +// Typically, 1 command = 1 gpu draw call (unless command is a callback) +struct ImDrawCmd +{ + unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2) + ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // The draw callback code can access this. + + ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = -8192.0f; ClipRect.z = ClipRect.w = +8192.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; } +}; + +// Vertex index (override with '#define ImDrawIdx unsigned int' inside in imconfig.h) +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; +#endif + +// Vertex layout +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef) +// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. +// You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. +struct ImDrawChannel +{ + ImVector CmdBuffer; + ImVector IdxBuffer; +}; + +// Draw command list +// This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future. +// If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), however you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well) +// Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions). +struct ImDrawList +{ + // This is what you have to render + ImVector CmdBuffer; // Commands. Typically 1 command = 1 GPU draw call. + ImVector IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector VtxBuffer; // Vertex buffer. + + // [Internal, used while building lists] + const char* _OwnerName; // Pointer to owner window's name for debugging + unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector _ClipRectStack; // [Internal] + ImVector _TextureIdStack; // [Internal] + ImVector _Path; // [Internal] current path building + int _ChannelsCurrent; // [Internal] current channel number (0) + int _ChannelsCount; // [Internal] number of active channels (1+) + ImVector _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) + + ImDrawList() { _OwnerName = NULL; Clear(); } + ~ImDrawList() { ClearFreeMemory(); } + IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) + IMGUI_API void PushClipRectFullScreen(); + IMGUI_API void PopClipRect(); + IMGUI_API void PushTextureID(const ImTextureID& texture_id); + IMGUI_API void PopTextureID(); + + // Primitives + IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ~0); // a: upper-left, b: lower-right + IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased); + IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); + + // Stateful path API, add points then finish with PathFill() or PathStroke() + inline void PathClear() { _Path.resize(0); } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); } + inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); PathClear(); } + IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); + IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ~0); // rounding_corners_flags: 4-bits corresponding to which corner to round + + // Channels + // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) + IMGUI_API void ChannelsSplit(int channels_count); + IMGUI_API void ChannelsMerge(); + IMGUI_API void ChannelsSetCurrent(int channel_index); + + // Advanced + IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. + IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible + + // Internal helpers + // NB: all primitives needs to be reserved via PrimReserve() beforehand! + IMGUI_API void Clear(); + IMGUI_API void ClearFreeMemory(); + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) + IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } + IMGUI_API void UpdateClipRect(); + IMGUI_API void UpdateTextureID(); +}; + +// All draw data to render an ImGui frame +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + ImDrawList** CmdLists; + int CmdListsCount; + int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size + int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size + + // Functions + ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } + IMGUI_API void DeIndexAllBuffers(); // For backward compatibility or convenience: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +struct ImFontConfig +{ + void* FontData; // // TTF data + int FontDataSize; // // TTF data size + bool FontDataOwnedByAtlas; // true // TTF data ownership taken by the container ImFontAtlas (will delete memory itself). Set to true + int FontNo; // 0 // Index of font within TTF file + float SizePixels; // // Size in pixels for rasterizer + int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. + bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. + ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input + const ImWchar* GlyphRanges; // // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. + + // [Internal] + char Name[32]; // Name (strictly to ease debugging) + ImFont* DstFont; + + IMGUI_API ImFontConfig(); +}; + +// Load and rasterize multiple TTF fonts into a same texture. +// Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering. +// We also add custom graphic data into the texture that serves for ImGui. +// 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you. +// 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. +// 3. Upload the pixels data into a texture within your graphics system. +// 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture. +// IMPORTANT: If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the ImFont is build (when calling GetTextData*** or Build()). We only copy the pointer, not the data. +struct ImFontAtlas +{ + IMGUI_API ImFontAtlas(); + IMGUI_API ~ImFontAtlas(); + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build() + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data' still owned by caller. Compress with binary_to_compressed_c.cpp + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 paramaeter + IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges) + IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates) + IMGUI_API void Clear(); // Clear all + + // Retrieve texture data + // User is in charge of copying the pixels into graphics memory, then call SetTextureUserID() + // After loading the texture into your graphic system, store your texture handle in 'TexID' (ignore if you aren't using multiple fonts nor images) + // RGBA32 format is provided for convenience and high compatibility, but note that all RGB pixels are white, so 75% of the memory is wasted. + // Pitch = Width * BytesPerPixels + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + void SetTexID(ImTextureID id) { TexID = id; } + + // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create a UTF-8 string literally using the u8"Hello world" syntax. See FAQ for details. + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + + // Members + // (Access texture data via GetTexData*() calls which will setup a default font for you.) + ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. + unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight + unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + int TexWidth; // Texture width calculated during Build(). + int TexHeight; // Texture height calculated during Build(). + int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. + + // Private + ImVector ConfigData; // Internal data + IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions. + IMGUI_API void RenderCustomTexData(int pass, void* rects); +}; + +// Font runtime data and rendering +// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). +struct ImFont +{ + struct Glyph + { + ImWchar Codepoint; + float XAdvance; + float X0, Y0, X1, Y1; + float U0, V0, U1, V1; // Texture coordinates + }; + + // Members: Hot ~62/78 bytes + float FontSize; // // Height of characters, set during loading (don't change after loading) + float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() + ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels + ImVector Glyphs; // // All glyphs. + ImVector IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). + ImVector IndexLookup; // // Sparse. Index glyphs by Unicode code-point. + const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) + float FallbackXAdvance; // == FallbackGlyph->XAdvance + ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() + + // Members: Cold ~18/26 bytes + short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData + ImFontAtlas* ContainerAtlas; // // What we has been loaded into + float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) + + // Methods + IMGUI_API ImFont(); + IMGUI_API ~ImFont(); + IMGUI_API void Clear(); + IMGUI_API void BuildLookupTable(); + IMGUI_API const Glyph* FindGlyph(ImWchar c) const; + IMGUI_API void SetFallbackChar(ImWchar c); + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; } + bool IsLoaded() const { return ContainerAtlas != NULL; } + + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 + IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // Private + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. +}; + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#include "imgui_user.h" +#endif diff --git a/src/imgui/imgui_demo.cpp b/src/imgui/imgui_demo.cpp new file mode 100644 index 00000000..f2d03396 --- /dev/null +++ b/src/imgui/imgui_demo.cpp @@ -0,0 +1,2648 @@ +// dear imgui, v1.51 WIP +// (demo code) + +// Message to the person tempted to delete this file when integrating ImGui into their code base: +// Don't do it! Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to. +// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow(). +// During development, you can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui. Have it wired in a debug menu! +// Removing this file from your project is hindering access to documentation for everyone in your team, likely leading you to poorer usage of the library. + +// Note that you can #define IMGUI_DISABLE_TEST_WINDOWS in imconfig.h for the same effect. +// If you want to link core ImGui in your public builds but not those test windows, #define IMGUI_DISABLE_TEST_WINDOWS in imconfig.h and those functions will be empty. +// For any other case, if you have ImGui available you probably want this to be available for reference and execution. + +// Thank you, +// -Your beloved friend, imgui_demo.cpp (that you won't delete) + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#include // toupper, isprint +#include // sqrtf, powf, cosf, sinf, floorf, ceilf +#include // vsnprintf, sscanf, printf +#include // NULL, malloc, free, atoi +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include // intptr_t +#else +#include // intptr_t +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' +#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#if __has_warning("-Wreserved-id-macro") +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#if (__GNUC__ >= 6) +#pragma GCC diagnostic ignored "-Wmisleading-indentation" // warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on github. +#endif +#endif + +// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" +#else +#define IM_NEWLINE "\n" +#endif + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) + +//----------------------------------------------------------------------------- +// DEMO CODE +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_TEST_WINDOWS + +static void ShowExampleAppConsole(bool* p_open); +static void ShowExampleAppLog(bool* p_open); +static void ShowExampleAppLayout(bool* p_open); +static void ShowExampleAppPropertyEditor(bool* p_open); +static void ShowExampleAppLongText(bool* p_open); +static void ShowExampleAppAutoResize(bool* p_open); +static void ShowExampleAppConstrainedResize(bool* p_open); +static void ShowExampleAppFixedOverlay(bool* p_open); +static void ShowExampleAppManipulatingWindowTitle(bool* p_open); +static void ShowExampleAppCustomRendering(bool* p_open); +static void ShowExampleAppMainMenuBar(); +static void ShowExampleMenuFile(); + +static void ShowHelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(450.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +void ImGui::ShowUserGuide() +{ + ImGui::BulletText("Double-click on title bar to collapse window."); + ImGui::BulletText("Click and drag on lower right corner to resize window."); + ImGui::BulletText("Click and drag on any empty space to move window."); + ImGui::BulletText("Mouse Wheel to scroll."); + if (ImGui::GetIO().FontAllowUserScaling) + ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); + ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + ImGui::BulletText("CTRL+Click on a slider or drag box to input text."); + ImGui::BulletText( + "While editing text:\n" + "- Hold SHIFT or use mouse to select text\n" + "- CTRL+Left/Right to word jump\n" + "- CTRL+A or double-click to select all\n" + "- CTRL+X,CTRL+C,CTRL+V clipboard\n" + "- CTRL+Z,CTRL+Y undo/redo\n" + "- ESCAPE to revert\n" + "- You can apply arithmetic operators +,*,/ on numerical values.\n" + " Use +- to subtract.\n"); +} + +// Demonstrate most ImGui features (big function!) +void ImGui::ShowTestWindow(bool* p_open) +{ + // Examples apps + static bool show_app_main_menu_bar = false; + static bool show_app_console = false; + static bool show_app_log = false; + static bool show_app_layout = false; + static bool show_app_property_editor = false; + static bool show_app_long_text = false; + static bool show_app_auto_resize = false; + static bool show_app_constrained_resize = false; + static bool show_app_fixed_overlay = false; + static bool show_app_manipulating_window_title = false; + static bool show_app_custom_rendering = false; + static bool show_app_style_editor = false; + + static bool show_app_metrics = false; + static bool show_app_about = false; + + if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); + if (show_app_console) ShowExampleAppConsole(&show_app_console); + if (show_app_log) ShowExampleAppLog(&show_app_log); + if (show_app_layout) ShowExampleAppLayout(&show_app_layout); + if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor); + if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text); + if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize); + if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize); + if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay); + if (show_app_manipulating_window_title) ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title); + if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); + + if (show_app_metrics) ImGui::ShowMetricsWindow(&show_app_metrics); + if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); } + if (show_app_about) + { + ImGui::Begin("About ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Text("dear imgui, %s", ImGui::GetVersion()); + ImGui::Separator(); + ImGui::Text("By Omar Cornut and all github contributors."); + ImGui::Text("ImGui is licensed under the MIT License, see LICENSE for more information."); + ImGui::End(); + } + + static bool no_titlebar = false; + static bool no_border = true; + static bool no_resize = false; + static bool no_move = false; + static bool no_scrollbar = false; + static bool no_collapse = false; + static bool no_menu = false; + + // Demonstrate the various window flags. Typically you would just use the default. + ImGuiWindowFlags window_flags = 0; + if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; + if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders; + if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; + if (no_move) window_flags |= ImGuiWindowFlags_NoMove; + if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; + if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; + if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar; + ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("ImGui Demo", p_open, window_flags)) + { + // Early out if the window is collapsed, as an optimization. + ImGui::End(); + return; + } + + //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels + ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels + + ImGui::Text("Dear ImGui says hello."); + + // Menu + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Examples")) + { + ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar); + ImGui::MenuItem("Console", NULL, &show_app_console); + ImGui::MenuItem("Log", NULL, &show_app_log); + ImGui::MenuItem("Simple layout", NULL, &show_app_layout); + ImGui::MenuItem("Property editor", NULL, &show_app_property_editor); + ImGui::MenuItem("Long text display", NULL, &show_app_long_text); + ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize); + ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize); + ImGui::MenuItem("Simple overlay", NULL, &show_app_fixed_overlay); + ImGui::MenuItem("Manipulating window title", NULL, &show_app_manipulating_window_title); + ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Help")) + { + ImGui::MenuItem("Metrics", NULL, &show_app_metrics); + ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor); + ImGui::MenuItem("About ImGui", NULL, &show_app_about); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + ImGui::Spacing(); + if (ImGui::CollapsingHeader("Help")) + { + ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); + ImGui::ShowUserGuide(); + } + + if (ImGui::CollapsingHeader("Window options")) + { + ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150); + ImGui::Checkbox("No border", &no_border); ImGui::SameLine(300); + ImGui::Checkbox("No resize", &no_resize); + ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150); + ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300); + ImGui::Checkbox("No collapse", &no_collapse); + ImGui::Checkbox("No menu", &no_menu); + + if (ImGui::TreeNode("Style")) + { + ImGui::ShowStyleEditor(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Logging")) + { + ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded. You can also call ImGui::LogText() to output directly to the log without a visual output."); + ImGui::LogButtons(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Widgets")) + { + if (ImGui::TreeNode("Trees")) + { + if (ImGui::TreeNode("Basic trees")) + { + for (int i = 0; i < 5; i++) + if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("print")) printf("Child %d pressed", i); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Advanced, with Selectable nodes")) + { + ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); + static bool align_label_with_current_x_position = false; + ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position); + ImGui::Text("Hello!"); + if (align_label_with_current_x_position) + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + + static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. + int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc. + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents. + for (int i = 0; i < 6; i++) + { + // Disable the default open on single-click behavior and pass in Selected flag according to our selection state. + ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0); + if (i < 3) + { + // Node + bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + if (node_open) + { + ImGui::Text("Blah blah\nBlah Blah"); + ImGui::TreePop(); + } + } + else + { + // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text(). + ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + } + } + if (node_clicked != -1) + { + // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. + if (ImGui::GetIO().KeyCtrl) + selection_mask ^= (1 << node_clicked); // CTRL+click to toggle + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection + selection_mask = (1 << node_clicked); // Click to single-select + } + ImGui::PopStyleVar(); + if (align_label_with_current_x_position) + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Collapsing Headers")) + { + static bool closable_group = true; + if (ImGui::CollapsingHeader("Header")) + { + ImGui::Checkbox("Enable extra group", &closable_group); + for (int i = 0; i < 5; i++) + ImGui::Text("Some content %d", i); + } + if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) + { + for (int i = 0; i < 5; i++) + ImGui::Text("More content %d", i); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); + ImGui::Bullet(); ImGui::SmallButton("Button"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colored Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); + ImGui::TextDisabled("Disabled"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImGui::Text("Test paragraph 1:"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("The lazy dog is a good dog. This paragraph is made to fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); + ImGui::PopTextWrapPos(); + + ImGui::Text("Test paragraph 2:"); + pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); + ImGui::PopTextWrapPos(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test with Japanese characters + // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) + // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') + // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. + // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system! + // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges."); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Images")) + { + ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); + ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos(); + float tex_w = (float)ImGui::GetIO().Fonts->TexWidth; + float tex_h = (float)ImGui::GetIO().Fonts->TexHeight; + ImTextureID tex_id = ImGui::GetIO().Fonts->TexID; + ImGui::Text("%.0fx%.0f", tex_w, tex_h); + ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + float focus_sz = 32.0f; + float focus_x = ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > tex_w - focus_sz) focus_x = tex_w - focus_sz; + float focus_y = ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > tex_h - focus_sz) focus_y = tex_h - focus_sz; + ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y); + ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz); + ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h); + ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h); + ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::EndTooltip(); + } + ImGui::TextWrapped("And now some textured buttons.."); + static int pressed_count = 0; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); + int frame_padding = -1 + i; // -1 = uses default padding + if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding, ImColor(0,0,0,255))) + pressed_count += 1; + ImGui::PopID(); + ImGui::SameLine(); + } + ImGui::NewLine(); + ImGui::Text("Pressed %d times.", pressed_count); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Selectables")) + { + if (ImGui::TreeNode("Basic")) + { + static bool selected[4] = { false, true, false, false }; + ImGui::Selectable("1. I am selectable", &selected[0]); + ImGui::Selectable("2. I am selectable", &selected[1]); + ImGui::Text("3. I am not selectable"); + ImGui::Selectable("4. I am selectable", &selected[2]); + if (ImGui::Selectable("5. I am double clickable", selected[3], ImGuiSelectableFlags_AllowDoubleClick)) + if (ImGui::IsMouseDoubleClicked(0)) + selected[3] = !selected[3]; + ImGui::TreePop(); + } + if (ImGui::TreeNode("Rendering more text into the same block")) + { + static bool selected[3] = { false, false, false }; + ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); + ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::TreePop(); + } + if (ImGui::TreeNode("In columns")) + { + ImGui::Columns(3, NULL, false); + static bool selected[16] = { 0 }; + for (int i = 0; i < 16; i++) + { + char label[32]; sprintf(label, "Item %d", i); + if (ImGui::Selectable(label, &selected[i])) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Grid")) + { + static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; + for (int i = 0; i < 16; i++) + { + ImGui::PushID(i); + if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50))) + { + int x = i % 4, y = i / 4; + if (x > 0) selected[i - 1] ^= 1; + if (x < 3) selected[i + 1] ^= 1; + if (y > 0) selected[i - 4] ^= 1; + if (y < 3) selected[i + 4] ^= 1; + } + if ((i % 4) < 3) ImGui::SameLine(); + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Filtered Text Input")) + { + static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); + static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); + static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); + struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; + static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + + ImGui::Text("Password input"); + static char bufpass[64] = "password123"; + ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); + ImGui::SameLine(); ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-line Text Input")) + { + static bool read_only = false; + static char text[1024*16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Read-only", &read_only); + ImGui::PopStyleVar(); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0)); + ImGui::TreePop(); + } + + static bool a=false; + if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } + if (a) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f)); + ImGui::Button("Click"); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + + ImGui::Text("Hover over me"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip"); + + ImGui::SameLine(); + ImGui::Text("- or me"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::EndTooltip(); + } + + // Testing IMGUI_ONCE_UPON_A_FRAME macro + //for (int i = 0; i < 5; i++) + //{ + // IMGUI_ONCE_UPON_A_FRAME + // { + // ImGui::Text("This will be displayed only once."); + // } + //} + + ImGui::Separator(); + + ImGui::LabelText("label", "Value"); + + static int item = 1; + ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); // Combo using values packed in a single constant string (for really quick combo) + + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; + static int item2 = -1; + ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that. + + { + static char str0[128] = "Hello, world!"; + static int i0=123; + static float f0=0.001f; + ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); + ImGui::SameLine(); ShowHelpMarker("Hold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n"); + + ImGui::InputInt("input int", &i0); + ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); + + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); + + static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + ImGui::InputFloat3("input float3", vec4a); + } + + { + static int i1=50, i2=42; + ImGui::DragInt("drag int", &i1, 1); + ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value."); + + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%"); + + static float f1=1.00f, f2=0.0067f; + ImGui::DragFloat("drag float", &f1, 0.005f); + ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + } + + { + static int i1=0; + ImGui::SliderInt("slider int", &i1, -1, 3); + ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value."); + + static float f1=0.123f, f2=0.0f; + ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); + ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f); + static float angle = 0.0f; + ImGui::SliderAngle("slider angle", &angle); + } + + static float col1[3] = { 1.0f,0.0f,0.2f }; + static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::SameLine(); ShowHelpMarker("Click on the colored square to change edit mode.\nCTRL+click on individual component to input value.\n"); + + ImGui::ColorEdit4("color 2", col2); + + const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int listbox_item_current = 1; + ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + + //static int listbox_item_current2 = 2; + //ImGui::PushItemWidth(-1); + //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + //ImGui::PopItemWidth(); + + if (ImGui::TreeNode("Range Widgets")) + { + ImGui::Unindent(); + + static float begin = 10, end = 90; + static int begin_i = 100, end_i = 1000; + ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %.0f units", "Max: %.0f units"); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-component Widgets")) + { + ImGui::Unindent(); + + static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + static int vec4i[4] = { 1, 5, 100, 255 }; + + ImGui::InputFloat2("input float2", vec4f); + ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); + ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); + ImGui::InputInt2("input int2", vec4i); + ImGui::SliderInt2("slider int2", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat3("input float3", vec4f); + ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); + ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); + ImGui::InputInt3("input int3", vec4i); + ImGui::SliderInt3("slider int3", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat4("input float4", vec4f); + ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); + ImGui::InputInt4("input int4", vec4i); + ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); + ImGui::SliderInt4("slider int4", vec4i, 0, 255); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Vertical Sliders")) + { + ImGui::Unindent(); + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + static int int_value = 0; + ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); + ImGui::SameLine(); + + static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; + ImGui::PushID("set1"); + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values[i]); + ImGui::PopStyleColor(4); + ImGui::PopID(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set2"); + static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; + const int rows = 3; + const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows); + for (int nx = 0; nx < 4; nx++) + { + if (nx > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + for (int ny = 0; ny < rows; ny++) + { + ImGui::PushID(nx*rows+ny); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values2[nx]); + ImGui::PopID(); + } + ImGui::EndGroup(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set3"); + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PopStyleVar(); + ImGui::PopID(); + } + ImGui::PopID(); + ImGui::PopStyleVar(); + + ImGui::Indent(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Graphs widgets")) + { + static bool animate = true; + ImGui::Checkbox("Animate", &animate); + + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); + + // Create a dummy array of contiguous float values to plot + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter. + static float values[90] = { 0 }; + static int values_offset = 0; + if (animate) + { + static float refresh_time = ImGui::GetTime(); // Create dummy data at fixed 60 hz rate for the demo + for (; ImGui::GetTime() > refresh_time + 1.0f/60.0f; refresh_time += 1.0f/60.0f) + { + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset+1) % IM_ARRAYSIZE(values); + phase += 0.10f*values_offset; + } + } + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); + + // Use functions to generate output + // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count. + struct Funcs + { + static float Sin(void*, int i) { return sinf(i * 0.1f); } + static float Saw(void*, int i) { return (i & 1) ? 1.0f : 0.0f; } + }; + static int func_type = 0, display_count = 70; + ImGui::Separator(); + ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); + ImGui::SliderInt("Sample count", &display_count, 1, 400); + float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; + ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::Separator(); + + // Animate a simple progress bar + static float progress = 0.0f, progress_dir = 1.0f; + if (animate) + { + progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } + if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } + } + + // Typically we would use ImVec2(-1.0f,0.0f) to use all available width, or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f)); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Progress Bar"); + + float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress; + char buf[32]; + sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); + } + + if (ImGui::CollapsingHeader("Layout")) + { + if (ImGui::TreeNode("Child regions")) + { + ImGui::Text("Without border"); + static int line = 50; + bool goto_line = ImGui::Button("Goto"); + ImGui::SameLine(); + ImGui::PushItemWidth(100); + goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); + ImGui::PopItemWidth(); + ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f,300), false, ImGuiWindowFlags_HorizontalScrollbar); + for (int i = 0; i < 100; i++) + { + ImGui::Text("%04d: scrollable region", i); + if (goto_line && line == i) + ImGui::SetScrollHere(); + } + if (goto_line && line >= 100) + ImGui::SetScrollHere(); + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); + ImGui::BeginChild("Sub2", ImVec2(0,300), true); + ImGui::Text("With border"); + ImGui::Columns(2); + for (int i = 0; i < 100; i++) + { + if (i == 50) + ImGui::NextColumn(); + char buf[32]; + sprintf(buf, "%08x", i*5731); + ImGui::Button(buf, ImVec2(-1.0f, 0.0f)); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Widgets Width")) + { + static float f = 0.0f; + ImGui::Text("PushItemWidth(100)"); + ImGui::SameLine(); ShowHelpMarker("Fixed width."); + ImGui::PushItemWidth(100); + ImGui::DragFloat("float##1", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of window width."); + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); + ImGui::DragFloat("float##2", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); + ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); + ImGui::DragFloat("float##3", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-100)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge minus 100"); + ImGui::PushItemWidth(-100); + ImGui::DragFloat("float##4", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-1)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge"); + ImGui::PushItemWidth(-1); + ImGui::DragFloat("float##5", &f); + ImGui::PopItemWidth(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Basic Horizontal Layout")) + { + ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)"); + + // Text + ImGui::Text("Two items: Hello"); ImGui::SameLine(); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Adjust spacing + ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Button + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("Normal buttons"); ImGui::SameLine(); + ImGui::Button("Banana"); ImGui::SameLine(); + ImGui::Button("Apple"); ImGui::SameLine(); + ImGui::Button("Corniflower"); + + // Button + ImGui::Text("Small buttons"); ImGui::SameLine(); + ImGui::SmallButton("Like this one"); ImGui::SameLine(); + ImGui::Text("can fit within a text block."); + + // Aligned to arbitrary position. Easy/cheap column. + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::Text("x=150"); + ImGui::SameLine(300); ImGui::Text("x=300"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::SmallButton("x=150"); + ImGui::SameLine(300); ImGui::SmallButton("x=300"); + + // Checkbox + static bool c1=false,c2=false,c3=false,c4=false; + ImGui::Checkbox("My", &c1); ImGui::SameLine(); + ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); + ImGui::Checkbox("Is", &c3); ImGui::SameLine(); + ImGui::Checkbox("Rich", &c4); + + // Various + static float f0=1.0f, f1=2.0f, f2=3.0f; + ImGui::PushItemWidth(80); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; + static int item = -1; + ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); + ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Z", &f2, 0.0f,5.0f); + ImGui::PopItemWidth(); + + ImGui::PushItemWidth(80); + ImGui::Text("Lists:"); + static int selection[4] = { 0, 1, 2, 3 }; + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); + ImGui::PopID(); + //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); + } + ImGui::PopItemWidth(); + + // Dummy + ImVec2 sz(30,30); + ImGui::Button("A", sz); ImGui::SameLine(); + ImGui::Dummy(sz); ImGui::SameLine(); + ImGui::Button("B", sz); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Groups")) + { + ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it.)"); + ImGui::BeginGroup(); + { + ImGui::BeginGroup(); + ImGui::Button("AAA"); + ImGui::SameLine(); + ImGui::Button("BBB"); + ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Button("CCC"); + ImGui::Button("DDD"); + ImGui::EndGroup(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Group hovered"); + ImGui::SameLine(); + ImGui::Button("EEE"); + ImGui::EndGroup(); + } + // Capture the group size and create widgets using the same size + ImVec2 size = ImGui::GetItemRectSize(); + const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; + ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); + + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::SameLine(); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::EndGroup(); + ImGui::SameLine(); + + ImGui::Button("LEVERAGE\nBUZZWORD", size); + ImGui::SameLine(); + + ImGui::ListBoxHeader("List", size); + ImGui::Selectable("Selected", true); + ImGui::Selectable("Not Selected", false); + ImGui::ListBoxFooter(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Text Baseline Alignment")) + { + ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)"); + + ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("One\nTwo\nThree"); + + ImGui::Button("HOP##1"); ImGui::SameLine(); + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("HOP##2"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("TEST##1"); ImGui::SameLine(); + ImGui::Text("TEST"); ImGui::SameLine(); + ImGui::SmallButton("TEST##2"); + + ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets. + ImGui::Text("Text aligned to Widget"); ImGui::SameLine(); + ImGui::Button("Widget##1"); ImGui::SameLine(); + ImGui::Text("Widget"); ImGui::SameLine(); + ImGui::SmallButton("Widget##2"); + + // Tree + const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::Button("Button##1"); + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + ImGui::AlignFirstTextHeightToWidgets(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit). + bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); + if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + // Bullet + ImGui::Button("Button##3"); + ImGui::SameLine(0.0f, spacing); + ImGui::BulletText("Bullet text"); + + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::BulletText("Node"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Scrolling")) + { + ImGui::TextWrapped("(Use SetScrollHere() or SetScrollFromPosY() to scroll to a given position.)"); + static bool track = true; + static int track_line = 50, scroll_to_px = 200; + ImGui::Checkbox("Track", &track); + ImGui::PushItemWidth(100); + ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line %.0f"); + bool scroll_to = ImGui::Button("Scroll To"); + ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "y = %.0f px"); + ImGui::PopItemWidth(); + if (scroll_to) track = false; + + for (int i = 0; i < 5; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(ImGui::GetWindowWidth() * 0.17f, 200.0f), true); + if (scroll_to) + ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f); + for (int line = 0; line < 100; line++) + { + if (track && line == track_line) + { + ImGui::TextColored(ImColor(255,255,0), "Line %d", line); + ImGui::SetScrollHere(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom + } + else + { + ImGui::Text("Line %d", line); + } + } + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Horizontal Scrolling")) + { + ImGui::Bullet(); ImGui::TextWrapped("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag."); + ImGui::Bullet(); ImGui::TextWrapped("You may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); + static int lines = 7; + ImGui::SliderInt("Lines", &lines, 1, 15); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); + ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetItemsLineHeightWithSpacing()*7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar); + for (int line = 0; line < lines; line++) + { + // Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off + // manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API) + int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); + for (int n = 0; n < num_buttons; n++) + { + if (n > 0) ImGui::SameLine(); + ImGui::PushID(n + line * 1000); + char num_buf[16]; + const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : (sprintf(num_buf, "%d", n), num_buf); + float hue = n*0.05f; + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(hue, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(hue, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(hue, 0.8f, 0.8f)); + ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f)); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + float scroll_x_delta = 0.0f; + ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("Scroll from code"); ImGui::SameLine(); + ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + if (scroll_x_delta != 0.0f) + { + ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window) + ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); + ImGui::End(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Clipping")) + { + static ImVec2 size(100, 100), offset(50, 20); + ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + ImGui::DragFloat2("size", (float*)&size, 0.5f, 0.0f, 200.0f, "%.0f"); + ImGui::TextWrapped("(Click and drag)"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec4 clip_rect(pos.x, pos.y, pos.x+size.x, pos.y+size.y); + ImGui::InvisibleButton("##dummy", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; } + ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x+size.x,pos.y+size.y), ImColor(90,90,120,255)); + ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), ImColor(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Popups & Modal windows")) + { + if (ImGui::TreeNode("Popups")) + { + ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it."); + + static int selected_fish = -1; + const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; + static bool toggles[] = { true, false, false, false, false }; + + // Simple selection popup + // (If you want to show the current selection inside the Button itself, you may want to build a string using the "###" operator to preserve a constant ID with a variable label) + if (ImGui::Button("Select..")) + ImGui::OpenPopup("select"); + ImGui::SameLine(); + ImGui::Text(selected_fish == -1 ? "" : names[selected_fish]); + if (ImGui::BeginPopup("select")) + { + ImGui::Text("Aquarium"); + ImGui::Separator(); + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + if (ImGui::Selectable(names[i])) + selected_fish = i; + ImGui::EndPopup(); + } + + // Showing a menu with toggles + if (ImGui::Button("Toggle..")) + ImGui::OpenPopup("toggle"); + if (ImGui::BeginPopup("toggle")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + + ImGui::Separator(); + ImGui::Text("Tooltip here"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip over a popup"); + + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + ImGui::EndPopup(); + } + ImGui::EndPopup(); + } + + if (ImGui::Button("Popup Menu..")) + ImGui::OpenPopup("FilePopup"); + if (ImGui::BeginPopup("FilePopup")) + { + ShowExampleMenuFile(); + ImGui::EndPopup(); + } + + ImGui::Spacing(); + ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); + ImGui::Separator(); + // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above. + // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here + // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus. + ImGui::PushID("foo"); + ImGui::MenuItem("Menu item", "CTRL+M"); + if (ImGui::BeginMenu("Menu inside a regular window")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::PopID(); + ImGui::Separator(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Context menus")) + { + static float value = 0.5f; + ImGui::Text("Value = %.3f (<-- right-click here)", value); + if (ImGui::BeginPopupContextItem("item context menu")) + { + if (ImGui::Selectable("Set to zero")) value = 0.0f; + if (ImGui::Selectable("Set to PI")) value = 3.1415f; + ImGui::EndPopup(); + } + + static ImVec4 color = ImColor(0.8f, 0.5f, 1.0f, 1.0f); + ImGui::ColorButton(color); + if (ImGui::BeginPopupContextItem("color context menu")) + { + ImGui::Text("Edit color"); + ImGui::ColorEdit3("##edit", (float*)&color); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::SameLine(); ImGui::Text("(<-- right-click here)"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Modals")) + { + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window."); + + if (ImGui::Button("Delete..")) + ImGui::OpenPopup("Delete?"); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); + ImGui::Separator(); + + //static int dummy_i = 0; + //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0"); + + static bool dont_ask_me_next_time = false; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time); + ImGui::PopStyleVar(); + + if (ImGui::Button("OK", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::EndPopup(); + } + + if (ImGui::Button("Stacked modals..")) + ImGui::OpenPopup("Stacked 1"); + if (ImGui::BeginPopupModal("Stacked 1")) + { + ImGui::Text("Hello from Stacked The First"); + + if (ImGui::Button("Another one..")) + ImGui::OpenPopup("Stacked 2"); + if (ImGui::BeginPopupModal("Stacked 2")) + { + ImGui::Text("Hello from Stacked The Second"); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Columns")) + { + // Basic columns + if (ImGui::TreeNode("Basic")) + { + ImGui::Text("Without border:"); + ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border + ImGui::Separator(); + for (int n = 0; n < 14; n++) + { + char label[32]; + sprintf(label, "Item %d", n); + if (ImGui::Selectable(label)) {} + //if (ImGui::Button(label, ImVec2(-1,0))) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + + ImGui::Text("With border:"); + ImGui::Columns(4, "mycolumns"); // 4-ways, with border + ImGui::Separator(); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Text("Flags"); ImGui::NextColumn(); + ImGui::Separator(); + const char* names[3] = { "One", "Two", "Three" }; + const char* paths[3] = { "/path/one", "/path/two", "/path/three" }; + static int selected = -1; + for (int i = 0; i < 3; i++) + { + char label[32]; + sprintf(label, "%04d", i); + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns)) + selected = i; + ImGui::NextColumn(); + ImGui::Text(names[i]); ImGui::NextColumn(); + ImGui::Text(paths[i]); ImGui::NextColumn(); + ImGui::Text("...."); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Scrolling columns + /* + if (ImGui::TreeNode("Scrolling")) + { + ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y)); + ImGui::Columns(3); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::EndChild(); + ImGui::BeginChild("##scrollingregion", ImVec2(0, 60)); + ImGui::Columns(3); + for (int i = 0; i < 10; i++) + { + ImGui::Text("%04d", i); ImGui::NextColumn(); + ImGui::Text("Foobar"); ImGui::NextColumn(); + ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::EndChild(); + ImGui::TreePop(); + } + */ + + // Create multiple items in a same cell before switching to next column + if (ImGui::TreeNode("Mixed items")) + { + ImGui::Columns(3, "mixed"); + ImGui::Separator(); + + ImGui::Text("Hello"); + ImGui::Button("Banana"); + ImGui::NextColumn(); + + ImGui::Text("ImGui"); + ImGui::Button("Apple"); + static float foo = 1.0f; + ImGui::InputFloat("red", &foo, 0.05f, 0, 3); + ImGui::Text("An extra line here."); + ImGui::NextColumn(); + + ImGui::Text("Sailor"); + ImGui::Button("Corniflower"); + static float bar = 1.0f; + ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); + ImGui::NextColumn(); + + if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Word wrapping + if (ImGui::TreeNode("Word-wrapping")) + { + ImGui::Columns(2, "word-wrapping"); + ImGui::Separator(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Left"); + ImGui::NextColumn(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Right"); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Borders")) + { + static bool h_borders = true; + static bool v_borders = true; + ImGui::Checkbox("horizontal", &h_borders); + ImGui::SameLine(); + ImGui::Checkbox("vertical", &v_borders); + ImGui::Columns(4, NULL, v_borders); + if (h_borders) ImGui::Separator(); + for (int i = 0; i < 8; i++) + { + ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); + ImGui::NextColumn(); + } + ImGui::Columns(1); + if (h_borders) ImGui::Separator(); + ImGui::TreePop(); + } + + bool node_open = ImGui::TreeNode("Tree within single cell"); + ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell.\nThere's no storage of state per-cell."); + if (node_open) + { + ImGui::Columns(2, "tree items"); + ImGui::Separator(); + if (ImGui::TreeNode("Hello")) { ImGui::BulletText("Sailor"); ImGui::TreePop(); } ImGui::NextColumn(); + if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Marin"); ImGui::TreePop(); } ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Filtering")) + { + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_ARRAYSIZE(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + } + + if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus")) + { + if (ImGui::TreeNode("Tabbing")) + { + ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); + static char buf[32] = "dummy"; + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); + ImGui::PushAllowKeyboardFocus(false); + ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); + //ImGui::SameLine(); ShowHelperMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + ImGui::PopAllowKeyboardFocus(); + ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Focus from code")) + { + bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + bool focus_3 = ImGui::Button("Focus on 3"); + int has_focus = 0; + static char buf[128] = "click on a button to set focus"; + + if (focus_1) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 1; + + if (focus_2) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 2; + + ImGui::PushAllowKeyboardFocus(false); + if (focus_3) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 3; + ImGui::PopAllowKeyboardFocus(); + if (has_focus) + ImGui::Text("Item with focus: %d", has_focus); + else + ImGui::Text("Item with focus: "); + ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code."); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Dragging")) + { + ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget."); + ImGui::Button("Drag Me"); + if (ImGui::IsItemActive()) + { + // Draw a line between the button and the mouse cursor + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->PushClipRectFullScreen(); + draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f); + draw_list->PopClipRect(); + ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + ImVec2 mouse_delta = ImGui::GetIO().MouseDelta; + ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Keyboard & Mouse State")) + { + ImGuiIO& io = ImGui::GetIO(); + + ImGui::Text("MousePos: (%g, %g)", io.MousePos.x, io.MousePos.y); + ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("MouseWheel: %.1f", io.MouseWheel); + + ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); } + ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("KeyMods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + + ImGui::Text("WantCaptureMouse: %s", io.WantCaptureMouse ? "true" : "false"); + ImGui::Text("WantCaptureKeyboard: %s", io.WantCaptureKeyboard ? "true" : "false"); + ImGui::Text("WantTextInput: %s", io.WantTextInput ? "true" : "false"); + + ImGui::Button("Hovering me sets the\nkeyboard capture flag"); + if (ImGui::IsItemHovered()) + ImGui::CaptureKeyboardFromApp(true); + ImGui::SameLine(); + ImGui::Button("Holding me clears the\nthe keyboard capture flag"); + if (ImGui::IsItemActive()) + ImGui::CaptureKeyboardFromApp(false); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Mouse cursors")) + { + ImGui::TextWrapped("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software."); + ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor); + ImGui::Text("Hover to see mouse cursors:"); + for (int i = 0; i < ImGuiMouseCursor_Count_; i++) + { + char label[32]; + sprintf(label, "Mouse cursor %d", i); + ImGui::Bullet(); ImGui::Selectable(label, false); + if (ImGui::IsItemHovered()) + ImGui::SetMouseCursor(i); + } + ImGui::TreePop(); + } + } + + ImGui::End(); +} + +void ImGui::ShowStyleEditor(ImGuiStyle* ref) +{ + ImGuiStyle& style = ImGui::GetStyle(); + + // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to the default style) + const ImGuiStyle default_style; // Default style + if (ImGui::Button("Revert Style")) + style = ref ? *ref : default_style; + + if (ref) + { + ImGui::SameLine(); + if (ImGui::Button("Save Style")) + *ref = style; + } + + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f); + + if (ImGui::TreeNode("Rendering")) + { + ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + ImGui::Checkbox("Anti-aliased shapes", &style.AntiAliasedShapes); + ImGui::PushItemWidth(100); + ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, NULL, 2.0f); + if (style.CurveTessellationTol < 0.0f) style.CurveTessellationTol = 0.10f; + ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + ImGui::PopItemWidth(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Settings")) + { + ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 16.0f, "%.0f"); + ImGui::Text("Alignment"); + ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a button is larger than its text content."); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colors")) + { + static int output_dest = 0; + static bool output_only_modified = false; + if (ImGui::Button("Copy Colors")) + { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" IM_NEWLINE); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const ImVec4& col = style.Colors[i]; + const char* name = ImGui::GetStyleColName(i); + if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 22 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + } + ImGui::LogFinish(); + } + ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified); + + static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; + ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); + ImGui::SameLine(); + ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); + ImGui::SameLine(); + ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); + //ImGui::Text("Tip: Click on colored square to change edit mode."); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", 200); + + ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar); + ImGui::PushItemWidth(-160); + ImGui::ColorEditMode(edit_mode); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = ImGui::GetStyleColName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); + if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + { + ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : default_style.Colors[i]; + if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } + } + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::EndChild(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size)) + { + ImGui::SameLine(); ShowHelpMarker("Tip: Load fonts with io.Fonts->AddFontFromFileTTF()\nbefore calling io.Fonts->GetTex* functions."); + ImFontAtlas* atlas = ImGui::GetIO().Fonts; + if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + { + ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::TreePop(); + } + ImGui::PushItemWidth(100); + for (int i = 0; i < atlas->Fonts.Size; i++) + { + ImFont* font = atlas->Fonts[i]; + ImGui::BulletText("Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size); + ImGui::TreePush((void*)(intptr_t)i); + ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) ImGui::GetIO().FontDefault = font; + ImGui::PushFont(font); + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::PopFont(); + if (ImGui::TreeNode("Details")) + { + ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font + ImGui::SameLine(); ShowHelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.\n\n(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)"); + ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar); + ImGui::Text("Texture surface: %d pixels (approx) ~ %dx%d", font->MetricsTotalSurface, (int)sqrtf((float)font->MetricsTotalSurface), (int)sqrtf((float)font->MetricsTotalSurface)); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + { + ImFontConfig* cfg = &font->ConfigData[config_i]; + ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); + } + if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + { + // Display all glyphs of the fonts in separate pages of 256 characters + const ImFont::Glyph* glyph_fallback = font->FallbackGlyph; // Forcefully/dodgily make FindGlyph() return NULL on fallback, which isn't the default behavior. + font->FallbackGlyph = NULL; + for (int base = 0; base < 0x10000; base += 256) + { + int count = 0; + for (int n = 0; n < 256; n++) + count += font->FindGlyph((ImWchar)(base + n)) ? 1 : 0; + if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base+255, count, count > 1 ? "glyphs" : "glyph")) + { + float cell_spacing = style.ItemSpacing.y; + ImVec2 cell_size(font->FontSize * 1, font->FontSize * 1); + ImVec2 base_pos = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 256; n++) + { + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size.x + cell_spacing), base_pos.y + (n / 16) * (cell_size.y + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size.x, cell_p1.y + cell_size.y); + const ImFont::Glyph* glyph = font->FindGlyph((ImWchar)(base+n));; + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255,255,255,100) : IM_COL32(255,255,255,50)); + font->RenderChar(draw_list, cell_size.x, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base+n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string. + if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) + { + ImGui::BeginTooltip(); + ImGui::Text("Codepoint: U+%04X", base+n); + ImGui::Separator(); + ImGui::Text("XAdvance+1: %.1f", glyph->XAdvance); + ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + ImGui::EndTooltip(); + } + } + ImGui::Dummy(ImVec2((cell_size.x + cell_spacing) * 16, (cell_size.y + cell_spacing) * 16)); + ImGui::TreePop(); + } + } + font->FallbackGlyph = glyph_fallback; + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + static float window_scale = 1.0f; + ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this window + ImGui::DragFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale everything + ImGui::PopItemWidth(); + ImGui::SetWindowFontScale(window_scale); + ImGui::TreePop(); + } + + ImGui::PopItemWidth(); +} + +// Demonstrate creating a fullscreen menu bar and populating it. +static void ShowExampleAppMainMenuBar() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Undo", "CTRL+Z")) {} + if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item + ImGui::Separator(); + if (ImGui::MenuItem("Cut", "CTRL+X")) {} + if (ImGui::MenuItem("Copy", "CTRL+C")) {} + if (ImGui::MenuItem("Paste", "CTRL+V")) {} + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} + +static void ShowExampleMenuFile() +{ + ImGui::MenuItem("(dummy menu)", NULL, false, false); + if (ImGui::MenuItem("New")) {} + if (ImGui::MenuItem("Open", "Ctrl+O")) {} + if (ImGui::BeginMenu("Open Recent")) + { + ImGui::MenuItem("fish_hat.c"); + ImGui::MenuItem("fish_hat.inl"); + ImGui::MenuItem("fish_hat.h"); + if (ImGui::BeginMenu("More..")) + { + ImGui::MenuItem("Hello"); + ImGui::MenuItem("Sailor"); + if (ImGui::BeginMenu("Recurse..")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Save", "Ctrl+S")) {} + if (ImGui::MenuItem("Save As..")) {} + ImGui::Separator(); + if (ImGui::BeginMenu("Options")) + { + static bool enabled = true; + ImGui::MenuItem("Enabled", "", &enabled); + ImGui::BeginChild("child", ImVec2(0, 60), true); + for (int i = 0; i < 10; i++) + ImGui::Text("Scrolling Text %d", i); + ImGui::EndChild(); + static float f = 0.5f; + static int n = 0; + ImGui::SliderFloat("Value", &f, 0.0f, 1.0f); + ImGui::InputFloat("Input", &f, 0.1f); + ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0"); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Colors")) + { + for (int i = 0; i < ImGuiCol_COUNT; i++) + ImGui::MenuItem(ImGui::GetStyleColName((ImGuiCol)i)); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Disabled", false)) // Disabled + { + IM_ASSERT(0); + } + if (ImGui::MenuItem("Checked", NULL, true)) {} + if (ImGui::MenuItem("Quit", "Alt+F4")) {} +} + +// Demonstrate creating a window which gets auto-resized according to its content. +static void ShowExampleAppAutoResize(bool* p_open) +{ + if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + + static int lines = 10; + ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop."); + ImGui::SliderInt("Number of lines", &lines, 1, 20); + for (int i = 0; i < lines; i++) + ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally + ImGui::End(); +} + +// Demonstrate creating a window with custom resize constraints. +static void ShowExampleAppConstrainedResize(bool* p_open) +{ + struct CustomConstraints // Helper functions to demonstrate programmatic constraints + { + static void Square(ImGuiSizeConstraintCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); } + static void Step(ImGuiSizeConstraintCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } + }; + + static int type = 0; + if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only + if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only + if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100 + if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(300, 0), ImVec2(400, FLT_MAX)); // Width 300-400 + if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square + if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step + + if (ImGui::Begin("Example: Constrained Resize", p_open)) + { + const char* desc[] = + { + "Resize vertical only", + "Resize horizontal only", + "Width > 100, Height > 100", + "Width 300-400", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); + if (ImGui::Button("200x200")) ImGui::SetWindowSize(ImVec2(200,200)); ImGui::SameLine(); + if (ImGui::Button("500x500")) ImGui::SetWindowSize(ImVec2(500,500)); ImGui::SameLine(); + if (ImGui::Button("800x200")) ImGui::SetWindowSize(ImVec2(800,200)); + for (int i = 0; i < 10; i++) + ImGui::Text("Hello, sailor! Making this line long enough for the example."); + } + ImGui::End(); +} + +// Demonstrate creating a simple static window with no decoration. +static void ShowExampleAppFixedOverlay(bool* p_open) +{ + ImGui::SetNextWindowPos(ImVec2(10,10)); + if (!ImGui::Begin("Example: Fixed Overlay", p_open, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) + { + ImGui::End(); + return; + } + ImGui::Text("Simple overlay\non the top-left side of the screen."); + ImGui::Separator(); + ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); + ImGui::End(); +} + +// Demonstrate using "##" and "###" in identifiers to manipulate ID generation. +// Read section "How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs." about ID. +static void ShowExampleAppManipulatingWindowTitle(bool*) +{ + // By default, Windows are uniquely identified by their title. + // You can use the "##" and "###" markers to manipulate the display/ID. + + // Using "##" to display same title but have unique identifier. + ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##1"); + ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); + ImGui::End(); + + ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##2"); + ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); + ImGui::End(); + + // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" + char buf[128]; + sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand()); + ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver); + ImGui::Begin(buf); + ImGui::Text("This window has a changing title."); + ImGui::End(); +} + +// Demonstrate using the low-level ImDrawList to draw custom shapes. +static void ShowExampleAppCustomRendering(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Custom rendering", p_open)) + { + ImGui::End(); + return; + } + + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. + // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. + // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) + // In this example we are not using the maths operators! + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + // Primitives + ImGui::Text("Primitives"); + static float sz = 36.0f; + static ImVec4 col = ImVec4(1.0f,1.0f,0.4f,1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f"); + ImGui::ColorEdit3("Color", &col.x); + { + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col32 = ImColor(col); + float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f; + for (int n = 0; n < 2; n++) + { + float thickness = (n == 0) ? 1.0f : 4.0f; + draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ~0, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ~0, thickness); x += sz+spacing; + draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y ), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y+sz), col32, thickness); x += spacing; + draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x+sz*1.3f,y+sz*0.3f), ImVec2(x+sz-sz*1.3f,y+sz-sz*0.3f), ImVec2(x+sz, y+sz), col32, thickness); + x = p.x + 4; + y += sz+spacing; + } + draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing; + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing; + draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), ImColor(0,0,0), ImColor(255,0,0), ImColor(255,255,0), ImColor(0,255,0)); + ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3)); + } + ImGui::Separator(); + { + static ImVector points; + static bool adding_line = false; + ImGui::Text("Canvas example"); + if (ImGui::Button("Clear")) points.clear(); + if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } + ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); + + // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() + // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). + // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). + ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; + if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; + draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60)); + draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(255,255,255)); + + bool adding_preview = false; + ImGui::InvisibleButton("canvas", canvas_size); + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); + if (adding_line) + { + adding_preview = true; + points.push_back(mouse_pos_in_canvas); + if (!ImGui::GetIO().MouseDown[0]) + adding_line = adding_preview = false; + } + if (ImGui::IsItemHovered()) + { + if (!adding_line && ImGui::IsMouseClicked(0)) + { + points.push_back(mouse_pos_in_canvas); + adding_line = true; + } + if (ImGui::IsMouseClicked(1) && !points.empty()) + { + adding_line = adding_preview = false; + points.pop_back(); + points.pop_back(); + } + } + draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.) + for (int i = 0; i < points.Size - 1; i += 2) + draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), IM_COL32(255,255,0,255), 2.0f); + draw_list->PopClipRect(); + if (adding_preview) + points.pop_back(); + } + ImGui::End(); +} + +// Demonstrating creating a simple console window, with scrolling, filtering, completion and history. +// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions. +struct ExampleAppConsole +{ + char InputBuf[256]; + ImVector Items; + bool ScrollToBottom; + ImVector History; + int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. + ImVector Commands; + + ExampleAppConsole() + { + ClearLog(); + memset(InputBuf, 0, sizeof(InputBuf)); + HistoryPos = -1; + Commands.push_back("HELP"); + Commands.push_back("HISTORY"); + Commands.push_back("CLEAR"); + Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. + AddLog("Welcome to ImGui!"); + } + ~ExampleAppConsole() + { + ClearLog(); + for (int i = 0; i < History.Size; i++) + free(History[i]); + } + + // Portable helpers + static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } + static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } + static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buff = malloc(len); return (char*)memcpy(buff, (const void*)str, len); } + + void ClearLog() + { + for (int i = 0; i < Items.Size; i++) + free(Items[i]); + Items.clear(); + ScrollToBottom = true; + } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + char buf[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); + buf[IM_ARRAYSIZE(buf)-1] = 0; + va_end(args); + Items.push_back(Strdup(buf)); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open) + { + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); + + // TODO: display items starting from the bottom + + if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) ClearLog(); ImGui::SameLine(); + if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true; + //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } + + ImGui::Separator(); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + static ImGuiTextFilter filter; + filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + ImGui::PopStyleVar(); + ImGui::Separator(); + + ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar); + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::Selectable("Clear")) ClearLog(); + ImGui::EndPopup(); + } + + // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items. + // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements. + // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with: + // ImGuiListClipper clipper(Items.Size); + // while (clipper.Step()) + // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + // However take note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code! + // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing + for (int i = 0; i < Items.Size; i++) + { + const char* item = Items[i]; + if (!filter.PassFilter(item)) + continue; + ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text. + if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f); + else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f); + ImGui::PushStyleColor(ImGuiCol_Text, col); + ImGui::TextUnformatted(item); + ImGui::PopStyleColor(); + } + if (ScrollToBottom) + ImGui::SetScrollHere(); + ScrollToBottom = false; + ImGui::PopStyleVar(); + ImGui::EndChild(); + ImGui::Separator(); + + // Command-line + if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) + { + char* input_end = InputBuf+strlen(InputBuf); + while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0; + if (InputBuf[0]) + ExecCommand(InputBuf); + strcpy(InputBuf, ""); + } + + // Demonstrate keeping auto focus on the input box + if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) + ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget + + ImGui::End(); + } + + void ExecCommand(const char* command_line) + { + AddLog("# %s\n", command_line); + + // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. + HistoryPos = -1; + for (int i = History.Size-1; i >= 0; i--) + if (Stricmp(History[i], command_line) == 0) + { + free(History[i]); + History.erase(History.begin() + i); + break; + } + History.push_back(Strdup(command_line)); + + // Process command + if (Stricmp(command_line, "CLEAR") == 0) + { + ClearLog(); + } + else if (Stricmp(command_line, "HELP") == 0) + { + AddLog("Commands:"); + for (int i = 0; i < Commands.Size; i++) + AddLog("- %s", Commands[i]); + } + else if (Stricmp(command_line, "HISTORY") == 0) + { + for (int i = History.Size >= 10 ? History.Size - 10 : 0; i < History.Size; i++) + AddLog("%3d: %s\n", i, History[i]); + } + else + { + AddLog("Unknown command: '%s'\n", command_line); + } + } + + static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks + { + ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; + return console->TextEditCallback(data); + } + + int TextEditCallback(ImGuiTextEditCallbackData* data) + { + //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); + switch (data->EventFlag) + { + case ImGuiInputTextFlags_CallbackCompletion: + { + // Example of TEXT COMPLETION + + // Locate beginning of current word + const char* word_end = data->Buf + data->CursorPos; + const char* word_start = word_end; + while (word_start > data->Buf) + { + const char c = word_start[-1]; + if (c == ' ' || c == '\t' || c == ',' || c == ';') + break; + word_start--; + } + + // Build a list of candidates + ImVector candidates; + for (int i = 0; i < Commands.Size; i++) + if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) + candidates.push_back(Commands[i]); + + if (candidates.Size == 0) + { + // No match + AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); + } + else if (candidates.Size == 1) + { + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing + data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0]); + data->InsertChars(data->CursorPos, " "); + } + else + { + // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" + int match_len = (int)(word_end - word_start); + for (;;) + { + int c = 0; + bool all_candidates_matches = true; + for (int i = 0; i < candidates.Size && all_candidates_matches; i++) + if (i == 0) + c = toupper(candidates[i][match_len]); + else if (c == 0 || c != toupper(candidates[i][match_len])) + all_candidates_matches = false; + if (!all_candidates_matches) + break; + match_len++; + } + + if (match_len > 0) + { + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + } + + // List matches + AddLog("Possible matches:\n"); + for (int i = 0; i < candidates.Size; i++) + AddLog("- %s\n", candidates[i]); + } + + break; + } + case ImGuiInputTextFlags_CallbackHistory: + { + // Example of HISTORY + const int prev_history_pos = HistoryPos; + if (data->EventKey == ImGuiKey_UpArrow) + { + if (HistoryPos == -1) + HistoryPos = History.Size - 1; + else if (HistoryPos > 0) + HistoryPos--; + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + if (HistoryPos != -1) + if (++HistoryPos >= History.Size) + HistoryPos = -1; + } + + // A better implementation would preserve the data on the current input line along with cursor position. + if (prev_history_pos != HistoryPos) + { + data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); + data->BufDirty = true; + } + } + } + return 0; + } +}; + +static void ShowExampleAppConsole(bool* p_open) +{ + static ExampleAppConsole console; + console.Draw("Example: Console", p_open); +} + +// Usage: +// static ExampleAppLog my_log; +// my_log.AddLog("Hello %d world\n", 123); +// my_log.Draw("title"); +struct ExampleAppLog +{ + ImGuiTextBuffer Buf; + ImGuiTextFilter Filter; + ImVector LineOffsets; // Index to lines offset + bool ScrollToBottom; + + void Clear() { Buf.clear(); LineOffsets.clear(); } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open = NULL) + { + ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver); + ImGui::Begin(title, p_open); + if (ImGui::Button("Clear")) Clear(); + ImGui::SameLine(); + bool copy = ImGui::Button("Copy"); + ImGui::SameLine(); + Filter.Draw("Filter", -100.0f); + ImGui::Separator(); + ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); + if (copy) ImGui::LogToClipboard(); + + if (Filter.IsActive()) + { + const char* buf_begin = Buf.begin(); + const char* line = buf_begin; + for (int line_no = 0; line != NULL; line_no++) + { + const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; + if (Filter.PassFilter(line, line_end)) + ImGui::TextUnformatted(line, line_end); + line = line_end && line_end[1] ? line_end + 1 : NULL; + } + } + else + { + ImGui::TextUnformatted(Buf.begin()); + } + + if (ScrollToBottom) + ImGui::SetScrollHere(1.0f); + ScrollToBottom = false; + ImGui::EndChild(); + ImGui::End(); + } +}; + +// Demonstrate creating a simple log window with basic filtering. +static void ShowExampleAppLog(bool* p_open) +{ + static ExampleAppLog log; + + // Demo fill + static float last_time = -1.0f; + float time = ImGui::GetTime(); + if (time - last_time >= 0.3f) + { + const char* random_words[] = { "system", "info", "warning", "error", "fatal", "notice", "log" }; + log.AddLog("[%s] Hello, time is %.1f, rand() %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, (int)rand()); + last_time = time; + } + + log.Draw("Example: Log", p_open); +} + +// Demonstrate create a window with multiple child windows. +static void ShowExampleAppLayout(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiSetCond_FirstUseEver); + if (ImGui::Begin("Example: Layout", p_open, ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Close")) *p_open = false; + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // left + static int selected = 0; + ImGui::BeginChild("left pane", ImVec2(150, 0), true); + for (int i = 0; i < 100; i++) + { + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i)) + selected = i; + } + ImGui::EndChild(); + ImGui::SameLine(); + + // right + ImGui::BeginGroup(); + ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing())); // Leave room for 1 line below us + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndChild(); + ImGui::BeginChild("buttons"); + if (ImGui::Button("Revert")) {} + ImGui::SameLine(); + if (ImGui::Button("Save")) {} + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::End(); +} + +// Demonstrate create a simple property editor. +static void ShowExampleAppPropertyEditor(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Property editor", p_open)) + { + ImGui::End(); + return; + } + + ShowHelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API."); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); + ImGui::Columns(2); + ImGui::Separator(); + + struct funcs + { + static void ShowDummyObject(const char* prefix, int uid) + { + ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. + ImGui::AlignFirstTextHeightToWidgets(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high. + bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + ImGui::NextColumn(); + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("my sailor is rich"); + ImGui::NextColumn(); + if (node_open) + { + static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); // Use field index as identifier. + if (i < 2) + { + ShowDummyObject("Child", 424242); + } + else + { + ImGui::AlignFirstTextHeightToWidgets(); + // Here we use a Selectable (instead of Text) to highlight on hover + //ImGui::Text("Field_%d", i); + char label[32]; + sprintf(label, "Field_%d", i); + ImGui::Bullet(); + ImGui::Selectable(label); + ImGui::NextColumn(); + ImGui::PushItemWidth(-1); + if (i >= 5) + ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + else + ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::PopItemWidth(); + ImGui::NextColumn(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::PopID(); + } + }; + + // Iterate dummy objects with dummy members (all the same data) + for (int obj_i = 0; obj_i < 3; obj_i++) + funcs::ShowDummyObject("Object", obj_i); + + ImGui::Columns(1); + ImGui::Separator(); + ImGui::PopStyleVar(); + ImGui::End(); +} + +// Demonstrate/test rendering huge amount of text, and the incidence of clipping. +static void ShowExampleAppLongText(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Long text display", p_open)) + { + ImGui::End(); + return; + } + + static int test_type = 0; + static ImGuiTextBuffer log; + static int lines = 0; + ImGui::Text("Printing unusually long amount of text."); + ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped\0"); + ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); + if (ImGui::Button("Clear")) { log.clear(); lines = 0; } + ImGui::SameLine(); + if (ImGui::Button("Add 1000 lines")) + { + for (int i = 0; i < 1000; i++) + log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); + lines += 1000; + } + ImGui::BeginChild("Log"); + switch (test_type) + { + case 0: + // Single call to TextUnformatted() with a big buffer + ImGui::TextUnformatted(log.begin(), log.end()); + break; + case 1: + { + // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGuiListClipper clipper(lines); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + case 2: + // Multiple calls to Text(), not clipped (slow) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + for (int i = 0; i < lines; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + ImGui::EndChild(); + ImGui::End(); +} + +// End of Demo code +#else + +void ImGui::ShowTestWindow(bool*) {} +void ImGui::ShowUserGuide() {} +void ImGui::ShowStyleEditor(ImGuiStyle*) {} + +#endif diff --git a/src/imgui/imgui_draw.cpp b/src/imgui/imgui_draw.cpp new file mode 100644 index 00000000..fa6838a6 --- /dev/null +++ b/src/imgui/imgui_draw.cpp @@ -0,0 +1,2417 @@ +// dear imgui, v1.51 WIP +// (drawing and font code) + +// Contains implementation for +// - ImDrawList +// - ImDrawData +// - ImFontAtlas +// - ImFont +// - Default font data + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + +#include // vsnprintf, sscanf, printf +#if !defined(alloca) +#ifdef _WIN32 +#include // alloca +#elif (defined(__FreeBSD__) || defined(FreeBSD_kernel) || defined(__DragonFly__)) && !defined(__GLIBC__) +#include // alloca. FreeBSD uses stdlib.h unless GLIBC +#else +#include // alloca +#endif +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif + +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#if __has_warning("-Wreserved-id-macro") +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#endif +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers +#endif + +//------------------------------------------------------------------------- +// STB libraries implementation +//------------------------------------------------------------------------- + +//#define IMGUI_STB_NAMESPACE ImGuiStb +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION + +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE +{ +#endif + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#endif + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] +#endif + +#define STBRP_ASSERT(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +#define STBRP_STATIC +#define STB_RECT_PACK_IMPLEMENTATION +#endif +#include "stb_rect_pack.h" + +#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) +#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) +#define STBTT_assert(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#else +#define STBTT_DEF extern +#endif +#include "stb_truetype.h" + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +#ifdef IMGUI_STB_NAMESPACE +} // namespace ImGuiStb +using namespace IMGUI_STB_NAMESPACE; +#endif + +//----------------------------------------------------------------------------- +// ImDrawList +//----------------------------------------------------------------------------- + +static const ImVec4 GNullClipRect(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Large values that are easy to encode in a few bits+shift + +void ImDrawList::Clear() +{ + CmdBuffer.resize(0); + IdxBuffer.resize(0); + VtxBuffer.resize(0); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.resize(0); + _TextureIdStack.resize(0); + _Path.resize(0); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + // NB: Do not clear channels so our allocations are re-used after the first frame. +} + +void ImDrawList::ClearFreeMemory() +{ + CmdBuffer.clear(); + IdxBuffer.clear(); + VtxBuffer.clear(); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.clear(); + _TextureIdStack.clear(); + _Path.clear(); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + for (int i = 0; i < _Channels.Size; i++) + { + if (i == 0) memset(&_Channels[0], 0, sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i].CmdBuffer.clear(); + _Channels[i].IdxBuffer.clear(); + } + _Channels.clear(); +} + +// Use macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug mode +#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : GNullClipRect) +#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL) + +void ImDrawList::AddDrawCmd() +{ + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = GetCurrentClipRect(); + draw_cmd.TextureId = GetCurrentTextureId(); + + IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); + CmdBuffer.push_back(draw_cmd); +} + +void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) +{ + ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) + { + AddDrawCmd(); + current_cmd = &CmdBuffer.back(); + } + current_cmd->UserCallback = callback; + current_cmd->UserCallbackData = callback_data; + + AddDrawCmd(); // Force a new command after us (see comment below) +} + +// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +void ImDrawList::UpdateClipRect() +{ + // If current command is used with different settings we need to add a new command + const ImVec4 curr_clip_rect = GetCurrentClipRect(); + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->ClipRect = curr_clip_rect; +} + +void ImDrawList::UpdateTextureID() +{ + // If current command is used with different settings we need to add a new command + const ImTextureID curr_texture_id = GetCurrentTextureId(); + ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->TextureId = curr_texture_id; +} + +#undef GetCurrentClipRect +#undef GetCurrentTextureId + +// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) +void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) +{ + ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); + if (intersect_with_current_clip_rect && _ClipRectStack.Size) + { + ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + if (cr.x < current.x) cr.x = current.x; + if (cr.y < current.y) cr.y = current.y; + if (cr.z > current.z) cr.z = current.z; + if (cr.w > current.w) cr.w = current.w; + } + cr.z = ImMax(cr.x, cr.z); + cr.w = ImMax(cr.y, cr.w); + + _ClipRectStack.push_back(cr); + UpdateClipRect(); +} + +void ImDrawList::PushClipRectFullScreen() +{ + PushClipRect(ImVec2(GNullClipRect.x, GNullClipRect.y), ImVec2(GNullClipRect.z, GNullClipRect.w)); + //PushClipRect(GetVisibleRect()); // FIXME-OPT: This would be more correct but we're not supposed to access ImGuiContext from here? +} + +void ImDrawList::PopClipRect() +{ + IM_ASSERT(_ClipRectStack.Size > 0); + _ClipRectStack.pop_back(); + UpdateClipRect(); +} + +void ImDrawList::PushTextureID(const ImTextureID& texture_id) +{ + _TextureIdStack.push_back(texture_id); + UpdateTextureID(); +} + +void ImDrawList::PopTextureID() +{ + IM_ASSERT(_TextureIdStack.Size > 0); + _TextureIdStack.pop_back(); + UpdateTextureID(); +} + +void ImDrawList::ChannelsSplit(int channels_count) +{ + IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + _Channels.resize(channels_count); + _ChannelsCount = channels_count; + + // _Channels[] (24 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer + // The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); + } + else + { + _Channels[i].CmdBuffer.resize(0); + _Channels[i].IdxBuffer.resize(0); + } + if (_Channels[i].CmdBuffer.Size == 0) + { + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = _ClipRectStack.back(); + draw_cmd.TextureId = _TextureIdStack.back(); + _Channels[i].CmdBuffer.push_back(draw_cmd); + } + } +} + +void ImDrawList::ChannelsMerge() +{ + // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_ChannelsCount <= 1) + return; + + ChannelsSetCurrent(0); + if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) + CmdBuffer.pop_back(); + + int new_cmd_buffer_count = 0, new_idx_buffer_count = 0; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) + ch.CmdBuffer.pop_back(); + new_cmd_buffer_count += ch.CmdBuffer.Size; + new_idx_buffer_count += ch.IdxBuffer.Size; + } + CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); + IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); + + ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; } + } + AddDrawCmd(); + _ChannelsCount = 1; +} + +void ImDrawList::ChannelsSetCurrent(int idx) +{ + IM_ASSERT(idx < _ChannelsCount); + if (_ChannelsCurrent == idx) return; + memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times + memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer)); + _ChannelsCurrent = idx; + memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer)); + memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer)); + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size; +} + +// NB: this can be called with negative count for removing primitives (as long as the result does not underflow) +void ImDrawList::PrimReserve(int idx_count, int vtx_count) +{ + ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; + draw_cmd.ElemCount += idx_count; + + int vtx_buffer_old_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_old_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; + + int idx_buffer_old_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_old_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; +} + +// Fully unrolled with inline call to keep our debug builds decently fast. +void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv(GImGui->FontTexUvWhitePixel); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness, bool anti_aliased) +{ + if (points_count < 2) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedLines; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + int count = points_count; + if (!closed) + count = points_count-1; + + const bool thick_line = thickness > 1.0f; + if (anti_aliased) + { + // Anti-aliased stroke + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & IM_COL32(255,255,255,0); + + const int idx_count = thick_line ? count*18 : count*12; + const int vtx_count = thick_line ? points_count*4 : points_count*3; + PrimReserve(idx_count, vtx_count); + + // Temporary buffer + ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); + ImVec2* temp_points = temp_normals + points_count; + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + ImVec2 diff = points[i2] - points[i1]; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i1].x = diff.y; + temp_normals[i1].y = -diff.x; + } + if (!closed) + temp_normals[points_count-1] = temp_normals[points_count-2]; + + if (!thick_line) + { + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; + temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE; + temp_points[i2*2+0] = points[i2] + dm; + temp_points[i2*2+1] = points[i2] - dm; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); + _IdxWritePtr += 12; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; + _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; + _VtxWritePtr += 3; + } + } + else + { + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + ImVec2 dm_out = dm * (half_inner_thickness + AA_SIZE); + ImVec2 dm_in = dm * half_inner_thickness; + temp_points[i2*4+0] = points[i2] + dm_out; + temp_points[i2*4+1] = points[i2] + dm_in; + temp_points[i2*4+2] = points[i2] - dm_in; + temp_points[i2*4+3] = points[i2] - dm_out; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Stroke + const int idx_count = count*6; + const int vtx_count = count*4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + const ImVec2& p1 = points[i1]; + const ImVec2& p2 = points[i2]; + ImVec2 diff = p2 - p1; + diff *= ImInvLength(diff, 1.0f); + + const float dx = diff.x * (thickness * 0.5f); + const float dy = diff.y * (thickness * 0.5f); + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } +} + +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, bool anti_aliased) +{ + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedShapes; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + if (anti_aliased) + { + // Anti-aliased Fill + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & IM_COL32(255,255,255,0); + const int idx_count = (points_count-2)*3 + points_count*6; + const int vtx_count = (points_count*2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); + _IdxWritePtr += 3; + } + + // Compute normals + ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + ImVec2 diff = p1 - p0; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i0].x = diff.y; + temp_normals[i0].y = -diff.x; + } + + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + ImVec2 dm = (n0 + n1) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos = (points[i1] - dm); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos = (points[i1] + dm); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count-2)*3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int amin, int amax) +{ + static ImVec2 circle_vtx[12]; + static bool circle_vtx_builds = false; + const int circle_vtx_count = IM_ARRAYSIZE(circle_vtx); + if (!circle_vtx_builds) + { + for (int i = 0; i < circle_vtx_count; i++) + { + const float a = ((float)i / (float)circle_vtx_count) * 2*IM_PI; + circle_vtx[i].x = cosf(a); + circle_vtx[i].y = sinf(a); + } + circle_vtx_builds = true; + } + + if (amin > amax) return; + if (radius == 0.0f) + { + _Path.push_back(centre); + } + else + { + _Path.reserve(_Path.Size + (amax - amin + 1)); + for (int a = amin; a <= amax; a++) + { + const ImVec2& c = circle_vtx[a % circle_vtx_count]; + _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); + } + } +} + +void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float amin, float amax, int num_segments) +{ + if (radius == 0.0f) + _Path.push_back(centre); + _Path.reserve(_Path.Size + (num_segments + 1)); + for (int i = 0; i <= num_segments; i++) + { + const float a = amin + ((float)i / (float)num_segments) * (amax - amin); + _Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(a) * radius)); + } +} + +static void PathBezierToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); + float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + { + path->push_back(ImVec2(x4, y4)); + } + else if (level < 10) + { + float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; + float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; + float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; + float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; + float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; + float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; + + PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); + PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); + } +} + +void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + // Auto-tessellated + PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, GImGui->Style.CurveTessellationTol, 0); + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + { + float t = t_step * i_step; + float u = 1.0f - t; + float w1 = u*u*u; + float w2 = 3*u*u*t; + float w3 = 3*u*t*t; + float w4 = t*t*t; + _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); + } + } +} + +void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) +{ + float r = rounding; + r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f ) - 1.0f); + r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f ) - 1.0f); + + if (r <= 0.0f || rounding_corners == 0) + { + PathLineTo(a); + PathLineTo(ImVec2(b.x,a.y)); + PathLineTo(b); + PathLineTo(ImVec2(a.x,b.y)); + } + else + { + const float r0 = (rounding_corners & 1) ? r : 0.0f; + const float r1 = (rounding_corners & 2) ? r : 0.0f; + const float r2 = (rounding_corners & 4) ? r : 0.0f; + const float r3 = (rounding_corners & 8) ? r : 0.0f; + PathArcToFast(ImVec2(a.x+r0,a.y+r0), r0, 6, 9); + PathArcToFast(ImVec2(b.x-r1,a.y+r1), r1, 9, 12); + PathArcToFast(ImVec2(b.x-r2,b.y-r2), r2, 0, 3); + PathArcToFast(ImVec2(a.x+r3,b.y-r3), r3, 3, 6); + } +} + +void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + PathLineTo(a + ImVec2(0.5f,0.5f)); + PathLineTo(b + ImVec2(0.5f,0.5f)); + PathStroke(col, false, thickness); +} + +// a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. +void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.5f,0.5f), rounding, rounding_corners_flags); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners_flags) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + if (rounding > 0.0f) + { + PathRect(a, b, rounding, rounding_corners_flags); + PathFillConvex(col); + } + else + { + PrimReserve(6, 4); + PrimRect(a, b, col); + } +} + +void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +{ + if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + PrimReserve(6, 4); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); + PrimWriteVtx(a, uv, col_upr_left); + PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); + PrimWriteVtx(c, uv, col_bot_right); + PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); +} + +void ImDrawList::AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathFillConvex(col); +} + +void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathFillConvex(col); +} + +void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius-0.5f, 0.0f, a_max, num_segments); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius, 0.0f, a_max, num_segments); + PathFillConvex(col); +} + +void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + PathLineTo(pos0); + PathBezierCurveTo(cp0, cp1, pos1, num_segments); + PathStroke(col, false, thickness); +} + +void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + if (text_end == NULL) + text_end = text_begin + strlen(text_begin); + if (text_begin == text_end) + return; + + // IMPORTANT: This is one of the few instance of breaking the encapsulation of ImDrawList, as we pull this from ImGui state, but it is just SO useful. + // Might just move Font/FontSize to ImDrawList? + if (font == NULL) + font = GImGui->Font; + if (font_size == 0.0f) + font_size = GImGui->FontSize; + + IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + + ImVec4 clip_rect = _ClipRectStack.back(); + if (cpu_fine_clip_rect) + { + clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); + clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); + clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); + clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); + } + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL); +} + +void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) +{ + AddText(NULL, 0.0f, pos, col, text_begin, text_end); +} + +void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + // FIXME-OPT: This is wasting draw calls. + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimRectUV(a, b, uv_a, uv_b, col); + + if (push_texture_id) + PopTextureID(); +} + +void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + if ((col & IM_COL32_A_MASK) == 0) + return; + + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); + + if (push_texture_id) + PopTextureID(); +} + +//----------------------------------------------------------------------------- +// ImDrawData +//----------------------------------------------------------------------------- + +// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! +void ImDrawData::DeIndexAllBuffers() +{ + ImVector new_vtx_buffer; + TotalVtxCount = TotalIdxCount = 0; + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + if (cmd_list->IdxBuffer.empty()) + continue; + new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); + for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; + cmd_list->VtxBuffer.swap(new_vtx_buffer); + cmd_list->IdxBuffer.resize(0); + TotalVtxCount += cmd_list->VtxBuffer.Size; + } +} + +// Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2& scale) +{ + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; + cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x, cmd->ClipRect.w * scale.y); + } + } +} + +//----------------------------------------------------------------------------- +// ImFontAtlas +//----------------------------------------------------------------------------- + +ImFontConfig::ImFontConfig() +{ + FontData = NULL; + FontDataSize = 0; + FontDataOwnedByAtlas = true; + FontNo = 0; + SizePixels = 0.0f; + OversampleH = 3; + OversampleV = 1; + PixelSnapH = false; + GlyphExtraSpacing = ImVec2(0.0f, 0.0f); + GlyphOffset = ImVec2(0.0f, 0.0f); + GlyphRanges = NULL; + MergeMode = false; + DstFont = NULL; + memset(Name, 0, sizeof(Name)); +} + +ImFontAtlas::ImFontAtlas() +{ + TexID = NULL; + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; + TexWidth = TexHeight = TexDesiredWidth = 0; + TexUvWhitePixel = ImVec2(0, 0); +} + +ImFontAtlas::~ImFontAtlas() +{ + Clear(); +} + +void ImFontAtlas::ClearInputData() +{ + for (int i = 0; i < ConfigData.Size; i++) + if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) + { + ImGui::MemFree(ConfigData[i].FontData); + ConfigData[i].FontData = NULL; + } + + // When clearing this we lose access to the font name and other information used to build the font. + for (int i = 0; i < Fonts.Size; i++) + if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) + { + Fonts[i]->ConfigData = NULL; + Fonts[i]->ConfigDataCount = 0; + } + ConfigData.clear(); +} + +void ImFontAtlas::ClearTexData() +{ + if (TexPixelsAlpha8) + ImGui::MemFree(TexPixelsAlpha8); + if (TexPixelsRGBA32) + ImGui::MemFree(TexPixelsRGBA32); + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; +} + +void ImFontAtlas::ClearFonts() +{ + for (int i = 0; i < Fonts.Size; i++) + { + Fonts[i]->~ImFont(); + ImGui::MemFree(Fonts[i]); + } + Fonts.clear(); +} + +void ImFontAtlas::Clear() +{ + ClearInputData(); + ClearTexData(); + ClearFonts(); +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Build atlas on demand + if (TexPixelsAlpha8 == NULL) + { + if (ConfigData.empty()) + AddFontDefault(); + Build(); + } + + *out_pixels = TexPixelsAlpha8; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Convert to RGBA32 format on demand + // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp + if (!TexPixelsRGBA32) + { + unsigned char* pixels; + GetTexDataAsAlpha8(&pixels, NULL, NULL); + TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); + const unsigned char* src = pixels; + unsigned int* dst = TexPixelsRGBA32; + for (int n = TexWidth * TexHeight; n > 0; n--) + *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); + } + + *out_pixels = (unsigned char*)TexPixelsRGBA32; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; +} + +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) +{ + IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); + IM_ASSERT(font_cfg->SizePixels > 0.0f); + + // Create new font + if (!font_cfg->MergeMode) + { + ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); + IM_PLACEMENT_NEW(font) ImFont(); + Fonts.push_back(font); + } + else + { + IM_ASSERT(!Fonts.empty()); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font. + } + + ConfigData.push_back(*font_cfg); + ImFontConfig& new_font_cfg = ConfigData.back(); + if (!new_font_cfg.DstFont) + new_font_cfg.DstFont = Fonts.back(); + if (!new_font_cfg.FontDataOwnedByAtlas) + { + new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); + new_font_cfg.FontDataOwnedByAtlas = true; + memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + } + + // Invalidate texture + ClearTexData(); + return new_font_cfg.DstFont; +} + +// Default font TTF is compressed with stb_compress then base85 encoded (see extra_fonts/binary_to_compressed_c.cpp for encoder) +static unsigned int stb_decompress_length(unsigned char *input); +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); +static const char* GetDefaultCompressedFontDataTTFBase85(); +static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } +static void Decode85(const unsigned char* src, unsigned char* dst) +{ + while (*src) + { + unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. + src += 5; + dst += 4; + } +} + +// Load embedded ProggyClean.ttf at size 13, disable oversampling +ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + { + font_cfg.OversampleH = font_cfg.OversampleV = 1; + font_cfg.PixelSnapH = true; + } + if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "ProggyClean.ttf, 13px"); + + const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); + ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, 13.0f, &font_cfg, GetGlyphRangesDefault()); + return font; +} + +ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + int data_size = 0; + void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0); + if (!data) + { + IM_ASSERT(0); // Could not load file. + return NULL; + } + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.Name[0] == '\0') + { + // Store a short copy of filename into into the font name for convenience + const char* p; + for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} + snprintf(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels); + } + return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges); +} + +// NBM Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). +ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontData = ttf_data; + font_cfg.FontDataSize = ttf_size; + font_cfg.SizePixels = size_pixels; + if (glyph_ranges) + font_cfg.GlyphRanges = glyph_ranges; + return AddFont(&font_cfg); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + const unsigned int buf_decompressed_size = stb_decompress_length((unsigned char*)compressed_ttf_data); + unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); + stb_decompress(buf_decompressed_data, (unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); + + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontDataOwnedByAtlas = true; + return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) +{ + int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + void* compressed_ttf = ImGui::MemAlloc((size_t)compressed_ttf_size); + Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); + ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + ImGui::MemFree(compressed_ttf); + return font; +} + +bool ImFontAtlas::Build() +{ + IM_ASSERT(ConfigData.Size > 0); + + TexID = NULL; + TexWidth = TexHeight = 0; + TexUvWhitePixel = ImVec2(0, 0); + ClearTexData(); + + struct ImFontTempBuildData + { + stbtt_fontinfo FontInfo; + stbrp_rect* Rects; + stbtt_pack_range* Ranges; + int RangesCount; + }; + ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)ConfigData.Size * sizeof(ImFontTempBuildData)); + + // Initialize font information early (so we can error without any cleanup) + count glyphs + int total_glyph_count = 0; + int total_glyph_range_count = 0; + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == this)); + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); + IM_ASSERT(font_offset >= 0); + if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) + return false; + + // Count glyphs + if (!cfg.GlyphRanges) + cfg.GlyphRanges = GetGlyphRangesDefault(); + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + total_glyph_count += (in_range[1] - in_range[0]) + 1; + total_glyph_range_count++; + } + } + + // Start packing. We need a known width for the skyline algorithm. Using a cheap heuristic here to decide of width. User can override TexDesiredWidth if they wish. + // After packing is done, width shouldn't matter much, but some API/GPU have texture size limitations and increasing width can decrease height. + TexWidth = (TexDesiredWidth > 0) ? TexDesiredWidth : (total_glyph_count > 4000) ? 4096 : (total_glyph_count > 2000) ? 2048 : (total_glyph_count > 1000) ? 1024 : 512; + TexHeight = 0; + const int max_tex_height = 1024*32; + stbtt_pack_context spc; + stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); + + // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). + ImVector extra_rects; + RenderCustomTexData(0, &extra_rects); + stbtt_PackSetOversampling(&spc, 1, 1); + stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], extra_rects.Size); + for (int i = 0; i < extra_rects.Size; i++) + if (extra_rects[i].was_packed) + TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); + + // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) + int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; + stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); + stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); + stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); + memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); + memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. + memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); + + // First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point) + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + // Setup ranges + int glyph_count = 0; + int glyph_ranges_count = 0; + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + glyph_count += (in_range[1] - in_range[0]) + 1; + glyph_ranges_count++; + } + tmp.Ranges = buf_ranges + buf_ranges_n; + tmp.RangesCount = glyph_ranges_count; + buf_ranges_n += glyph_ranges_count; + for (int i = 0; i < glyph_ranges_count; i++) + { + const ImWchar* in_range = &cfg.GlyphRanges[i * 2]; + stbtt_pack_range& range = tmp.Ranges[i]; + range.font_size = cfg.SizePixels; + range.first_unicode_codepoint_in_range = in_range[0]; + range.num_chars = (in_range[1] - in_range[0]) + 1; + range.chardata_for_range = buf_packedchars + buf_packedchars_n; + buf_packedchars_n += range.num_chars; + } + + // Pack + tmp.Rects = buf_rects + buf_rects_n; + buf_rects_n += glyph_count; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n); + + // Extend texture height + for (int i = 0; i < n; i++) + if (tmp.Rects[i].was_packed) + TexHeight = ImMax(TexHeight, tmp.Rects[i].y + tmp.Rects[i].h); + } + IM_ASSERT(buf_rects_n == total_glyph_count); + IM_ASSERT(buf_packedchars_n == total_glyph_count); + IM_ASSERT(buf_ranges_n == total_glyph_range_count); + + // Create texture + TexHeight = ImUpperPowerOfTwo(TexHeight); + TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); + memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); + spc.pixels = TexPixelsAlpha8; + spc.height = TexHeight; + + // Second pass: render characters + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + tmp.Rects = NULL; + } + + // End packing + stbtt_PackEnd(&spc); + ImGui::MemFree(buf_rects); + buf_rects = NULL; + + // Third pass: setup ImFont and glyphs for runtime + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + ImFont* dst_font = cfg.DstFont; // We can have multiple input fonts writing into a same destination font (when using MergeMode=true) + + float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels); + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + + float ascent = unscaled_ascent * font_scale; + float descent = unscaled_descent * font_scale; + if (!cfg.MergeMode) + { + dst_font->ContainerAtlas = this; + dst_font->ConfigData = &cfg; + dst_font->ConfigDataCount = 0; + dst_font->FontSize = cfg.SizePixels; + dst_font->Ascent = ascent; + dst_font->Descent = descent; + dst_font->Glyphs.resize(0); + dst_font->MetricsTotalSurface = 0; + } + dst_font->ConfigDataCount++; + float off_x = cfg.GlyphOffset.x; + float off_y = cfg.GlyphOffset.y; + + dst_font->FallbackGlyph = NULL; // Always clear fallback so FindGlyph can return NULL. It will be set again in BuildLookupTable() + for (int i = 0; i < tmp.RangesCount; i++) + { + stbtt_pack_range& range = tmp.Ranges[i]; + for (int char_idx = 0; char_idx < range.num_chars; char_idx += 1) + { + const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; + if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) + continue; + + const int codepoint = range.first_unicode_codepoint_in_range + char_idx; + if (cfg.MergeMode && dst_font->FindGlyph((unsigned short)codepoint)) + continue; + + stbtt_aligned_quad q; + float dummy_x = 0.0f, dummy_y = 0.0f; + stbtt_GetPackedQuad(range.chardata_for_range, TexWidth, TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0); + + dst_font->Glyphs.resize(dst_font->Glyphs.Size + 1); + ImFont::Glyph& glyph = dst_font->Glyphs.back(); + glyph.Codepoint = (ImWchar)codepoint; + glyph.X0 = q.x0 + off_x; glyph.Y0 = q.y0 + off_y; glyph.X1 = q.x1 + off_x; glyph.Y1 = q.y1 + off_y; + glyph.U0 = q.s0; glyph.V0 = q.t0; glyph.U1 = q.s1; glyph.V1 = q.t1; + glyph.Y0 += (float)(int)(dst_font->Ascent + 0.5f); + glyph.Y1 += (float)(int)(dst_font->Ascent + 0.5f); + glyph.XAdvance = (pc.xadvance + cfg.GlyphExtraSpacing.x); // Bake spacing into XAdvance + if (cfg.PixelSnapH) + glyph.XAdvance = (float)(int)(glyph.XAdvance + 0.5f); + dst_font->MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * TexWidth + 1.99f) * (int)((glyph.V1 - glyph.V0) * TexHeight + 1.99f); // +1 to account for average padding, +0.99 to round + } + } + cfg.DstFont->BuildLookupTable(); + } + + // Cleanup temporaries + ImGui::MemFree(buf_packedchars); + ImGui::MemFree(buf_ranges); + ImGui::MemFree(tmp_array); + + // Render into our custom data block + RenderCustomTexData(1, &extra_rects); + + return true; +} + +void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) +{ + // A work of art lies ahead! (. = white layer, X = black layer, others are blank) + // The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. + const int TEX_DATA_W = 90; + const int TEX_DATA_H = 27; + const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = + { + "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" + "..- -X.....X- X.X - X.X -X.....X - X.....X" + "--- -XXX.XXX- X...X - X...X -X....X - X....X" + "X - X.X - X.....X - X.....X -X...X - X...X" + "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" + "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" + "X..X - X.X - X.X - X.X -XX X.X - X.X XX" + "X...X - X.X - X.X - XX X.X XX - X.X - X.X " + "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " + "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " + "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " + "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " + "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " + "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " + "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " + "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " + "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " + "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" + "X.X X..X - -X.......X- X.......X - XX XX - " + "XX X..X - - X.....X - X.....X - X.X X.X - " + " X..X - X...X - X...X - X..X X..X - " + " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " + "------------ - X - X -X.....................X- " + " ----------------------------------- X...XXXXXXXXXXXXX...X - " + " - X..X X..X - " + " - X.X X.X - " + " - XX XX - " + }; + + ImVector& rects = *(ImVector*)p_rects; + if (pass == 0) + { + // Request rectangles + stbrp_rect r; + memset(&r, 0, sizeof(r)); + r.w = (TEX_DATA_W*2)+1; + r.h = TEX_DATA_H+1; + rects.push_back(r); + } + else if (pass == 1) + { + // Render/copy pixels + const stbrp_rect& r = rects[0]; + for (int y = 0, n = 0; y < TEX_DATA_H; y++) + for (int x = 0; x < TEX_DATA_W; x++, n++) + { + const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; + const int offset1 = offset0 + 1 + TEX_DATA_W; + TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; + TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; + } + const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); + TexUvWhitePixel = ImVec2((r.x + 0.5f) * tex_uv_scale.x, (r.y + 0.5f) * tex_uv_scale.y); + + // Setup mouse cursors + const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = + { + // Pos ........ Size ......... Offset ...... + { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow + { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput + { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move + { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS + { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW + { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW + { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE + }; + + for (int type = 0; type < ImGuiMouseCursor_Count_; type++) + { + ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; + ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); + const ImVec2 size = cursor_datas[type][1]; + cursor_data.Type = type; + cursor_data.Size = size; + cursor_data.HotOffset = cursor_datas[type][2]; + cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; + pos.x += TEX_DATA_W+1; + cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; + } + } +} + +// Retrieve list of range (2 int per range, values are inclusive) +const ImWchar* ImFontAtlas::GetGlyphRangesDefault() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesKorean() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3131, 0x3163, // Korean alphabets + 0xAC00, 0xD79D, // Korean characters + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesChinese() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0x4e00, 0x9FAF, // CJK Ideograms + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() +{ + // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. + // This encoding helps us reduce the source code size. + static const short offsets_from_0x4E00[] = + { + -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, + 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, + 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, + 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, + 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, + 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, + 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, + 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, + 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, + 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, + 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, + 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, + 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, + 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, + 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, + 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, + 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, + 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, + 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, + 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, + 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, + 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, + 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, + 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, + 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, + 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, + 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, + 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, + 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, + 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, + 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, + 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, + }; + static ImWchar base_ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + }; + static bool full_ranges_unpacked = false; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1]; + if (!full_ranges_unpacked) + { + // Unpack + int codepoint = 0x4e00; + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + ImWchar* dst = full_ranges + IM_ARRAYSIZE(base_ranges);; + for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) + dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); + dst[0] = 0; + full_ranges_unpacked = true; + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement + 0x2DE0, 0x2DFF, // Cyrillic Extended-A + 0xA640, 0xA69F, // Cyrillic Extended-B + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesThai() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + 0x0E00, 0x0E7F, // Thai + 0, + }; + return &ranges[0]; +} + +//----------------------------------------------------------------------------- +// ImFont +//----------------------------------------------------------------------------- + +ImFont::ImFont() +{ + Scale = 1.0f; + FallbackChar = (ImWchar)'?'; + Clear(); +} + +ImFont::~ImFont() +{ + // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. + // If you want to delete fonts you need to do it between Render() and NewFrame(). + // FIXME-CLEANUP + /* + ImGuiContext& g = *GImGui; + if (g.Font == this) + g.Font = NULL; + */ + Clear(); +} + +void ImFont::Clear() +{ + FontSize = 0.0f; + DisplayOffset = ImVec2(0.0f, 1.0f); + Glyphs.clear(); + IndexXAdvance.clear(); + IndexLookup.clear(); + FallbackGlyph = NULL; + FallbackXAdvance = 0.0f; + ConfigDataCount = 0; + ConfigData = NULL; + ContainerAtlas = NULL; + Ascent = Descent = 0.0f; + MetricsTotalSurface = 0; +} + +void ImFont::BuildLookupTable() +{ + int max_codepoint = 0; + for (int i = 0; i != Glyphs.Size; i++) + max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); + + IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved + IndexXAdvance.clear(); + IndexLookup.clear(); + GrowIndex(max_codepoint + 1); + for (int i = 0; i < Glyphs.Size; i++) + { + int codepoint = (int)Glyphs[i].Codepoint; + IndexXAdvance[codepoint] = Glyphs[i].XAdvance; + IndexLookup[codepoint] = (unsigned short)i; + } + + // Create a glyph to handle TAB + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (FindGlyph((unsigned short)' ')) + { + if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times + Glyphs.resize(Glyphs.Size + 1); + ImFont::Glyph& tab_glyph = Glyphs.back(); + tab_glyph = *FindGlyph((unsigned short)' '); + tab_glyph.Codepoint = '\t'; + tab_glyph.XAdvance *= 4; + IndexXAdvance[(int)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; + IndexLookup[(int)tab_glyph.Codepoint] = (unsigned short)(Glyphs.Size-1); + } + + FallbackGlyph = NULL; + FallbackGlyph = FindGlyph(FallbackChar); + FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; + for (int i = 0; i < max_codepoint + 1; i++) + if (IndexXAdvance[i] < 0.0f) + IndexXAdvance[i] = FallbackXAdvance; +} + +void ImFont::SetFallbackChar(ImWchar c) +{ + FallbackChar = c; + BuildLookupTable(); +} + +void ImFont::GrowIndex(int new_size) +{ + IM_ASSERT(IndexXAdvance.Size == IndexLookup.Size); + int old_size = IndexLookup.Size; + if (new_size <= old_size) + return; + IndexXAdvance.resize(new_size); + IndexLookup.resize(new_size); + for (int i = old_size; i < new_size; i++) + { + IndexXAdvance[i] = -1.0f; + IndexLookup[i] = (unsigned short)-1; + } +} + +void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +{ + IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. + int index_size = IndexLookup.Size; + + if (dst < index_size && IndexLookup.Data[dst] == (unsigned short)-1 && !overwrite_dst) // 'dst' already exists + return; + if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op + return; + + GrowIndex(dst + 1); + IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (unsigned short)-1; + IndexXAdvance[dst] = (src < index_size) ? IndexXAdvance.Data[src] : 1.0f; +} + +const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const +{ + if (c < IndexLookup.Size) + { + const unsigned short i = IndexLookup[c]; + if (i != (unsigned short)-1) + return &Glyphs.Data[i]; + } + return FallbackGlyph; +} + +const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const +{ + // Simple word-wrapping for English, not full-featured. Please submit failing cases! + // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) + + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // List of hardcoded separators: .,;!?'" + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" --> "Hello" "World" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + float line_width = 0.0f; + float word_width = 0.0f; + float blank_width = 0.0f; + + const char* word_end = text; + const char* prev_word_end = NULL; + bool inside_word = true; + + const char* s = text; + while (s < text_end) + { + unsigned int c = (unsigned int)*s; + const char* next_s; + if (c < 0x80) + next_s = s + 1; + else + next_s = s + ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + + if (c < 32) + { + if (c == '\n') + { + line_width = word_width = blank_width = 0.0f; + inside_word = true; + s = next_s; + continue; + } + if (c == '\r') + { + s = next_s; + continue; + } + } + + const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; + if (ImCharIsSpace(c)) + { + if (inside_word) + { + line_width += blank_width; + blank_width = 0.0f; + word_end = s; + } + blank_width += char_width; + inside_word = false; + } + else + { + word_width += char_width; + if (inside_word) + { + word_end = next_s; + } + else + { + prev_word_end = word_end; + line_width += word_width + blank_width; + word_width = blank_width = 0.0f; + } + + // Allow wrapping after punctuation. + inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); + } + + // We ignore blank width at the end of the line (they can be skipped) + if (line_width + word_width >= wrap_width) + { + // Words that cannot possibly fit within an entire line will be cut anywhere. + if (word_width < wrap_width) + s = prev_word_end ? prev_word_end : word_end; + break; + } + + s = next_s; + } + + return s; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + + const float line_height = size; + const float scale = size / FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const char* s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + const char* prev_s = s; + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + continue; + } + if (c == '\r') + continue; + } + + const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; + if (line_width + char_width >= max_width) + { + s = prev_s; + break; + } + + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (line_width > 0 || text_size.y == 0.0f) + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const +{ + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded. + return; + if (const Glyph* glyph = FindGlyph(c)) + { + float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + ImVec2 pos_tl(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale); + ImVec2 pos_br(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale); + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(pos_tl, pos_br, ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); + } +} + +void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // ImGui functions generally already provides a valid text_end, so this is merely to handle direct calls. + + // Align to be pixel perfect + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + float x = pos.x; + float y = pos.y; + if (y > clip_rect.w) + return; + + const float scale = size / FontSize; + const float line_height = FontSize * scale; + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + // Skip non-visible lines + const char* s = text_begin; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + + // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int vtx_count_max = (int)(text_end - s) * 4; + const int idx_count_max = (int)(text_end - s) * 6; + const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; + + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + x = pos.x; + y += line_height; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) // Malformed UTF-8? + break; + } + + if (c < 32) + { + if (c == '\n') + { + x = pos.x; + y += line_height; + + if (y > clip_rect.w) + break; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + continue; + } + if (c == '\r') + continue; + } + + float char_width = 0.0f; + if (const Glyph* glyph = FindGlyph((unsigned short)c)) + { + char_width = glyph->XAdvance * scale; + + // Arbitrarily assume that both space and tabs are empty glyphs as an optimization + if (c != ' ' && c != '\t') + { + // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip) + { + if (x1 < clip_rect.x) + { + u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); + x1 = clip_rect.x; + } + if (y1 < clip_rect.y) + { + v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); + y1 = clip_rect.y; + } + if (x2 > clip_rect.z) + { + u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); + x2 = clip_rect.z; + } + if (y2 > clip_rect.w) + { + v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); + y2 = clip_rect.w; + } + if (y1 >= y2) + { + x += char_width; + continue; + } + } + + // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: + { + idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); + idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); + vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; + vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; + vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; + vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; + vtx_write += 4; + vtx_current_idx += 4; + idx_write += 6; + } + } + } + } + + x += char_width; + } + + // Give back unused vertices + draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); + draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->_VtxWritePtr = vtx_write; + draw_list->_IdxWritePtr = idx_write; + draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size; +} + +//----------------------------------------------------------------------------- +// DEFAULT FONT DATA +//----------------------------------------------------------------------------- +// Compressed with stb_compress() then converted to a C array. +// Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file. +// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h +//----------------------------------------------------------------------------- + +static unsigned int stb_decompress_length(unsigned char *input) +{ + return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; +} + +static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; +static unsigned char *stb__dout; +static void stb__match(unsigned char *data, unsigned int length) +{ + // INVERSE of memmove... write each byte before copying the next... + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } + while (length--) *stb__dout++ = *data++; +} + +static void stb__lit(unsigned char *data, unsigned int length) +{ + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } + memcpy(stb__dout, data, length); + stb__dout += length; +} + +#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) +#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) +#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) + +static unsigned char *stb_decompress_token(unsigned char *i) +{ + if (*i >= 0x20) { // use fewer if's for cases that expand small + if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; + else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; + else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); + } else { // more ifs for cases that expand large, since overhead is amortized + if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; + else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; + else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); + else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); + else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; + else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; + } + return i; +} + +static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) +{ + const unsigned long ADLER_MOD = 65521; + unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; + unsigned long blocklen, i; + + blocklen = buflen % 5552; + while (buflen) { + for (i=0; i + 7 < blocklen; i += 8) { + s1 += buffer[0], s2 += s1; + s1 += buffer[1], s2 += s1; + s1 += buffer[2], s2 += s1; + s1 += buffer[3], s2 += s1; + s1 += buffer[4], s2 += s1; + s1 += buffer[5], s2 += s1; + s1 += buffer[6], s2 += s1; + s1 += buffer[7], s2 += s1; + + buffer += 8; + } + + for (; i < blocklen; ++i) + s1 += *buffer++, s2 += s1; + + s1 %= ADLER_MOD, s2 %= ADLER_MOD; + buflen -= blocklen; + blocklen = 5552; + } + return (unsigned int)(s2 << 16) + (unsigned int)s1; +} + +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) +{ + unsigned int olen; + if (stb__in4(0) != 0x57bC0000) return 0; + if (stb__in4(4) != 0) return 0; // error! stream is > 4GB + olen = stb_decompress_length(i); + stb__barrier2 = i; + stb__barrier3 = i+length; + stb__barrier = output + olen; + stb__barrier4 = output; + i += 16; + + stb__dout = output; + for (;;) { + unsigned char *old_i = i; + i = stb_decompress_token(i); + if (i == old_i) { + if (*i == 0x05 && i[1] == 0xfa) { + IM_ASSERT(stb__dout == output + olen); + if (stb__dout != output + olen) return 0; + if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) + return 0; + return olen; + } else { + IM_ASSERT(0); /* NOTREACHED */ + return 0; + } + } + IM_ASSERT(stb__dout <= output + olen); + if (stb__dout > output + olen) + return 0; + } +} + +//----------------------------------------------------------------------------- +// ProggyClean.ttf +// Copyright (c) 2004, 2005 Tristan Grimmer +// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) +// Download and more information at http://upperbounds.net +//----------------------------------------------------------------------------- +// File: 'ProggyClean.ttf' (41208 bytes) +// Exported using binary_to_compressed_c.cpp +//----------------------------------------------------------------------------- +static const char proggy_clean_ttf_compressed_data_base85[11980+1] = + "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" + "2*>]b(MC;$jPfY.;h^`IWM9Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1=Ke$$'5F%)]0^#0X@U.a$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;--VsM.M0rJfLH2eTM`*oJMHRC`N" + "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa&VZ>1i%h1S9u5o@YaaW$e+bROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." + "x]Ip.PH^'/aqUO/$1WxLoW0[iLAw=4h(9.`G" + "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?Ggv:[7MI2k).'2($5FNP&EQ(,)" + "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" + "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" + "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" + "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" + "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[Ket`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" + "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" + "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$MhLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" + "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" + "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" + "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VBpqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<-+k?'(^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" + "D?@f&1'BW-)Ju#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" + "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" + "bIu)'Z,*[>br5fX^:FPAWr-m2KgLQ_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" + "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aege0jT6'N#(q%.O=?2S]u*(m<-" + "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" + "sZ88+dKQ)W6>J%CL`.d*(B`-n8D9oK-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P r+$%CE=68>K8r0=dSC%%(@p7" + ".m7jilQ02'0-VWAgTlGW'b)Tq7VT9q^*^$$.:&N@@" + "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" + "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" + "@-W$U%VEQ/,,>>#)D#%8cY#YZ?=,`Wdxu/ae&#" + "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$so8lKN%5/$(vdfq7+ebA#" + "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" + "6e%B/:=>)N4xeW.*wft-;$'58-ESqr#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" + "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjLV#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#SfD07&6D@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5" + "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" + "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" + "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmLq9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" + "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3$U4O]GKx'm9)b@p7YsvK3w^YR-" + "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" + "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdFTi1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IXSsDiWP,##P`%/L-" + "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdFl*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" + "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#$(>.Z-I&J(Q0Hd5Q%7Co-b`-cP)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8WlA2);Sa" + ">gXm8YB`1d@K#n]76-a$U,mF%Ul:#/'xoFM9QX-$.QN'>" + "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" + "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-uW%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" + "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" + "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" + "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*'IAO" + "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" + ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T" + "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" + "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" + "/QHC#3^ZC#7jmC#;v)D#?,)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" + "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" + "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; + +static const char* GetDefaultCompressedFontDataTTFBase85() +{ + return proggy_clean_ttf_compressed_data_base85; +} diff --git a/src/imgui/imgui_impl_sdl.cpp b/src/imgui/imgui_impl_sdl.cpp new file mode 100644 index 00000000..f0758bda --- /dev/null +++ b/src/imgui/imgui_impl_sdl.cpp @@ -0,0 +1,283 @@ +// ImGui SDL2 binding with OpenGL +// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. + +// If your context or own usage of OpenGL involve anything GL3/GL4, prefer using the code in sdl_opengl3_example. +// If you are not sure what that means, prefer using the code in sdl_opengl3_example. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). +// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +#include +#include +#include +#include +#include "imgui_impl_sdl.h" + +// Data +static double g_Time = 0.0f; +static bool g_MousePressed[3] = { false, false, false }; +static float g_MouseWheel = 0.0f; +static GLuint g_FontTexture = 0; + +// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) +// If text or lines are blurry when integrating ImGui in your engine: +// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) +void ImGui_ImplSdl_RenderDrawLists(ImDrawData* draw_data) +{ + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + ImGuiIO& io = ImGui::GetIO(); + int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); + int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); + if (fb_width == 0 || fb_height == 0) + return; + draw_data->ScaleClipRects(io.DisplayFramebufferScale); + + // We are using the OpenGL fixed pipeline to make the example code simpler to read! + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers. + GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); + GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); + glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glEnable(GL_SCISSOR_TEST); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); + glEnable(GL_TEXTURE_2D); + //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context + + // Setup viewport, orthographic projection matrix + glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f); + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + // Render command lists + #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; + const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; + glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, pos))); + glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, uv))); + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + OFFSETOF(ImDrawVert, col))); + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); + glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); + glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer); + } + idx_buffer += pcmd->ElemCount; + } + } + #undef OFFSETOF + + // Restore modified state + glDisableClientState(GL_COLOR_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); + glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture); + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + glPopAttrib(); + glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); + glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); +} + +static const char* ImGui_ImplSdl_GetClipboardText(void*) +{ + return SDL_GetClipboardText(); +} + +static void ImGui_ImplSdl_SetClipboardText(void*, const char* text) +{ + SDL_SetClipboardText(text); +} + +bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event) +{ + ImGuiIO& io = ImGui::GetIO(); + switch (event->type) + { + case SDL_MOUSEWHEEL: + { + if (event->wheel.y > 0) + g_MouseWheel = 1; + if (event->wheel.y < 0) + g_MouseWheel = -1; + return true; + } + case SDL_MOUSEBUTTONDOWN: + { + if (event->button.button == SDL_BUTTON_LEFT) g_MousePressed[0] = true; + if (event->button.button == SDL_BUTTON_RIGHT) g_MousePressed[1] = true; + if (event->button.button == SDL_BUTTON_MIDDLE) g_MousePressed[2] = true; + return true; + } + case SDL_TEXTINPUT: + { + io.AddInputCharactersUTF8(event->text.text); + return true; + } + case SDL_KEYDOWN: + case SDL_KEYUP: + { + int key = event->key.keysym.sym & ~SDLK_SCANCODE_MASK; + io.KeysDown[key] = (event->type == SDL_KEYDOWN); + io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0); + io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0); + io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0); + io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0); + return true; + } + } + return false; +} + +bool ImGui_ImplSdl_CreateDeviceObjects() +{ + // Build texture atlas + ImGuiIO& io = ImGui::GetIO(); + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height); + + // Upload texture to graphics system + GLint last_texture; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + glGenTextures(1, &g_FontTexture); + glBindTexture(GL_TEXTURE_2D, g_FontTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels); + + // Store our identifier + io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; + + // Restore state + glBindTexture(GL_TEXTURE_2D, last_texture); + + return true; +} + +void ImGui_ImplSdl_InvalidateDeviceObjects() +{ + if (g_FontTexture) + { + glDeleteTextures(1, &g_FontTexture); + ImGui::GetIO().Fonts->TexID = 0; + g_FontTexture = 0; + } +} + +bool ImGui_ImplSdl_Init(SDL_Window* window) +{ + ImGuiIO& io = ImGui::GetIO(); + io.KeyMap[ImGuiKey_Tab] = SDLK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. + io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT; + io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT; + io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP; + io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN; + io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP; + io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN; + io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME; + io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END; + io.KeyMap[ImGuiKey_Delete] = SDLK_DELETE; + io.KeyMap[ImGuiKey_Backspace] = SDLK_BACKSPACE; + io.KeyMap[ImGuiKey_Enter] = SDLK_RETURN; + io.KeyMap[ImGuiKey_Escape] = SDLK_ESCAPE; + io.KeyMap[ImGuiKey_A] = SDLK_a; + io.KeyMap[ImGuiKey_C] = SDLK_c; + io.KeyMap[ImGuiKey_V] = SDLK_v; + io.KeyMap[ImGuiKey_X] = SDLK_x; + io.KeyMap[ImGuiKey_Y] = SDLK_y; + io.KeyMap[ImGuiKey_Z] = SDLK_z; + + io.RenderDrawListsFn = ImGui_ImplSdl_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer. + io.SetClipboardTextFn = ImGui_ImplSdl_SetClipboardText; + io.GetClipboardTextFn = ImGui_ImplSdl_GetClipboardText; + io.ClipboardUserData = NULL; + +#ifdef _WIN32 + SDL_SysWMinfo wmInfo; + SDL_VERSION(&wmInfo.version); + SDL_GetWindowWMInfo(window, &wmInfo); + io.ImeWindowHandle = wmInfo.info.win.window; +#else + (void)window; +#endif + + return true; +} + +void ImGui_ImplSdl_Shutdown() +{ + ImGui_ImplSdl_InvalidateDeviceObjects(); + ImGui::Shutdown(); +} + +void ImGui_ImplSdl_NewFrame(SDL_Window *window) +{ + if (!g_FontTexture) + ImGui_ImplSdl_CreateDeviceObjects(); + + ImGuiIO& io = ImGui::GetIO(); + + // Setup display size (every frame to accommodate for window resizing) + int w, h; + int display_w, display_h; + SDL_GetWindowSize(window, &w, &h); + SDL_GL_GetDrawableSize(window, &display_w, &display_h); + io.DisplaySize = ImVec2((float)w, (float)h); + io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); + + // Setup time step + Uint32 time = SDL_GetTicks(); + double current_time = time / 1000.0; + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + g_Time = current_time; + + // Setup inputs + // (we already got mouse wheel, keyboard keys & characters from SDL_PollEvent()) + int mx, my; + Uint32 mouseMask = SDL_GetMouseState(&mx, &my); + if (SDL_GetWindowFlags(window) & SDL_WINDOW_MOUSE_FOCUS) + io.MousePos = ImVec2((float)mx, (float)my); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) + else + io.MousePos = ImVec2(-1,-1); + + io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; // 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. + io.MouseDown[1] = g_MousePressed[1] || (mouseMask & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; + io.MouseDown[2] = g_MousePressed[2] || (mouseMask & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0; + g_MousePressed[0] = g_MousePressed[1] = g_MousePressed[2] = false; + + io.MouseWheel = g_MouseWheel; + g_MouseWheel = 0.0f; + + // Hide OS mouse cursor if ImGui is drawing it + SDL_ShowCursor(io.MouseDrawCursor ? 0 : 1); + + // Start the frame + ImGui::NewFrame(); +} diff --git a/src/imgui/imgui_impl_sdl.h b/src/imgui/imgui_impl_sdl.h new file mode 100644 index 00000000..a322bf2d --- /dev/null +++ b/src/imgui/imgui_impl_sdl.h @@ -0,0 +1,19 @@ +// ImGui SDL2 binding with OpenGL +// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). +// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +struct SDL_Window; +typedef union SDL_Event SDL_Event; + +IMGUI_API bool ImGui_ImplSdl_Init(SDL_Window* window); +IMGUI_API void ImGui_ImplSdl_Shutdown(); +IMGUI_API void ImGui_ImplSdl_NewFrame(SDL_Window* window); +IMGUI_API bool ImGui_ImplSdl_ProcessEvent(SDL_Event* event); + +// Use if you want to reset your rendering device without losing ImGui state. +IMGUI_API void ImGui_ImplSdl_InvalidateDeviceObjects(); +IMGUI_API bool ImGui_ImplSdl_CreateDeviceObjects(); diff --git a/src/imgui/imgui_internal.h b/src/imgui/imgui_internal.h new file mode 100644 index 00000000..9a5e147d --- /dev/null +++ b/src/imgui/imgui_internal.h @@ -0,0 +1,776 @@ +// dear imgui, v1.51 WIP +// (internals) + +// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! +// Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) +// #define IMGUI_DEFINE_MATH_OPERATORS + +#pragma once + +#ifndef IMGUI_VERSION +#error Must include imgui.h before imgui_internal.h +#endif + +#include // FILE* +#include // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + +//----------------------------------------------------------------------------- +// Forward Declarations +//----------------------------------------------------------------------------- + +struct ImRect; +struct ImGuiColMod; +struct ImGuiStyleMod; +struct ImGuiGroupData; +struct ImGuiSimpleColumns; +struct ImGuiDrawContext; +struct ImGuiTextEditState; +struct ImGuiIniData; +struct ImGuiMouseCursorData; +struct ImGuiPopupRef; +struct ImGuiWindow; + +typedef int ImGuiLayoutType; // enum ImGuiLayoutType_ +typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_ +typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_ +typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_ + +//------------------------------------------------------------------------- +// STB libraries +//------------------------------------------------------------------------- + +namespace ImGuiStb +{ + +#undef STB_TEXTEDIT_STRING +#undef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_STRING ImGuiTextEditState +#define STB_TEXTEDIT_CHARTYPE ImWchar +#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f +#include "stb_textedit.h" + +} // namespace ImGuiStb + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +#ifndef GImGui +extern IMGUI_API ImGuiContext* GImGui; // Current implicit ImGui context pointer +#endif + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_PI 3.14159265358979323846f +#define IM_OFFSETOF(_TYPE,_ELM) ((size_t)&(((_TYPE*)0)->_ELM)) + +// Helpers: UTF-8 <> wchar +IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count +IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count +IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count +IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) +IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points + +// Helpers: Misc +IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings +IMGUI_API void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0); +IMGUI_API FILE* ImFileOpen(const char* filename, const char* file_open_mode); +IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c); +static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } +static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } + +// Helpers: String +IMGUI_API int ImStricmp(const char* str1, const char* str2); +IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count); +IMGUI_API char* ImStrdup(const char* str); +IMGUI_API int ImStrlenW(const ImWchar* str); +IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line +IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); +IMGUI_API int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3); +IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args); + +// Helpers: Math +// We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined) +#ifdef IMGUI_DEFINE_MATH_OPERATORS +static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } +static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } +static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } +static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } +static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } +static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); } +#endif + +static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } +static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } +static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } +static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } +static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } +static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } +static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } +static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } +static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } +static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } +static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } +static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / sqrtf(d); return fail_value; } +static inline float ImFloor(float f) { return (float)(int)f; } +static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } + +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a dummy parameter allows us to bypass including which on some platforms complains when user has disabled exceptions. +#ifdef IMGUI_DEFINE_PLACEMENT_NEW +struct ImPlacementNewDummy {}; +inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; } +inline void operator delete(void*, ImPlacementNewDummy, void*) {} +#define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR) +#endif + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat + ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set) + ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release) + ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release) + ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping + ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press + ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction + ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only + ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held + ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable +}; + +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_Vertical = 1 << 0 +}; + +enum ImGuiSelectableFlagsPrivate_ +{ + // NB: need to be in sync with last value of ImGuiSelectableFlags_ + ImGuiSelectableFlags_Menu = 1 << 3, + ImGuiSelectableFlags_MenuItem = 1 << 4, + ImGuiSelectableFlags_Disabled = 1 << 5, + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6 +}; + +// FIXME: this is in development, not exposed/functional as a generic feature yet. +enum ImGuiLayoutType_ +{ + ImGuiLayoutType_Vertical, + ImGuiLayoutType_Horizontal +}; + +enum ImGuiPlotType +{ + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram +}; + +enum ImGuiDataType +{ + ImGuiDataType_Int, + ImGuiDataType_Float, + ImGuiDataType_Float2, +}; + +enum ImGuiCorner +{ + ImGuiCorner_TopLeft = 1 << 0, // 1 + ImGuiCorner_TopRight = 1 << 1, // 2 + ImGuiCorner_BottomRight = 1 << 2, // 4 + ImGuiCorner_BottomLeft = 1 << 3, // 8 + ImGuiCorner_All = 0x0F +}; + +// 2D axis aligned bounding-box +// NB: we can't rely on ImVec2 math operators being available here +struct IMGUI_API ImRect +{ + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right + + ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {} + ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} + ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} + ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} + + ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); } + float GetWidth() const { return Max.x-Min.x; } + float GetHeight() const { return Max.y-Min.y; } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; } + void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; } + void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; } + void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; } + ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const + { + if (!on_edge && Contains(p)) + return p; + if (p.x > Max.x) p.x = Max.x; + else if (p.x < Min.x) p.x = Min.x; + if (p.y > Max.y) p.y = Max.y; + else if (p.y < Min.y) p.y = Min.y; + return p; + } +}; + +// Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; + +// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; + ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } +}; + +// Stacked data for BeginGroup()/EndGroup() +struct ImGuiGroupData +{ + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + float BackupIndentX; + float BackupGroupOffsetX; + float BackupCurrentLineHeight; + float BackupCurrentLineTextBaseOffset; + float BackupLogLinePosY; + bool BackupActiveIdIsAlive; + bool AdvanceCursor; +}; + +// Per column data for Columns() +struct ImGuiColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + //float IndentX; +}; + +// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper. +struct IMGUI_API ImGuiSimpleColumns +{ + int Count; + float Spacing; + float Width, NextWidth; + float Pos[8], NextWidths[8]; + + ImGuiSimpleColumns(); + void Update(int count, float spacing, bool clear); + float DeclColumns(float w0, float w1, float w2); + float CalcExtraSpace(float avail_w); +}; + +// Internal state of the currently focused/edited text input box +struct IMGUI_API ImGuiTextEditState +{ + ImGuiID Id; // widget id owning the text state + ImVector Text; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. + ImVector InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) + ImVector TempTextBuffer; + int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. + int BufSizeA; // end-user buffer size + float ScrollX; + ImGuiStb::STB_TexteditState StbState; + float CursorAnim; + bool CursorFollow; + bool SelectedAllMouseLock; + + ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } + void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking + void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); } + bool HasSelection() const { return StbState.select_start != StbState.select_end; } + void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; } + void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } + void OnKeyPressed(int key); +}; + +// Data saved in imgui.ini file +struct ImGuiIniData +{ + char* Name; + ImGuiID Id; + ImVec2 Pos; + ImVec2 Size; + bool Collapsed; +}; + +// Mouse cursor data (used when io.MouseDrawCursor is set) +struct ImGuiMouseCursorData +{ + ImGuiMouseCursor Type; + ImVec2 HotOffset; + ImVec2 Size; + ImVec2 TexUvMin[2]; + ImVec2 TexUvMax[2]; +}; + +// Storage for current popup stack +struct ImGuiPopupRef +{ + ImGuiID PopupId; // Set on OpenPopup() + ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + ImGuiWindow* ParentWindow; // Set on OpenPopup() + ImGuiID ParentMenuSet; // Set on OpenPopup() + ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup + + ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupId = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; } +}; + +// Main state for ImGui +struct ImGuiContext +{ + bool Initialized; + ImGuiIO IO; + ImGuiStyle Style; + ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() + float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() + float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. + ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel + + float Time; + int FrameCount; + int FrameCountEnded; + int FrameCountRendered; + ImVector Windows; + ImVector WindowsSortBuffer; + ImGuiWindow* CurrentWindow; // Being drawn into + ImVector CurrentWindowStack; + ImGuiWindow* FocusedWindow; // Will catch keyboard inputs + ImGuiWindow* HoveredWindow; // Will catch mouse inputs + ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiID HoveredId; // Hovered widget + bool HoveredIdAllowOverlap; + ImGuiID HoveredIdPreviousFrame; + ImGuiID ActiveId; // Active widget + ImGuiID ActiveIdPreviousFrame; + bool ActiveIdIsAlive; + bool ActiveIdIsJustActivated; // Set at the time of activation for one frame + bool ActiveIdAllowOverlap; // Set only by active widget + ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) + ImGuiWindow* ActiveIdWindow; + ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. + ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId + ImVector Settings; // .ini Settings + float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero + ImVector ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() + ImVector StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() + ImVector FontStack; // Stack for PushFont()/PopFont() + ImVector OpenPopupStack; // Which popups are open (persistent) + ImVector CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame) + + // Storage for SetNexWindow** and SetNextTreeNode*** functions + ImVec2 SetNextWindowPosVal; + ImVec2 SetNextWindowSizeVal; + ImVec2 SetNextWindowContentSizeVal; + bool SetNextWindowCollapsedVal; + ImGuiSetCond SetNextWindowPosCond; + ImGuiSetCond SetNextWindowSizeCond; + ImGuiSetCond SetNextWindowContentSizeCond; + ImGuiSetCond SetNextWindowCollapsedCond; + ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true + ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback; + void* SetNextWindowSizeConstraintCallbackUserData; + bool SetNextWindowSizeConstraint; + bool SetNextWindowFocus; + bool SetNextTreeNodeOpenVal; + ImGuiSetCond SetNextTreeNodeOpenCond; + + // Render + ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user + ImVector RenderDrawLists[3]; + float ModalWindowDarkeningRatio; + ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays + ImGuiMouseCursor MouseCursor; + ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_]; + + // Widget state + ImGuiTextEditState InputTextState; + ImFont InputTextPasswordFont; + ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. + ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode + float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings + ImVec2 DragLastMouseDelta; + float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio + float DragSpeedScaleSlow; + float DragSpeedScaleFast; + ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? + int TooltipOverrideCount; + char* PrivateClipboard; // If no custom clipboard handler is defined + ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor + + // Logging + bool LogEnabled; + FILE* LogFile; // If != NULL log to stdout/ file + ImGuiTextBuffer* LogClipboard; // Else log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + int LogStartDepth; + int LogAutoExpandMaxDepth; + + // Misc + float FramerateSecPerFrame[120]; // calculate estimate of framerate for user + int FramerateSecPerFrameIdx; + float FramerateSecPerFrameAccum; + int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags + int CaptureKeyboardNextFrame; + char TempBuffer[1024*3+1]; // temporary text buffer + + ImGuiContext() + { + Initialized = false; + Font = NULL; + FontSize = FontBaseSize = 0.0f; + FontTexUvWhitePixel = ImVec2(0.0f, 0.0f); + + Time = 0.0f; + FrameCount = 0; + FrameCountEnded = FrameCountRendered = -1; + CurrentWindow = NULL; + FocusedWindow = NULL; + HoveredWindow = NULL; + HoveredRootWindow = NULL; + HoveredId = 0; + HoveredIdAllowOverlap = false; + HoveredIdPreviousFrame = 0; + ActiveId = 0; + ActiveIdPreviousFrame = 0; + ActiveIdIsAlive = false; + ActiveIdIsJustActivated = false; + ActiveIdAllowOverlap = false; + ActiveIdClickOffset = ImVec2(-1,-1); + ActiveIdWindow = NULL; + MovedWindow = NULL; + MovedWindowMoveId = 0; + SettingsDirtyTimer = 0.0f; + + SetNextWindowPosVal = ImVec2(0.0f, 0.0f); + SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); + SetNextWindowCollapsedVal = false; + SetNextWindowPosCond = 0; + SetNextWindowSizeCond = 0; + SetNextWindowContentSizeCond = 0; + SetNextWindowCollapsedCond = 0; + SetNextWindowSizeConstraintRect = ImRect(); + SetNextWindowSizeConstraintCallback = NULL; + SetNextWindowSizeConstraintCallbackUserData = NULL; + SetNextWindowSizeConstraint = false; + SetNextWindowFocus = false; + SetNextTreeNodeOpenVal = false; + SetNextTreeNodeOpenCond = 0; + + ScalarAsInputTextId = 0; + DragCurrentValue = 0.0f; + DragLastMouseDelta = ImVec2(0.0f, 0.0f); + DragSpeedDefaultRatio = 1.0f / 100.0f; + DragSpeedScaleSlow = 0.01f; + DragSpeedScaleFast = 10.0f; + ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); + TooltipOverrideCount = 0; + PrivateClipboard = NULL; + OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f); + + ModalWindowDarkeningRatio = 0.0f; + OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging + MouseCursor = ImGuiMouseCursor_Arrow; + memset(MouseCursorData, 0, sizeof(MouseCursorData)); + + LogEnabled = false; + LogFile = NULL; + LogClipboard = NULL; + LogStartDepth = 0; + LogAutoExpandMaxDepth = 2; + + memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); + FramerateSecPerFrameIdx = 0; + FramerateSecPerFrameAccum = 0.0f; + CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1; + memset(TempBuffer, 0, sizeof(TempBuffer)); + } +}; + +// Transient per-window data, reset at the beginning of the frame +// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered. +struct IMGUI_API ImGuiDrawContext +{ + ImVec2 CursorPos; + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; + ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame + float CurrentLineHeight; + float CurrentLineTextBaseOffset; + float PrevLineHeight; + float PrevLineTextBaseOffset; + float LogLinePosY; + int TreeDepth; + ImGuiID LastItemId; + ImRect LastItemRect; + bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window) + bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window) + bool MenuBarAppending; + float MenuBarOffsetX; + ImVector ChildWindows; + ImGuiStorage* StateStorage; + ImGuiLayoutType LayoutType; + + // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. + float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window + float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] + bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true] + bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false] + ImVector ItemWidthStack; + ImVector TextWrapPosStack; + ImVector AllowKeyboardFocusStack; + ImVector ButtonRepeatStack; + ImVectorGroupStack; + ImGuiColorEditMode ColorEditMode; + int StackSizesBackup[6]; // Store size of various stacks for asserting + + float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + float GroupOffsetX; + float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. + int ColumnsCurrent; + int ColumnsCount; + float ColumnsMinX; + float ColumnsMaxX; + float ColumnsStartPosY; + float ColumnsCellMinY; + float ColumnsCellMaxY; + bool ColumnsShowBorders; + ImGuiID ColumnsSetId; + ImVector ColumnsData; + + ImGuiDrawContext() + { + CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); + CurrentLineHeight = PrevLineHeight = 0.0f; + CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; + LogLinePosY = -1.0f; + TreeDepth = 0; + LastItemId = 0; + LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); + LastItemHoveredAndUsable = LastItemHoveredRect = false; + MenuBarAppending = false; + MenuBarOffsetX = 0.0f; + StateStorage = NULL; + LayoutType = ImGuiLayoutType_Vertical; + ItemWidth = 0.0f; + ButtonRepeat = false; + AllowKeyboardFocus = true; + TextWrapPos = -1.0f; + ColorEditMode = ImGuiColorEditMode_RGB; + memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); + + IndentX = 0.0f; + GroupOffsetX = 0.0f; + ColumnsOffsetX = 0.0f; + ColumnsCurrent = 0; + ColumnsCount = 1; + ColumnsMinX = ColumnsMaxX = 0.0f; + ColumnsStartPosY = 0.0f; + ColumnsCellMinY = ColumnsCellMaxY = 0.0f; + ColumnsShowBorders = true; + ColumnsSetId = 0; + } +}; + +// Windows data +struct IMGUI_API ImGuiWindow +{ + char* Name; + ImGuiID ID; // == ImHash(Name) + ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ + int OrderWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. + ImVec2 PosFloat; + ImVec2 Pos; // Position rounded-up to nearest pixel + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed + ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame + ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize() + ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis + ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect + ImGuiID MoveId; // == window->GetID("#MOVE") + ImVec2 Scroll; + ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) + ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered + bool ScrollbarX, ScrollbarY; + ImVec2 ScrollbarSizes; + float BorderSize; + bool Active; // Set to true on Begin() + bool WasActive; + bool Accessed; // Set to true when any widget access the current window + bool Collapsed; // Set when collapsing window to become only title-bar + bool SkipItems; // == Visible && !Collapsed + int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + int AutoFitFramesX, AutoFitFramesY; + bool AutoFitOnlyGrows; + int AutoPosLastDirection; + int HiddenFrames; + int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag. + int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag. + int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag. + bool SetWindowPosCenterWanted; + + ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame + ImVector IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack + ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. + ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window. + int LastFrameActive; + float ItemWidthDefault; + ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items + ImGuiStorage StateStorage; + float FontWindowScale; // Scale multiplier per-window + ImDrawList* DrawList; + ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself. + ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself. + ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL. + + // Navigation / Focus + int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() + int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) + int FocusIdxAllRequestCurrent; // Item being requested for focus + int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus + int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) + int FocusIdxTabRequestNext; // " + +public: + ImGuiWindow(const char* name); + ~ImGuiWindow(); + + ImGuiID GetID(const char* str, const char* str_end = NULL); + ImGuiID GetID(const void* ptr); + ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL); + + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } + float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } + float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } + float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } +}; + +//----------------------------------------------------------------------------- +// Internal API +// No guarantee of forward compatibility here. +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) + // If this ever crash because g.CurrentWindow is NULL it means that either + // - ImGui::NewFrame() has never been called, which is illegal. + // - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. + inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; } + IMGUI_API ImGuiWindow* GetParentWindow(); + IMGUI_API ImGuiWindow* FindWindowByName(const char* name); + IMGUI_API void FocusWindow(ImGuiWindow* window); + + IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead! + + IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void ClearActiveID(); + IMGUI_API void SetHoveredID(ImGuiID id); + IMGUI_API void KeepAliveID(ImGuiID id); + + IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f); + IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); + IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id); + IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged); + IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false); + IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop = true); // Return true if focus is requested + IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); + IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); + + IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing); + + // NB: All position are in absolute pixels coordinates (not window coordinates) + // FIXME: All those functions are a mess and needs to be refactored into something decent. AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. + // We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers. + IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); + IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); + IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL); + IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); + IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f); + IMGUI_API void RenderBullet(ImVec2 pos); + IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col); + IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. + + IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); + IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); + + IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power); + IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format); + + IMGUI_API bool DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power); + IMGUI_API bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power); + IMGUI_API bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format); + + IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision); + + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging + IMGUI_API void TreePushRawID(ImGuiID id); + + IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); + + IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value); + IMGUI_API float RoundScalar(float value, int decimal_precision); + +} // namespace ImGui + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif diff --git a/src/imgui/stb_rect_pack.h b/src/imgui/stb_rect_pack.h new file mode 100644 index 00000000..c75527da --- /dev/null +++ b/src/imgui/stb_rect_pack.h @@ -0,0 +1,583 @@ +// stb_rect_pack.h - v0.10 - public domain - rectangle packing +// Sean Barrett 2014 +// +// Useful for e.g. packing rectangular textures into an atlas. +// Does not do rotation. +// +// Not necessarily the awesomest packing method, but better than +// the totally naive one in stb_truetype (which is primarily what +// this is meant to replace). +// +// Has only had a few tests run, may have issues. +// +// More docs to come. +// +// No memory allocations; uses qsort() and assert() from stdlib. +// Can override those by defining STBRP_SORT and STBRP_ASSERT. +// +// This library currently uses the Skyline Bottom-Left algorithm. +// +// Please note: better rectangle packers are welcome! Please +// implement them to the same API, but with a different init +// function. +// +// Credits +// +// Library +// Sean Barrett +// Minor features +// Martins Mozeiko +// Bugfixes / warning fixes +// Jeremy Jaussaud +// +// Version history: +// +// 0.10 (2016-10-25) remove cast-away-const to avoid warnings +// 0.09 (2016-08-27) fix compiler warnings +// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort +// 0.05: added STBRP_ASSERT to allow replacing assert +// 0.04: fixed minor bug in STBRP_LARGE_RECTS support +// 0.01: initial release +// +// LICENSE +// +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. + +////////////////////////////////////////////////////////////////////////////// +// +// INCLUDE SECTION +// + +#ifndef STB_INCLUDE_STB_RECT_PACK_H +#define STB_INCLUDE_STB_RECT_PACK_H + +#define STB_RECT_PACK_VERSION 1 + +#ifdef STBRP_STATIC +#define STBRP_DEF static +#else +#define STBRP_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct stbrp_context stbrp_context; +typedef struct stbrp_node stbrp_node; +typedef struct stbrp_rect stbrp_rect; + +#ifdef STBRP_LARGE_RECTS +typedef int stbrp_coord; +#else +typedef unsigned short stbrp_coord; +#endif + +STBRP_DEF void stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); +// Assign packed locations to rectangles. The rectangles are of type +// 'stbrp_rect' defined below, stored in the array 'rects', and there +// are 'num_rects' many of them. +// +// Rectangles which are successfully packed have the 'was_packed' flag +// set to a non-zero value and 'x' and 'y' store the minimum location +// on each axis (i.e. bottom-left in cartesian coordinates, top-left +// if you imagine y increasing downwards). Rectangles which do not fit +// have the 'was_packed' flag set to 0. +// +// You should not try to access the 'rects' array from another thread +// while this function is running, as the function temporarily reorders +// the array while it executes. +// +// To pack into another rectangle, you need to call stbrp_init_target +// again. To continue packing into the same rectangle, you can call +// this function again. Calling this multiple times with multiple rect +// arrays will probably produce worse packing results than calling it +// a single time with the full rectangle array, but the option is +// available. + +struct stbrp_rect +{ + // reserved for your use: + int id; + + // input: + stbrp_coord w, h; + + // output: + stbrp_coord x, y; + int was_packed; // non-zero if valid packing + +}; // 16 bytes, nominally + + +STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); +// Initialize a rectangle packer to: +// pack a rectangle that is 'width' by 'height' in dimensions +// using temporary storage provided by the array 'nodes', which is 'num_nodes' long +// +// You must call this function every time you start packing into a new target. +// +// There is no "shutdown" function. The 'nodes' memory must stay valid for +// the following stbrp_pack_rects() call (or calls), but can be freed after +// the call (or calls) finish. +// +// Note: to guarantee best results, either: +// 1. make sure 'num_nodes' >= 'width' +// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' +// +// If you don't do either of the above things, widths will be quantized to multiples +// of small integers to guarantee the algorithm doesn't run out of temporary storage. +// +// If you do #2, then the non-quantized algorithm will be used, but the algorithm +// may run out of temporary storage and be unable to pack some rectangles. + +STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); +// Optionally call this function after init but before doing any packing to +// change the handling of the out-of-temp-memory scenario, described above. +// If you call init again, this will be reset to the default (false). + + +STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); +// Optionally select which packing heuristic the library should use. Different +// heuristics will produce better/worse results for different data sets. +// If you call init again, this will be reset to the default. + +enum +{ + STBRP_HEURISTIC_Skyline_default=0, + STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, + STBRP_HEURISTIC_Skyline_BF_sortHeight +}; + + +////////////////////////////////////////////////////////////////////////////// +// +// the details of the following structures don't matter to you, but they must +// be visible so you can handle the memory allocations for them + +struct stbrp_node +{ + stbrp_coord x,y; + stbrp_node *next; +}; + +struct stbrp_context +{ + int width; + int height; + int align; + int init_mode; + int heuristic; + int num_nodes; + stbrp_node *active_head; + stbrp_node *free_head; + stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' +}; + +#ifdef __cplusplus +} +#endif + +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// IMPLEMENTATION SECTION +// + +#ifdef STB_RECT_PACK_IMPLEMENTATION +#ifndef STBRP_SORT +#include +#define STBRP_SORT qsort +#endif + +#ifndef STBRP_ASSERT +#include +#define STBRP_ASSERT assert +#endif + +#ifdef _MSC_VER +#define STBRP__NOTUSED(v) (void)(v) +#else +#define STBRP__NOTUSED(v) (void)sizeof(v) +#endif + +enum +{ + STBRP__INIT_skyline = 1 +}; + +STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) +{ + switch (context->init_mode) { + case STBRP__INIT_skyline: + STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); + context->heuristic = heuristic; + break; + default: + STBRP_ASSERT(0); + } +} + +STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) +{ + if (allow_out_of_mem) + // if it's ok to run out of memory, then don't bother aligning them; + // this gives better packing, but may fail due to OOM (even though + // the rectangles easily fit). @TODO a smarter approach would be to only + // quantize once we've hit OOM, then we could get rid of this parameter. + context->align = 1; + else { + // if it's not ok to run out of memory, then quantize the widths + // so that num_nodes is always enough nodes. + // + // I.e. num_nodes * align >= width + // align >= width / num_nodes + // align = ceil(width/num_nodes) + + context->align = (context->width + context->num_nodes-1) / context->num_nodes; + } +} + +STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) +{ + int i; +#ifndef STBRP_LARGE_RECTS + STBRP_ASSERT(width <= 0xffff && height <= 0xffff); +#endif + + for (i=0; i < num_nodes-1; ++i) + nodes[i].next = &nodes[i+1]; + nodes[i].next = NULL; + context->init_mode = STBRP__INIT_skyline; + context->heuristic = STBRP_HEURISTIC_Skyline_default; + context->free_head = &nodes[0]; + context->active_head = &context->extra[0]; + context->width = width; + context->height = height; + context->num_nodes = num_nodes; + stbrp_setup_allow_out_of_mem(context, 0); + + // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) + context->extra[0].x = 0; + context->extra[0].y = 0; + context->extra[0].next = &context->extra[1]; + context->extra[1].x = (stbrp_coord) width; +#ifdef STBRP_LARGE_RECTS + context->extra[1].y = (1<<30); +#else + context->extra[1].y = 65535; +#endif + context->extra[1].next = NULL; +} + +// find minimum y position if it starts at x1 +static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) +{ + stbrp_node *node = first; + int x1 = x0 + width; + int min_y, visited_width, waste_area; + + STBRP__NOTUSED(c); + + STBRP_ASSERT(first->x <= x0); + + #if 0 + // skip in case we're past the node + while (node->next->x <= x0) + ++node; + #else + STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency + #endif + + STBRP_ASSERT(node->x <= x0); + + min_y = 0; + waste_area = 0; + visited_width = 0; + while (node->x < x1) { + if (node->y > min_y) { + // raise min_y higher. + // we've accounted for all waste up to min_y, + // but we'll now add more waste for everything we've visted + waste_area += visited_width * (node->y - min_y); + min_y = node->y; + // the first time through, visited_width might be reduced + if (node->x < x0) + visited_width += node->next->x - x0; + else + visited_width += node->next->x - node->x; + } else { + // add waste area + int under_width = node->next->x - node->x; + if (under_width + visited_width > width) + under_width = width - visited_width; + waste_area += under_width * (min_y - node->y); + visited_width += under_width; + } + node = node->next; + } + + *pwaste = waste_area; + return min_y; +} + +typedef struct +{ + int x,y; + stbrp_node **prev_link; +} stbrp__findresult; + +static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) +{ + int best_waste = (1<<30), best_x, best_y = (1 << 30); + stbrp__findresult fr; + stbrp_node **prev, *node, *tail, **best = NULL; + + // align to multiple of c->align + width = (width + c->align - 1); + width -= width % c->align; + STBRP_ASSERT(width % c->align == 0); + + node = c->active_head; + prev = &c->active_head; + while (node->x + width <= c->width) { + int y,waste; + y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); + if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL + // bottom left + if (y < best_y) { + best_y = y; + best = prev; + } + } else { + // best-fit + if (y + height <= c->height) { + // can only use it if it first vertically + if (y < best_y || (y == best_y && waste < best_waste)) { + best_y = y; + best_waste = waste; + best = prev; + } + } + } + prev = &node->next; + node = node->next; + } + + best_x = (best == NULL) ? 0 : (*best)->x; + + // if doing best-fit (BF), we also have to try aligning right edge to each node position + // + // e.g, if fitting + // + // ____________________ + // |____________________| + // + // into + // + // | | + // | ____________| + // |____________| + // + // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned + // + // This makes BF take about 2x the time + + if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { + tail = c->active_head; + node = c->active_head; + prev = &c->active_head; + // find first node that's admissible + while (tail->x < width) + tail = tail->next; + while (tail) { + int xpos = tail->x - width; + int y,waste; + STBRP_ASSERT(xpos >= 0); + // find the left position that matches this + while (node->next->x <= xpos) { + prev = &node->next; + node = node->next; + } + STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); + y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); + if (y + height < c->height) { + if (y <= best_y) { + if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { + best_x = xpos; + STBRP_ASSERT(y <= best_y); + best_y = y; + best_waste = waste; + best = prev; + } + } + } + tail = tail->next; + } + } + + fr.prev_link = best; + fr.x = best_x; + fr.y = best_y; + return fr; +} + +static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) +{ + // find best position according to heuristic + stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); + stbrp_node *node, *cur; + + // bail if: + // 1. it failed + // 2. the best node doesn't fit (we don't always check this) + // 3. we're out of memory + if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { + res.prev_link = NULL; + return res; + } + + // on success, create new node + node = context->free_head; + node->x = (stbrp_coord) res.x; + node->y = (stbrp_coord) (res.y + height); + + context->free_head = node->next; + + // insert the new node into the right starting point, and + // let 'cur' point to the remaining nodes needing to be + // stiched back in + + cur = *res.prev_link; + if (cur->x < res.x) { + // preserve the existing one, so start testing with the next one + stbrp_node *next = cur->next; + cur->next = node; + cur = next; + } else { + *res.prev_link = node; + } + + // from here, traverse cur and free the nodes, until we get to one + // that shouldn't be freed + while (cur->next && cur->next->x <= res.x + width) { + stbrp_node *next = cur->next; + // move the current node to the free list + cur->next = context->free_head; + context->free_head = cur; + cur = next; + } + + // stitch the list back in + node->next = cur; + + if (cur->x < res.x + width) + cur->x = (stbrp_coord) (res.x + width); + +#ifdef _DEBUG + cur = context->active_head; + while (cur->x < context->width) { + STBRP_ASSERT(cur->x < cur->next->x); + cur = cur->next; + } + STBRP_ASSERT(cur->next == NULL); + + { + stbrp_node *L1 = NULL, *L2 = NULL; + int count=0; + cur = context->active_head; + while (cur) { + L1 = cur; + cur = cur->next; + ++count; + } + cur = context->free_head; + while (cur) { + L2 = cur; + cur = cur->next; + ++count; + } + STBRP_ASSERT(count == context->num_nodes+2); + } +#endif + + return res; +} + +static int rect_height_compare(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; + if (p->h > q->h) + return -1; + if (p->h < q->h) + return 1; + return (p->w > q->w) ? -1 : (p->w < q->w); +} + +static int rect_width_compare(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; + if (p->w > q->w) + return -1; + if (p->w < q->w) + return 1; + return (p->h > q->h) ? -1 : (p->h < q->h); +} + +static int rect_original_order(const void *a, const void *b) +{ + const stbrp_rect *p = (const stbrp_rect *) a; + const stbrp_rect *q = (const stbrp_rect *) b; + return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); +} + +#ifdef STBRP_LARGE_RECTS +#define STBRP__MAXVAL 0xffffffff +#else +#define STBRP__MAXVAL 0xffff +#endif + +STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) +{ + int i; + + // we use the 'was_packed' field internally to allow sorting/unsorting + for (i=0; i < num_rects; ++i) { + rects[i].was_packed = i; + #ifndef STBRP_LARGE_RECTS + STBRP_ASSERT(rects[i].w <= 0xffff && rects[i].h <= 0xffff); + #endif + } + + // sort according to heuristic + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); + + for (i=0; i < num_rects; ++i) { + if (rects[i].w == 0 || rects[i].h == 0) { + rects[i].x = rects[i].y = 0; // empty rect needs no space + } else { + stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + if (fr.prev_link) { + rects[i].x = (stbrp_coord) fr.x; + rects[i].y = (stbrp_coord) fr.y; + } else { + rects[i].x = rects[i].y = STBRP__MAXVAL; + } + } + } + + // unsort + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); + + // set was_packed flags + for (i=0; i < num_rects; ++i) + rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); +} +#endif diff --git a/src/imgui/stb_textedit.h b/src/imgui/stb_textedit.h new file mode 100644 index 00000000..4b731a0c --- /dev/null +++ b/src/imgui/stb_textedit.h @@ -0,0 +1,1322 @@ +// [ImGui] this is a slightly modified version of stb_truetype.h 1.9. Those changes would need to be pushed into nothings/sb +// [ImGui] - fixed linestart handler when over last character of multi-line buffer + simplified existing code (#588, #815) +// [ImGui] - fixed a state corruption/crash bug in stb_text_redo and stb_textedit_discard_redo (#715) +// [ImGui] - fixed a crash bug in stb_textedit_discard_redo (#681) +// [ImGui] - fixed some minor warnings + +// stb_textedit.h - v1.9 - public domain - Sean Barrett +// Development of this library was sponsored by RAD Game Tools +// +// This C header file implements the guts of a multi-line text-editing +// widget; you implement display, word-wrapping, and low-level string +// insertion/deletion, and stb_textedit will map user inputs into +// insertions & deletions, plus updates to the cursor position, +// selection state, and undo state. +// +// It is intended for use in games and other systems that need to build +// their own custom widgets and which do not have heavy text-editing +// requirements (this library is not recommended for use for editing large +// texts, as its performance does not scale and it has limited undo). +// +// Non-trivial behaviors are modelled after Windows text controls. +// +// +// LICENSE +// +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. +// +// +// DEPENDENCIES +// +// Uses the C runtime function 'memmove', which you can override +// by defining STB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. +// +// +// VERSION HISTORY +// +// 1.9 (2016-08-27) customizable move-by-word +// 1.8 (2016-04-02) better keyboard handling when mouse button is down +// 1.7 (2015-09-13) change y range handling in case baseline is non-0 +// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +// 1.5 (2014-09-10) add support for secondary keys for OS X +// 1.4 (2014-08-17) fix signed/unsigned warnings +// 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +// 1.2 (2014-05-27) fix some RAD types that had crept into the new code +// 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +// 1.0 (2012-07-26) improve documentation, initial public release +// 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +// 0.2 (2011-11-28) fixes to undo/redo +// 0.1 (2010-07-08) initial version +// +// ADDITIONAL CONTRIBUTORS +// +// Ulf Winklemann: move-by-word in 1.1 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Omar Cornut +// +// USAGE +// +// This file behaves differently depending on what symbols you define +// before including it. +// +// +// Header-file mode: +// +// If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this, +// it will operate in "header file" mode. In this mode, it declares a +// single public symbol, STB_TexteditState, which encapsulates the current +// state of a text widget (except for the string, which you will store +// separately). +// +// To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a +// primitive type that defines a single character (e.g. char, wchar_t, etc). +// +// To save space or increase undo-ability, you can optionally define the +// following things that are used by the undo system: +// +// STB_TEXTEDIT_POSITIONTYPE small int type encoding a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// If you don't define these, they are set to permissive types and +// moderate sizes. The undo system does no memory allocations, so +// it grows STB_TexteditState by the worst-case storage which is (in bytes): +// +// [4 + sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT +// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT +// +// +// Implementation mode: +// +// If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it +// will compile the implementation of the text edit widget, depending +// on a large number of symbols which must be defined before the include. +// +// The implementation is defined only as static functions. You will then +// need to provide your own APIs in the same file which will access the +// static functions. +// +// The basic concept is that you provide a "string" object which +// behaves like an array of characters. stb_textedit uses indices to +// refer to positions in the string, implicitly representing positions +// in the displayed textedit. This is true for both plain text and +// rich text; even with rich text stb_truetype interacts with your +// code as if there was an array of all the displayed characters. +// +// Symbols that must be the same in header-file and implementation mode: +// +// STB_TEXTEDIT_CHARTYPE the character type +// STB_TEXTEDIT_POSITIONTYPE small type that a valid cursor position +// STB_TEXTEDIT_UNDOSTATECOUNT the number of undo states to allow +// STB_TEXTEDIT_UNDOCHARCOUNT the number of characters to store in the undo buffer +// +// Symbols you must define for implementation mode: +// +// STB_TEXTEDIT_STRING the type of object representing a string being edited, +// typically this is a wrapper object with other data you need +// +// STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +// STB_TEXTEDIT_LAYOUTROW(&r,obj,n) returns the results of laying out a line of characters +// starting from character #n (see discussion below) +// STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +// to the xpos of the i+1'th char for a line of characters +// starting at character #n (i.e. accounts for kerning +// with previous char) +// STB_TEXTEDIT_KEYTOTEXT(k) maps a keyboard input to an insertable character +// (return type is int, -1 means not valid to insert) +// STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 0-based +// STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +// as manually wordwrapping for end-of-line positioning +// +// STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +// STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n) insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*) +// +// STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +// +// STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +// STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +// STB_TEXTEDIT_K_UP keyboard input to move cursor up +// STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +// STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line // e.g. HOME +// STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line // e.g. END +// STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text // e.g. ctrl-HOME +// STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text // e.g. ctrl-END +// STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +// STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +// STB_TEXTEDIT_K_UNDO keyboard input to perform undo +// STB_TEXTEDIT_K_REDO keyboard input to perform redo +// +// Optional: +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for default WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line +// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text +// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text +// +// Todo: +// STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +// STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +// +// Keyboard input must be encoded as a single integer value; e.g. a character code +// and some bitflags that represent shift states. to simplify the interface, SHIFT must +// be a bitflag, so we can test the shifted state of cursor movements to allow selection, +// i.e. (STB_TEXTED_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +// +// You can encode other things, such as CONTROL or ALT, in additional bits, and +// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example, +// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN +// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit, +// and I pass both WM_KEYDOWN and WM_CHAR events to the "key" function in the +// API below. The control keys will only match WM_KEYDOWN events because of the +// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN +// bit so it only decodes WM_CHAR events. +// +// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +// row of characters assuming they start on the i'th character--the width and +// the height and the number of characters consumed. This allows this library +// to traverse the entire layout incrementally. You need to compute word-wrapping +// here. +// +// Each textfield keeps its own insert mode state, which is not how normal +// applications work. To keep an app-wide insert mode, update/copy the +// "insert_mode" field of STB_TexteditState before/after calling API functions. +// +// API +// +// void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +// +// void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +// int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +// int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len) +// void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) +// +// Each of these functions potentially updates the string and updates the +// state. +// +// initialize_state: +// set the textedit state to a known good default state when initially +// constructing the textedit. +// +// click: +// call this with the mouse x,y on a mouse down; it will update the cursor +// and reset the selection start/end to the cursor point. the x,y must +// be relative to the text widget, with (0,0) being the top left. +// +// drag: +// call this with the mouse x,y on a mouse drag/up; it will update the +// cursor and the selection end point +// +// cut: +// call this to delete the current selection; returns true if there was +// one. you should FIRST copy the current selection to the system paste buffer. +// (To copy, just copy the current selection out of the string yourself.) +// +// paste: +// call this to paste text at the current cursor point or over the current +// selection if there is one. +// +// key: +// call this for keyboard inputs sent to the textfield. you can use it +// for "key down" events or for "translated" key events. if you need to +// do both (as in Win32), or distinguish Unicode characters from control +// inputs, set a high bit to distinguish the two; then you can define the +// various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit +// set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is +// clear. +// +// When rendering, you can read the cursor position and selection state from +// the STB_TexteditState. +// +// +// Notes: +// +// This is designed to be usable in IMGUI, so it allows for the possibility of +// running in an IMGUI that has NOT cached the multi-line layout. For this +// reason, it provides an interface that is compatible with computing the +// layout incrementally--we try to make sure we make as few passes through +// as possible. (For example, to locate the mouse pointer in the text, we +// could define functions that return the X and Y positions of characters +// and binary search Y and then X, but if we're doing dynamic layout this +// will run the layout algorithm many times, so instead we manually search +// forward in one pass. Similar logic applies to e.g. up-arrow and +// down-arrow movement.) +// +// If it's run in a widget that *has* cached the layout, then this is less +// efficient, but it's not horrible on modern computers. But you wouldn't +// want to edit million-line files with it. + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Header-file mode +//// +//// + +#ifndef INCLUDE_STB_TEXTEDIT_H +#define INCLUDE_STB_TEXTEDIT_H + +//////////////////////////////////////////////////////////////////////// +// +// STB_TexteditState +// +// Definition of STB_TexteditState which you should store +// per-textfield; it includes cursor position, selection state, +// and undo state. +// + +#ifndef STB_TEXTEDIT_UNDOSTATECOUNT +#define STB_TEXTEDIT_UNDOSTATECOUNT 99 +#endif +#ifndef STB_TEXTEDIT_UNDOCHARCOUNT +#define STB_TEXTEDIT_UNDOCHARCOUNT 999 +#endif +#ifndef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_CHARTYPE int +#endif +#ifndef STB_TEXTEDIT_POSITIONTYPE +#define STB_TEXTEDIT_POSITIONTYPE int +#endif + +typedef struct +{ + // private data + STB_TEXTEDIT_POSITIONTYPE where; + short insert_length; + short delete_length; + short char_storage; +} StbUndoRecord; + +typedef struct +{ + // private data + StbUndoRecord undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT]; + STB_TEXTEDIT_CHARTYPE undo_char[STB_TEXTEDIT_UNDOCHARCOUNT]; + short undo_point, redo_point; + short undo_char_point, redo_char_point; +} StbUndoState; + +typedef struct +{ + ///////////////////// + // + // public data + // + + int cursor; + // position of the text cursor within the string + + int select_start; // selection start point + int select_end; + // selection start and end point in characters; if equal, no selection. + // note that start may be less than or greater than end (e.g. when + // dragging the mouse, start is where the initial click was, and you + // can drag in either direction) + + unsigned char insert_mode; + // each textfield keeps its own insert mode state. to keep an app-wide + // insert mode, copy this value in/out of the app state + + ///////////////////// + // + // private data + // + unsigned char cursor_at_end_of_line; // not implemented yet + unsigned char initialized; + unsigned char has_preferred_x; + unsigned char single_line; + unsigned char padding1, padding2, padding3; + float preferred_x; // this determines where the cursor up/down tries to seek to along x + StbUndoState undostate; +} STB_TexteditState; + + +//////////////////////////////////////////////////////////////////////// +// +// StbTexteditRow +// +// Result of layout query, used by stb_textedit to determine where +// the text in each row is. + +// result of layout query +typedef struct +{ + float x0,x1; // starting x location, end x location (allows for align=right, etc) + float baseline_y_delta; // position of baseline relative to previous row's baseline + float ymin,ymax; // height of row above and below baseline + int num_chars; +} StbTexteditRow; +#endif //INCLUDE_STB_TEXTEDIT_H + + +//////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////// +//// +//// Implementation mode +//// +//// + + +// implementation isn't include-guarded, since it might have indirectly +// included just the "header" portion +#ifdef STB_TEXTEDIT_IMPLEMENTATION + +#ifndef STB_TEXTEDIT_memmove +#include +#define STB_TEXTEDIT_memmove memmove +#endif + + +///////////////////////////////////////////////////////////////////////////// +// +// Mouse input handling +// + +// traverse the layout to locate the nearest character to a display position +static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) +{ + StbTexteditRow r; + int n = STB_TEXTEDIT_STRINGLEN(str); + float base_y = 0, prev_x; + int i=0, k; + + r.x0 = r.x1 = 0; + r.ymin = r.ymax = 0; + r.num_chars = 0; + + // search rows to find one that straddles 'y' + while (i < n) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (r.num_chars <= 0) + return n; + + if (i==0 && y < base_y + r.ymin) + return 0; + + if (y < base_y + r.ymax) + break; + + i += r.num_chars; + base_y += r.baseline_y_delta; + } + + // below all text, return 'after' last character + if (i >= n) + return n; + + // check if it's before the beginning of the line + if (x < r.x0) + return i; + + // check if it's before the end of the line + if (x < r.x1) { + // search characters in row for one that straddles 'x' + prev_x = r.x0; + for (k=0; k < r.num_chars; ++k) { + float w = STB_TEXTEDIT_GETWIDTH(str, i, k); + if (x < prev_x+w) { + if (x < prev_x+w/2) + return k+i; + else + return k+i+1; + } + prev_x += w; + } + // shouldn't happen, but if it does, fall through to end-of-line case + } + + // if the last character is a newline, return that. otherwise return 'after' the last character + if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE) + return i+r.num_chars-1; + else + return i+r.num_chars; +} + +// API click: on mouse down, move the cursor to the clicked location, and reset the selection +static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + state->cursor = stb_text_locate_coord(str, x, y); + state->select_start = state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; +} + +// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location +static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) +{ + int p = stb_text_locate_coord(str, x, y); + if (state->select_start == state->select_end) + state->select_start = state->cursor; + state->cursor = state->select_end = p; +} + +///////////////////////////////////////////////////////////////////////////// +// +// Keyboard input handling +// + +// forward declarations +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state); +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length); +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length); + +typedef struct +{ + float x,y; // position of n'th character + float height; // height of line + int first_char, length; // first char of row, and length + int prev_first; // first char of previous row +} StbFindState; + +// find the x/y location of a character, and remember info about the previous row in +// case we get a move-up event (for page up, we'll have to rescan) +static void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line) +{ + StbTexteditRow r; + int prev_start = 0; + int z = STB_TEXTEDIT_STRINGLEN(str); + int i=0, first; + + if (n == z) { + // if it's at the end, then find the last line -- simpler than trying to + // explicitly handle this case in the regular code + if (single_line) { + STB_TEXTEDIT_LAYOUTROW(&r, str, 0); + find->y = 0; + find->first_char = 0; + find->length = z; + find->height = r.ymax - r.ymin; + find->x = r.x1; + } else { + find->y = 0; + find->x = 0; + find->height = 1; + while (i < z) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + prev_start = i; + i += r.num_chars; + } + find->first_char = i; + find->length = 0; + find->prev_first = prev_start; + } + return; + } + + // search rows to find the one that straddles character n + find->y = 0; + + for(;;) { + STB_TEXTEDIT_LAYOUTROW(&r, str, i); + if (n < i + r.num_chars) + break; + prev_start = i; + i += r.num_chars; + find->y += r.baseline_y_delta; + } + + find->first_char = first = i; + find->length = r.num_chars; + find->height = r.ymax - r.ymin; + find->prev_first = prev_start; + + // now scan to find xpos + find->x = r.x0; + i = 0; + for (i=0; first+i < n; ++i) + find->x += STB_TEXTEDIT_GETWIDTH(str, first, i); +} + +#define STB_TEXT_HAS_SELECTION(s) ((s)->select_start != (s)->select_end) + +// make the selection/cursor state valid if client altered the string +static void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + int n = STB_TEXTEDIT_STRINGLEN(str); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start > n) state->select_start = n; + if (state->select_end > n) state->select_end = n; + // if clamping forced them to be equal, move the cursor to match + if (state->select_start == state->select_end) + state->cursor = state->select_start; + } + if (state->cursor > n) state->cursor = n; +} + +// delete characters while updating undo +static void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len) +{ + stb_text_makeundo_delete(str, state, where, len); + STB_TEXTEDIT_DELETECHARS(str, where, len); + state->has_preferred_x = 0; +} + +// delete the section +static void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + stb_textedit_clamp(str, state); + if (STB_TEXT_HAS_SELECTION(state)) { + if (state->select_start < state->select_end) { + stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start); + state->select_end = state->cursor = state->select_start; + } else { + stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end); + state->select_start = state->cursor = state->select_end; + } + state->has_preferred_x = 0; + } +} + +// canoncialize the selection so start <= end +static void stb_textedit_sortselection(STB_TexteditState *state) +{ + if (state->select_end < state->select_start) { + int temp = state->select_end; + state->select_end = state->select_start; + state->select_start = temp; + } +} + +// move cursor to first character of selection +static void stb_textedit_move_to_first(STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + state->cursor = state->select_start; + state->select_end = state->select_start; + state->has_preferred_x = 0; + } +} + +// move cursor to last character of selection +static void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_sortselection(state); + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->select_start = state->select_end; + state->has_preferred_x = 0; + } +} + +#ifdef STB_TEXTEDIT_IS_SPACE +static int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx ) +{ + return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1; +} + +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c ) +{ + --c; // always move at least one character + while( c >= 0 && !is_word_boundary( str, c ) ) + --c; + + if( c < 0 ) + c = 0; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif + +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c ) +{ + const int len = STB_TEXTEDIT_STRINGLEN(str); + ++c; // always move at least one character + while( c < len && !is_word_boundary( str, c ) ) + ++c; + + if( c > len ) + c = len; + + return c; +} +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + +#endif + +// update selection and cursor to match each other +static void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state) +{ + if (!STB_TEXT_HAS_SELECTION(state)) + state->select_start = state->select_end = state->cursor; + else + state->cursor = state->select_end; +} + +// API cut: delete selection +static int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + if (STB_TEXT_HAS_SELECTION(state)) { + stb_textedit_delete_selection(str,state); // implicity clamps + state->has_preferred_x = 0; + return 1; + } + return 0; +} + +// API paste: replace existing selection with passed-in text +static int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len) +{ + STB_TEXTEDIT_CHARTYPE *text = (STB_TEXTEDIT_CHARTYPE *) ctext; + // if there's a selection, the paste should delete it + stb_textedit_clamp(str, state); + stb_textedit_delete_selection(str,state); + // try to insert the characters + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) { + stb_text_makeundo_insert(state, state->cursor, len); + state->cursor += len; + state->has_preferred_x = 0; + return 1; + } + // remove the undo since we didn't actually insert the characters + if (state->undostate.undo_point) + --state->undostate.undo_point; + return 0; +} + +// API key: process a keyboard input +static void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int key) +{ +retry: + switch (key) { + default: { + int c = STB_TEXTEDIT_KEYTOTEXT(key); + if (c > 0) { + STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c; + + // can't add newline in single-line mode + if (c == '\n' && state->single_line) + break; + + if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) { + stb_text_makeundo_replace(str, state, state->cursor, 1, 1); + STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1); + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + ++state->cursor; + state->has_preferred_x = 0; + } + } else { + stb_textedit_delete_selection(str,state); // implicity clamps + if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) { + stb_text_makeundo_insert(state, state->cursor, 1); + ++state->cursor; + state->has_preferred_x = 0; + } + } + } + break; + } + +#ifdef STB_TEXTEDIT_K_INSERT + case STB_TEXTEDIT_K_INSERT: + state->insert_mode = !state->insert_mode; + break; +#endif + + case STB_TEXTEDIT_K_UNDO: + stb_text_undo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_REDO: + stb_text_redo(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT: + // if currently there's a selection, move cursor to start of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else + if (state->cursor > 0) + --state->cursor; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_RIGHT: + // if currently there's a selection, move cursor to end of selection + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else + ++state->cursor; + stb_textedit_clamp(str, state); + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + // move selection left + if (state->select_end > 0) + --state->select_end; + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_MOVEWORDLEFT + case STB_TEXTEDIT_K_WORDLEFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + stb_textedit_clamp( str, state ); + } + break; + + case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: + if( !STB_TEXT_HAS_SELECTION( state ) ) + stb_textedit_prep_selection_at_cursor(state); + + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor); + state->select_end = state->cursor; + + stb_textedit_clamp( str, state ); + break; +#endif + + case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + // move selection right + ++state->select_end; + stb_textedit_clamp(str, state); + state->cursor = state->select_end; + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_DOWN: + case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + + if (state->single_line) { + // on windows, up&down in single-line behave like left&right + key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str,state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + // now find character position down a row + if (find.length) { + float goal_x = state->has_preferred_x ? state->preferred_x : find.x; + float x; + int start = find.first_char + find.length; + state->cursor = start; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, start, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + } + break; + } + + case STB_TEXTEDIT_K_UP: + case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT: { + StbFindState find; + StbTexteditRow row; + int i, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0; + + if (state->single_line) { + // on windows, up&down become left&right + key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT); + goto retry; + } + + if (sel) + stb_textedit_prep_selection_at_cursor(state); + else if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_first(state); + + // compute current position of cursor point + stb_textedit_clamp(str, state); + stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); + + // can only go up if there's a previous row + if (find.prev_first != find.first_char) { + // now find character position up a row + float goal_x = state->has_preferred_x ? state->preferred_x : find.x; + float x; + state->cursor = find.prev_first; + STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor); + x = row.x0; + for (i=0; i < row.num_chars; ++i) { + float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i); + #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE + if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE) + break; + #endif + x += dx; + if (x > goal_x) + break; + ++state->cursor; + } + stb_textedit_clamp(str, state); + + state->has_preferred_x = 1; + state->preferred_x = goal_x; + + if (sel) + state->select_end = state->cursor; + } + break; + } + + case STB_TEXTEDIT_K_DELETE: + case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + int n = STB_TEXTEDIT_STRINGLEN(str); + if (state->cursor < n) + stb_textedit_delete(str, state, state->cursor, 1); + } + state->has_preferred_x = 0; + break; + + case STB_TEXTEDIT_K_BACKSPACE: + case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_delete_selection(str, state); + else { + stb_textedit_clamp(str, state); + if (state->cursor > 0) { + stb_textedit_delete(str, state, state->cursor-1, 1); + --state->cursor; + } + } + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif + case STB_TEXTEDIT_K_TEXTSTART: + state->cursor = state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif + case STB_TEXTEDIT_K_TEXTEND: + state->cursor = STB_TEXTEDIT_STRINGLEN(str); + state->select_start = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = 0; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: + stb_textedit_prep_selection_at_cursor(state); + state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); + state->has_preferred_x = 0; + break; + + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif + case STB_TEXTEDIT_K_LINESTART: + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif + case STB_TEXTEDIT_K_LINEEND: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_move_to_first(state); + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; + state->has_preferred_x = 0; + break; + } + +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = 0; + else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif + case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { + int n = STB_TEXTEDIT_STRINGLEN(str); + stb_textedit_clamp(str, state); + stb_textedit_prep_selection_at_cursor(state); + if (state->single_line) + state->cursor = n; + else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE) + ++state->cursor; + state->select_end = state->cursor; + state->has_preferred_x = 0; + break; + } + +// @TODO: +// STB_TEXTEDIT_K_PGUP - move cursor up a page +// STB_TEXTEDIT_K_PGDOWN - move cursor down a page + } +} + +///////////////////////////////////////////////////////////////////////////// +// +// Undo processing +// +// @OPTIMIZE: the undo/redo buffer should be circular + +static void stb_textedit_flush_redo(StbUndoState *state) +{ + state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; +} + +// discard the oldest entry in the undo list +static void stb_textedit_discard_undo(StbUndoState *state) +{ + if (state->undo_point > 0) { + // if the 0th undo state has characters, clean those up + if (state->undo_rec[0].char_storage >= 0) { + int n = state->undo_rec[0].insert_length, i; + // delete n characters from all other records + state->undo_char_point = state->undo_char_point - (short) n; // vsnet05 + STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); + for (i=0; i < state->undo_point; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it + } + --state->undo_point; + STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); + } +} + +// discard the oldest entry in the redo list--it's bad if this +// ever happens, but because undo & redo have to store the actual +// characters in different cases, the redo character buffer can +// fill up even though the undo buffer didn't +static void stb_textedit_discard_redo(StbUndoState *state) +{ + int k = STB_TEXTEDIT_UNDOSTATECOUNT-1; + + if (state->redo_point <= k) { + // if the k'th undo state has characters, clean those up + if (state->undo_rec[k].char_storage >= 0) { + int n = state->undo_rec[k].insert_length, i; + // delete n characters from all other records + state->redo_char_point = state->redo_char_point + (short) n; // vsnet05 + STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); + for (i=state->redo_point; i < k; ++i) + if (state->undo_rec[i].char_storage >= 0) + state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05 + } + STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point, state->undo_rec + state->redo_point-1, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); + ++state->redo_point; + } +} + +static StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars) +{ + // any time we create a new undo record, we discard redo + stb_textedit_flush_redo(state); + + // if we have no free records, we have to make room, by sliding the + // existing records down + if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + stb_textedit_discard_undo(state); + + // if the characters to store won't possibly fit in the buffer, we can't undo + if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) { + state->undo_point = 0; + state->undo_char_point = 0; + return NULL; + } + + // if we don't have enough free characters in the buffer, we have to make room + while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT) + stb_textedit_discard_undo(state); + + return &state->undo_rec[state->undo_point++]; +} + +static STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len) +{ + StbUndoRecord *r = stb_text_create_undo_record(state, insert_len); + if (r == NULL) + return NULL; + + r->where = pos; + r->insert_length = (short) insert_len; + r->delete_length = (short) delete_len; + + if (insert_len == 0) { + r->char_storage = -1; + return NULL; + } else { + r->char_storage = state->undo_char_point; + state->undo_char_point = state->undo_char_point + (short) insert_len; + return &state->undo_char[r->char_storage]; + } +} + +static void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord u, *r; + if (s->undo_point == 0) + return; + + // we need to do two things: apply the undo record, and create a redo record + u = s->undo_rec[s->undo_point-1]; + r = &s->undo_rec[s->redo_point-1]; + r->char_storage = -1; + + r->insert_length = u.delete_length; + r->delete_length = u.insert_length; + r->where = u.where; + + if (u.delete_length) { + // if the undo record says to delete characters, then the redo record will + // need to re-insert the characters that get deleted, so we need to store + // them. + + // there are three cases: + // there's enough room to store the characters + // characters stored for *redoing* don't leave room for redo + // characters stored for *undoing* don't leave room for redo + // if the last is true, we have to bail + + if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) { + // the undo records take up too much character space; there's no space to store the redo characters + r->insert_length = 0; + } else { + int i; + + // there's definitely room to store the characters eventually + while (s->undo_char_point + u.delete_length > s->redo_char_point) { + // there's currently not enough room, so discard a redo record + stb_textedit_discard_redo(s); + // should never happen: + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + } + r = &s->undo_rec[s->redo_point-1]; + + r->char_storage = s->redo_char_point - u.delete_length; + s->redo_char_point = s->redo_char_point - (short) u.delete_length; + + // now save the characters + for (i=0; i < u.delete_length; ++i) + s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i); + } + + // now we can carry out the deletion + STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length); + } + + // check type of recorded action: + if (u.insert_length) { + // easy case: was a deletion, so we need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length); + s->undo_char_point -= u.insert_length; + } + + state->cursor = u.where + u.insert_length; + + s->undo_point--; + s->redo_point--; +} + +static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) +{ + StbUndoState *s = &state->undostate; + StbUndoRecord *u, r; + if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT) + return; + + // we need to do two things: apply the redo record, and create an undo record + u = &s->undo_rec[s->undo_point]; + r = s->undo_rec[s->redo_point]; + + // we KNOW there must be room for the undo record, because the redo record + // was derived from an undo record + + u->delete_length = r.insert_length; + u->insert_length = r.delete_length; + u->where = r.where; + u->char_storage = -1; + + if (r.delete_length) { + // the redo record requires us to delete characters, so the undo record + // needs to store the characters + + if (s->undo_char_point + u->insert_length > s->redo_char_point) { + u->insert_length = 0; + u->delete_length = 0; + } else { + int i; + u->char_storage = s->undo_char_point; + s->undo_char_point = s->undo_char_point + u->insert_length; + + // now save the characters + for (i=0; i < u->insert_length; ++i) + s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i); + } + + STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length); + } + + if (r.insert_length) { + // easy case: need to insert n characters + STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + s->redo_char_point += r.insert_length; + } + + state->cursor = r.where + r.insert_length; + + s->undo_point++; + s->redo_point++; +} + +static void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length) +{ + stb_text_createundo(&state->undostate, where, 0, length); +} + +static void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0); + if (p) { + for (i=0; i < length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +static void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length) +{ + int i; + STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length); + if (p) { + for (i=0; i < old_length; ++i) + p[i] = STB_TEXTEDIT_GETCHAR(str, where+i); + } +} + +// reset the state to default +static void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line) +{ + state->undostate.undo_point = 0; + state->undostate.undo_char_point = 0; + state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT; + state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT; + state->select_end = state->select_start = 0; + state->cursor = 0; + state->has_preferred_x = 0; + state->preferred_x = 0; + state->cursor_at_end_of_line = 0; + state->initialized = 1; + state->single_line = (unsigned char) is_single_line; + state->insert_mode = 0; +} + +// API initialize +static void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line) +{ + stb_textedit_clear_state(state, is_single_line); +} +#endif//STB_TEXTEDIT_IMPLEMENTATION diff --git a/src/imgui/stb_truetype.h b/src/imgui/stb_truetype.h new file mode 100644 index 00000000..92b9a875 --- /dev/null +++ b/src/imgui/stb_truetype.h @@ -0,0 +1,4018 @@ +// stb_truetype.h - v1.14 - public domain +// authored from 2009-2016 by Sean Barrett / RAD Game Tools +// +// This library processes TrueType files: +// parse files +// extract glyph metrics +// extract glyph shapes +// render glyphs to one-channel bitmaps with antialiasing (box filter) +// +// Todo: +// non-MS cmaps +// crashproof on bad data +// hinting? (no longer patented) +// cleartype-style AA? +// optimize: use simple memory allocator for intermediates +// optimize: build edge-list directly from curves +// optimize: rasterize directly from curves? +// +// ADDITIONAL CONTRIBUTORS +// +// Mikko Mononen: compound shape support, more cmap formats +// Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty +// +// Bug/warning reports/fixes: +// "Zer" on mollyrocket (with fix) +// Cass Everitt +// stoiko (Haemimont Games) +// Brian Hook +// Walter van Niftrik +// David Gow +// David Given +// Ivan-Assen Ivanov +// Anthony Pesch +// Johan Duparc +// Hou Qiming +// Fabian "ryg" Giesen +// Martins Mozeiko +// Cap Petschulat +// Omar Cornut +// github:aloucks +// Peter LaValle +// Sergey Popov +// Giumo X. Clanjor +// Higor Euripedes +// Thomas Fields +// Derek Vinyard +// +// VERSION HISTORY +// +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts, num-fonts-in-TTC function +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// +// Full history can be found at the end of this file. +// +// LICENSE +// +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. +// +// USAGE +// +// Include this file in whatever places neeed to refer to it. In ONE C/C++ +// file, write: +// #define STB_TRUETYPE_IMPLEMENTATION +// before the #include of this file. This expands out the actual +// implementation into that C/C++ file. +// +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// +// Simple 3D API (don't ship this, but it's fine for tools and quick start) +// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture +// stbtt_GetBakedQuad() -- compute quad to draw for a given char +// +// Improved 3D API (more shippable): +// #include "stb_rect_pack.h" -- optional, but you really want it +// stbtt_PackBegin() +// stbtt_PackSetOversample() -- for improved quality on small fonts +// stbtt_PackFontRanges() -- pack and renders +// stbtt_PackEnd() +// stbtt_GetPackedQuad() +// +// "Load" a font file from a memory buffer (you have to keep the buffer loaded) +// stbtt_InitFont() +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections +// +// Render a unicode codepoint to a bitmap +// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap +// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide +// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be +// +// Character advance/positioning +// stbtt_GetCodepointHMetrics() +// stbtt_GetFontVMetrics() +// stbtt_GetCodepointKernAdvance() +// +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// +// ADDITIONAL DOCUMENTATION +// +// Immediately after this block comment are a series of sample programs. +// +// After the sample programs is the "header file" section. This section +// includes documentation for each API function. +// +// Some important concepts to understand to use this library: +// +// Codepoint +// Characters are defined by unicode codepoints, e.g. 65 is +// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +// the hiragana for "ma". +// +// Glyph +// A visual character shape (every codepoint is rendered as +// some glyph) +// +// Glyph index +// A font-specific integer ID representing a glyph +// +// Baseline +// Glyph shapes are defined relative to a baseline, which is the +// bottom of uppercase characters. Characters extend both above +// and below the baseline. +// +// Current Point +// As you draw text to the screen, you keep track of a "current point" +// which is the origin of each character. The current point's vertical +// position is the baseline. Even "baked fonts" use this model. +// +// Vertical Font Metrics +// The vertical qualities of the font, used to vertically position +// and space the characters. See docs for stbtt_GetFontVMetrics. +// +// Font Size in Pixels or Points +// The preferred interface for specifying font sizes in stb_truetype +// is to specify how tall the font's vertical extent should be in pixels. +// If that sounds good enough, skip the next paragraph. +// +// Most font APIs instead use "points", which are a common typographic +// measurement for describing font size, defined as 72 points per inch. +// stb_truetype provides a point API for compatibility. However, true +// "per inch" conventions don't make much sense on computer displays +// since they different monitors have different number of pixels per +// inch. For example, Windows traditionally uses a convention that +// there are 96 pixels per inch, thus making 'inch' measurements have +// nothing to do with inches, and thus effectively defining a point to +// be 1.333 pixels. Additionally, the TrueType font data provides +// an explicit scale factor to scale a given font's glyphs to points, +// but the author has observed that this scale factor is often wrong +// for non-commercial fonts, thus making fonts scaled in points +// according to the TrueType spec incoherently sized in practice. +// +// ADVANCED USAGE +// +// Quality: +// +// - Use the functions with Subpixel at the end to allow your characters +// to have subpixel positioning. Since the font is anti-aliased, not +// hinted, this is very import for quality. (This is not possible with +// baked fonts.) +// +// - Kerning is now supported, and if you're supporting subpixel rendering +// then kerning is worth using to give your text a polished look. +// +// Performance: +// +// - Convert Unicode codepoints to glyph indexes and operate on the glyphs; +// if you don't do this, stb_truetype is forced to do the conversion on +// every call. +// +// - There are a lot of memory allocations. We should modify it to take +// a temp buffer and allocate from the temp buffer (without freeing), +// should help performance a lot. +// +// NOTES +// +// The system uses the raw data found in the .ttf file without changing it +// and without building auxiliary data structures. This is a bit inefficient +// on little-endian systems (the data is big-endian), but assuming you're +// caching the bitmaps or glyph shapes this shouldn't be a big deal. +// +// It appears to be very hard to programmatically determine what font a +// given file is in a general way. I provide an API for this, but I don't +// recommend it. +// +// +// SOURCE STATISTICS (based on v0.6c, 2050 LOC) +// +// Documentation & header file 520 LOC \___ 660 LOC documentation +// Sample code 140 LOC / +// Truetype parsing 620 LOC ---- 620 LOC TrueType +// Software rasterization 240 LOC \ . +// Curve tesselation 120 LOC \__ 550 LOC Bitmap creation +// Bitmap management 100 LOC / +// Baked bitmap interface 70 LOC / +// Font name matching & access 150 LOC ---- 150 +// C runtime library abstraction 60 LOC ---- 60 +// +// +// PERFORMANCE MEASUREMENTS FOR 1.06: +// +// 32-bit 64-bit +// Previous release: 8.83 s 7.68 s +// Pool allocations: 7.72 s 6.34 s +// Inline sort : 6.54 s 5.65 s +// New rasterizer : 5.63 s 5.00 s + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// SAMPLE PROGRAMS +//// +// +// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless +// +#if 0 +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +unsigned char ttf_buffer[1<<20]; +unsigned char temp_bitmap[512*512]; + +stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs +GLuint ftex; + +void my_stbtt_initfont(void) +{ + fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); + stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! + // can free ttf_buffer at this point + glGenTextures(1, &ftex); + glBindTexture(GL_TEXTURE_2D, ftex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); + // can free temp_bitmap at this point + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +} + +void my_stbtt_print(float x, float y, char *text) +{ + // assume orthographic projection with units = screen pixels, origin at top left + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, ftex); + glBegin(GL_QUADS); + while (*text) { + if (*text >= 32 && *text < 128) { + stbtt_aligned_quad q; + stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 + glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); + glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); + glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); + glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); + } + ++text; + } + glEnd(); +} +#endif +// +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program (this compiles): get a single bitmap, print as ASCII art +// +#if 0 +#include +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +char ttf_buffer[1<<25]; + +int main(int argc, char **argv) +{ + stbtt_fontinfo font; + unsigned char *bitmap; + int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); + + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); + + stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); + + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) + putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); + putchar('\n'); + } + return 0; +} +#endif +// +// Output: +// +// .ii. +// @@@@@@. +// V@Mio@@o +// :i. V@V +// :oM@@M +// :@@@MM@M +// @@o o@M +// :@@. M@M +// @@@o@@@@ +// :M@@V:@@. +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program: print "Hello World!" banner, with bugs +// +#if 0 +char buffer[24<<20]; +unsigned char screen[20][79]; + +int main(int arg, char **argv) +{ + stbtt_fontinfo font; + int i,j,ascent,baseline,ch=0; + float scale, xpos=2; // leave a little padding in case the character extends left + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness + + fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); + stbtt_InitFont(&font, buffer, 0); + + scale = stbtt_ScaleForPixelHeight(&font, 15); + stbtt_GetFontVMetrics(&font, &ascent,0,0); + baseline = (int) (ascent*scale); + + while (text[ch]) { + int advance,lsb,x0,y0,x1,y1; + float x_shift = xpos - (float) floor(xpos); + stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); + stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); + stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); + // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong + // because this API is really for baking character bitmaps into textures. if you want to render + // a sequence of characters, you really need to render each bitmap to a temp buffer, then + // "alpha blend" that into the working buffer + xpos += (advance * scale); + if (text[ch+1]) + xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); + ++ch; + } + + for (j=0; j < 20; ++j) { + for (i=0; i < 78; ++i) + putchar(" .:ioVM@"[screen[j][i]>>5]); + putchar('\n'); + } + + return 0; +} +#endif + + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// INTEGRATION WITH YOUR CODEBASE +//// +//// The following sections allow you to supply alternate definitions +//// of C library functions used by stb_truetype. + +#ifdef STB_TRUETYPE_IMPLEMENTATION + // #define your own (u)stbtt_int8/16/32 before including to override this + #ifndef stbtt_uint8 + typedef unsigned char stbtt_uint8; + typedef signed char stbtt_int8; + typedef unsigned short stbtt_uint16; + typedef signed short stbtt_int16; + typedef unsigned int stbtt_uint32; + typedef signed int stbtt_int32; + #endif + + typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; + typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; + + // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h + #ifndef STBTT_ifloor + #include + #define STBTT_ifloor(x) ((int) floor(x)) + #define STBTT_iceil(x) ((int) ceil(x)) + #endif + + #ifndef STBTT_sqrt + #include + #define STBTT_sqrt(x) sqrt(x) + #endif + + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h + #ifndef STBTT_malloc + #include + #define STBTT_malloc(x,u) ((void)(u),malloc(x)) + #define STBTT_free(x,u) ((void)(u),free(x)) + #endif + + #ifndef STBTT_assert + #include + #define STBTT_assert(x) assert(x) + #endif + + #ifndef STBTT_strlen + #include + #define STBTT_strlen(x) strlen(x) + #endif + + #ifndef STBTT_memcpy + #include + #define STBTT_memcpy memcpy + #define STBTT_memset memset + #endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// INTERFACE +//// +//// + +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#define __STB_INCLUDE_STB_TRUETYPE_H__ + +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + +////////////////////////////////////////////////////////////////////////////// +// +// TEXTURE BAKING API +// +// If you use this API, you only have to call two functions ever. +// + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; +} stbtt_bakedchar; + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata); // you allocate this, it's num_chars long +// if return is positive, the first unused row of the bitmap +// if return is negative, returns the negative of the number of characters that fit +// if return is 0, no characters fit and no rows were used +// This uses a very crappy packing. + +typedef struct +{ + float x0,y0,s0,t0; // top-left + float x1,y1,s1,t1; // bottom-right +} stbtt_aligned_quad; + +STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier +// Call GetBakedQuad with char_index = 'character - first_char', and it +// creates the quad you need to draw and advances the current position. +// +// The coordinate system used assumes y increases downwards. +// +// Characters will extend both above and below the current position; +// see discussion of "BASELINE" above. +// +// It's inefficient; you might want to c&p it and optimize it. + + + +////////////////////////////////////////////////////////////////////////////// +// +// NEW TEXTURE BAKING API +// +// This provides options for packing multiple fonts into one atlas, not +// perfectly but better than nothing. + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; + float xoff2,yoff2; +} stbtt_packedchar; + +typedef struct stbtt_pack_context stbtt_pack_context; +typedef struct stbtt_fontinfo stbtt_fontinfo; +#ifndef STB_RECT_PACK_VERSION +typedef struct stbrp_rect stbrp_rect; +#endif + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); +// Initializes a packing context stored in the passed-in stbtt_pack_context. +// Future calls using this context will pack characters into the bitmap passed +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is +// the distance from one row to the next (or 0 to mean they are packed tightly +// together). "padding" is the amount of padding to leave between each +// character (normally you want '1' for bitmaps you'll use as textures with +// bilinear filtering). +// +// Returns 0 on failure, 1 on success. + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); +// Cleans up the packing context and frees all memory. + +#define STBTT_POINT_SIZE(x) (-(x)) + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size, + int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); +// Creates character bitmaps from the font_index'th font found in fontdata (use +// font_index=0 if you don't know what that is). It creates num_chars_in_range +// bitmaps for characters with unicode values starting at first_unicode_char_in_range +// and increasing. Data for how to render them is stored in chardata_for_range; +// pass these to stbtt_GetPackedQuad to get back renderable quads. +// +// font_size is the full height of the character from ascender to descender, +// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed +// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() +// and pass that result as 'font_size': +// ..., 20 , ... // font max minus min y is 20 pixels tall +// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall + +typedef struct +{ + float font_size; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; + stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally +} stbtt_pack_range; + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); +// Creates character bitmaps from multiple ranges of characters stored in +// ranges. This will usually create a better-packed bitmap than multiple +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); +// Oversampling a font increases the quality by allowing higher-quality subpixel +// positioning, and is especially valuable at smaller text sizes. +// +// This function sets the amount of oversampling for all following calls to +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is +// h_oversample*v_oversample larger than the default; for example, 2x2 +// oversampling requires 4x the storage of 1x1. For best results, render +// oversampled textures with bilinear filtering. Look at the readme in +// stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. + +STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int align_to_integer); + +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + +// this is an opaque structure that you shouldn't mess with which holds +// all the context needed from PackBegin to PackEnd. +struct stbtt_pack_context { + void *user_allocator_context; + void *pack_info; + int width; + int height; + int stride_in_bytes; + int padding; + unsigned int h_oversample, v_oversample; + unsigned char *pixels; + void *nodes; +}; + +////////////////////////////////////////////////////////////////////////////// +// +// FONT LOADING +// +// + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); +// Each .ttf/.ttc file may have more than one font. Each font has a sequential +// index number starting from 0. Call this function to get the font offset for +// a given index; it returns -1 if the index is out of range. A regular .ttf +// file will only define one font and it always be at offset 0, so it will +// return '0' for index 0, and -1 for all other indices. + +// The following structure is defined publically so you can declare one on +// the stack or as a global or etc, but you should treat it as opaque. +struct stbtt_fontinfo +{ + void * userdata; + unsigned char * data; // pointer to .ttf file + int fontstart; // offset of start of font + + int numGlyphs; // number of glyphs, needed for range checking + + int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf + int index_map; // a cmap mapping for our chosen character encoding + int indexToLocFormat; // format needed to map from glyph index to glyph + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); +// Given an offset into the file that defines a font, this function builds +// the necessary cached info for the rest of the system. You must allocate +// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't +// need to do anything special to free it, because the contents are pure +// value data with no additional data structures. Returns 0 on failure. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER TO GLYPH-INDEX CONVERSIOn + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); +// If you're going to perform multiple operations on the same character +// and you want a speed-up, call this function with the character you're +// going to process, then use glyph-based functions instead of the +// codepoint-based functions. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER PROPERTIES +// + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose "height" is 'pixels' tall. +// Height is measured as the distance from the highest ascender to the lowest +// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +// and computing: +// scale = pixels / (ascent - descent) +// so if you prefer to measure height by the ascent only, use a similar calculation. + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose EM size is mapped to +// 'pixels' tall. This is probably what traditional APIs compute, but +// I'm not positive. + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); +// ascent is the coordinate above the baseline the font extends; descent +// is the coordinate below the baseline the font extends (i.e. it is typically negative) +// lineGap is the spacing between one row's descent and the next row's ascent... +// so you should advance the vertical position by "*ascent - *descent + *lineGap" +// these are expressed in unscaled coordinates, so you must multiply by +// the scale factor for a given size + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); +// the bounding box around all possible characters + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); +// leftSideBearing is the offset from the current horizontal position to the left edge of the character +// advanceWidth is the offset from the current horizontal position to the next horizontal position +// these are expressed in unscaled coordinates + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); +// an additional amount to add to the 'advance' value between ch1 and ch2 + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); +// Gets the bounding box of the visible part of the glyph, in unscaled coordinates + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); +// as above, but takes one or more glyph indices for greater efficiency + + +////////////////////////////////////////////////////////////////////////////// +// +// GLYPH SHAPES (you probably don't need these, but they have to go before +// the bitmaps for C declaration-order reasons) +// + +#ifndef STBTT_vmove // you can predefine these to use different values (but why?) + enum { + STBTT_vmove=1, + STBTT_vline, + STBTT_vcurve, + STBTT_vcubic + }; +#endif + +#ifndef stbtt_vertex // you can predefine this to use different values + // (we share this with other code at RAD) + #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file + typedef struct + { + stbtt_vertex_type x,y,cx,cy,cx1,cy1; + unsigned char type,padding; + } stbtt_vertex; +#endif + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); +// returns non-zero if nothing is drawn for this glyph + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); +// returns # of vertices and fills *vertices with the pointer to them +// these are expressed in "unscaled" coordinates +// +// The shape is a series of countours. Each one starts with +// a STBTT_moveto, then consists of a series of mixed +// STBTT_lineto and STBTT_curveto segments. A lineto +// draws a line from previous endpoint to its x,y; a curveto +// draws a quadratic bezier from previous endpoint to +// its x,y, using cx,cy as the bezier control point. + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); +// frees the data allocated above + +////////////////////////////////////////////////////////////////////////////// +// +// BITMAP RENDERING +// + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); +// frees the bitmap allocated below + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// allocates a large-enough single-channel 8bpp bitmap and renders the +// specified character/glyph at the specified scale into it, with +// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). +// *width & *height are filled out with the width & height of the bitmap, +// which is stored left-to-right, top-to-bottom. +// +// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); +// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap +// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the +// width and height and positioning info for it first. + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); +// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +// get the bbox of the bitmap centered around the glyph origin; so the +// bitmap width is ix1-ix0, height is iy1-iy0, and location to place +// the bitmap top left is (leftSideBearing*scale,iy0). +// (Note that the bitmap uses y-increases-down, but the shape uses +// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); +// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel +// shift for the character + +// the following functions are equivalent to the above functions, but operate +// on glyph indices instead of Unicode codepoints (for efficiency) +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); + + +// @TODO: don't expose this structure +typedef struct +{ + int w,h,stride; + unsigned char *pixels; +} stbtt__bitmap; + +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC + +////////////////////////////////////////////////////////////////////////////// +// +// Finding the right font... +// +// You should really just solve this offline, keep your own tables +// of what font is what, and don't try to get it out of the .ttf file. +// That's because getting it out of the .ttf file is really hard, because +// the names in the file can appear in many possible encodings, in many +// possible languages, and e.g. if you need a case-insensitive comparison, +// the details of that depend on the encoding & language in a complex way +// (actually underspecified in truetype, but also gigantic). +// +// But you can use the provided functions in two possible ways: +// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on +// unicode-encoded names to try to find the font you want; +// you can run this before calling stbtt_InitFont() +// +// stbtt_GetFontNameString() lets you get any of the various strings +// from the file yourself and do your own comparisons on them. +// You have to have called stbtt_InitFont() first. + + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); +// returns the offset (not index) of the font that matches, or -1 if none +// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". +// if you use any other flag, use a font name like "Arial"; this checks +// the 'macStyle' header field; i don't know if fonts set this consistently +#define STBTT_MACSTYLE_DONTCARE 0 +#define STBTT_MACSTYLE_BOLD 1 +#define STBTT_MACSTYLE_ITALIC 2 +#define STBTT_MACSTYLE_UNDERSCORE 4 +#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); +// returns 1/0 whether the first string interpreted as utf8 is identical to +// the second string interpreted as big-endian utf16... useful for strings from next func + +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); +// returns the string (which may be big-endian double byte, e.g. for unicode) +// and puts the length in bytes in *length. +// +// some of the values for the IDs are below; for more see the truetype spec: +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html +// http://www.microsoft.com/typography/otspec/name.htm + +enum { // platformID + STBTT_PLATFORM_ID_UNICODE =0, + STBTT_PLATFORM_ID_MAC =1, + STBTT_PLATFORM_ID_ISO =2, + STBTT_PLATFORM_ID_MICROSOFT =3 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_UNICODE + STBTT_UNICODE_EID_UNICODE_1_0 =0, + STBTT_UNICODE_EID_UNICODE_1_1 =1, + STBTT_UNICODE_EID_ISO_10646 =2, + STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, + STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT + STBTT_MS_EID_SYMBOL =0, + STBTT_MS_EID_UNICODE_BMP =1, + STBTT_MS_EID_SHIFTJIS =2, + STBTT_MS_EID_UNICODE_FULL =10 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes + STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, + STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, + STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, + STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 +}; + +enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... + // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs + STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, + STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, + STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, + STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, + STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, + STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D +}; + +enum { // languageID for STBTT_PLATFORM_ID_MAC + STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, + STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, + STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, + STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , + STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , + STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, + STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 +}; + +#ifdef __cplusplus +} +#endif + +#endif // __STB_INCLUDE_STB_TRUETYPE_H__ + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// IMPLEMENTATION +//// +//// + +#ifdef STB_TRUETYPE_IMPLEMENTATION + +#ifndef STBTT_MAX_OVERSAMPLE +#define STBTT_MAX_OVERSAMPLE 8 +#endif + +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + +typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; + +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + int v, b0 = stbtt__buf_peek8(b); + STBTT_assert(b0 >= 28); + if (b0 == 30) { + stbtt__buf_skip(b, 1); + while (b->cursor < b->size) { + v = stbtt__buf_get8(b); + if ((v & 0xF) == 0xF || (v >> 4) == 0xF) + break; + } + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) +{ + stbtt__buf_seek(b, 0); + while (b->cursor < b->size) { + int start = b->cursor, end, op; + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + end = b->cursor; + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end-start); + } + return stbtt__buf_range(b, 0, 0); +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) +{ + int i; + stbtt__buf operands = stbtt__dict_get(b, key); + for (i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + STBTT_assert(i >= 0 && i < count); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + +////////////////////////////////////////////////////////////////////////// +// +// accessors to parse data from file +// + +// on platforms that don't allow misaligned reads, if we want to allow +// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE + +#define ttBYTE(p) (* (stbtt_uint8 *) (p)) +#define ttCHAR(p) (* (stbtt_int8 *) (p)) +#define ttFixed(p) ttLONG(p) + +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } + +#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) +#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) + +static int stbtt__isfont(stbtt_uint8 *font) +{ + // check the version number + if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 + if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! + if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF + if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts + return 0; +} + +// @OPTIMIZE: binary search +static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) +{ + stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + stbtt_uint32 tabledir = fontstart + 12; + stbtt_int32 i; + for (i=0; i < num_tables; ++i) { + stbtt_uint32 loc = tabledir + 16*i; + if (stbtt_tag(data+loc+0, tag)) + return ttULONG(data+loc+8); + } + return 0; +} + +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) +{ + // if it's just a font, there's only one valid index + if (stbtt__isfont(font_collection)) + return index == 0 ? 0 : -1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + stbtt_int32 n = ttLONG(font_collection+8); + if (index >= n) + return -1; + return ttULONG(font_collection+12+index*4); + } + } + return -1; +} + +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) +{ + stbtt_uint32 cmap, t; + stbtt_int32 i,numTables; + + info->data = data; + info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); + + cmap = stbtt__find_table(data, fontstart, "cmap"); // required + info->loca = stbtt__find_table(data, fontstart, "loca"); // required + info->head = stbtt__find_table(data, fontstart, "head"); // required + info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required + info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required + info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->kern = stbtt__find_table(data, fontstart, "kern"); // not required + + if (!cmap || !info->head || !info->hhea || !info->hmtx) + return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } + + t = stbtt__find_table(data, fontstart, "maxp"); + if (t) + info->numGlyphs = ttUSHORT(data+t+4); + else + info->numGlyphs = 0xffff; + + // find a cmap encoding table we understand *now* to avoid searching + // later. (todo: could make this installable) + // the same regardless of glyph. + numTables = ttUSHORT(data + cmap + 2); + info->index_map = 0; + for (i=0; i < numTables; ++i) { + stbtt_uint32 encoding_record = cmap + 4 + 8 * i; + // find an encoding we understand: + switch(ttUSHORT(data+encoding_record)) { + case STBTT_PLATFORM_ID_MICROSOFT: + switch (ttUSHORT(data+encoding_record+2)) { + case STBTT_MS_EID_UNICODE_BMP: + case STBTT_MS_EID_UNICODE_FULL: + // MS/Unicode + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + break; + case STBTT_PLATFORM_ID_UNICODE: + // Mac/iOS has these + // all the encodingIDs are unicode, so we don't bother to check it + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + } + if (info->index_map == 0) + return 0; + + info->indexToLocFormat = ttUSHORT(data+info->head + 50); + return 1; +} + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) +{ + stbtt_uint8 *data = info->data; + stbtt_uint32 index_map = info->index_map; + + stbtt_uint16 format = ttUSHORT(data + index_map + 0); + if (format == 0) { // apple byte encoding + stbtt_int32 bytes = ttUSHORT(data + index_map + 2); + if (unicode_codepoint < bytes-6) + return ttBYTE(data + index_map + 6 + unicode_codepoint); + return 0; + } else if (format == 6) { + stbtt_uint32 first = ttUSHORT(data + index_map + 6); + stbtt_uint32 count = ttUSHORT(data + index_map + 8); + if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) + return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); + return 0; + } else if (format == 2) { + STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean + return 0; + } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges + stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; + stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; + stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); + stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; + + // do a binary search of the segments + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + if (unicode_codepoint > 0xffff) + return 0; + + // they lie from endCount .. endCount + segCount + // but searchRange is the nearest power of two, so... + if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) + search += rangeShift*2; + + // now decrement to bias correctly to find smallest + search -= 2; + while (entrySelector) { + stbtt_uint16 end; + searchRange >>= 1; + end = ttUSHORT(data + search + searchRange*2); + if (unicode_codepoint > end) + search += searchRange*2; + --entrySelector; + } + search += 2; + + { + stbtt_uint16 offset, start; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + + STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + if (unicode_codepoint < start) + return 0; + + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + } + } else if (format == 12 || format == 13) { + stbtt_uint32 ngroups = ttULONG(data+index_map+12); + stbtt_int32 low,high; + low = 0; high = (stbtt_int32)ngroups; + // Binary search the right group. + while (low < high) { + stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high + stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); + stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); + if ((stbtt_uint32) unicode_codepoint < start_char) + high = mid; + else if ((stbtt_uint32) unicode_codepoint > end_char) + low = mid+1; + else { + stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); + if (format == 12) + return start_glyph + unicode_codepoint-start_char; + else // format == 13 + return start_glyph; + } + } + return 0; // not found + } + // @TODO + STBTT_assert(0); + return 0; +} + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) +{ + return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); +} + +static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) +{ + v->type = type; + v->x = (stbtt_int16) x; + v->y = (stbtt_int16) y; + v->cx = (stbtt_int16) cx; + v->cy = (stbtt_int16) cy; +} + +static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) +{ + int g1,g2; + + STBTT_assert(!info->cff.size); + + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range + if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format + + if (info->indexToLocFormat == 0) { + g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; + g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; + } else { + g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); + g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); + } + + return g1==g2 ? -1 : g1; // if length is 0, return -1 +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + if (info->cff.size) { + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; + + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } + return 1; +} + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) +{ + return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); +} + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt_int16 numberOfContours; + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 1; + numberOfContours = ttSHORT(info->data + g); + return numberOfContours == 0; +} + +static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, + stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) +{ + if (start_off) { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); + } + return num_vertices; +} + +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + stbtt_int16 numberOfContours; + stbtt_uint8 *endPtsOfContours; + stbtt_uint8 *data = info->data; + stbtt_vertex *vertices=0; + int num_vertices=0; + int g = stbtt__GetGlyfOffset(info, glyph_index); + + *pvertices = NULL; + + if (g < 0) return 0; + + numberOfContours = ttSHORT(data + g); + + if (numberOfContours > 0) { + stbtt_uint8 flags=0,flagcount; + stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; + stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; + stbtt_uint8 *points; + endPtsOfContours = (data + g + 10); + ins = ttUSHORT(data + g + 10 + numberOfContours * 2); + points = data + g + 10 + numberOfContours * 2 + 2 + ins; + + n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); + + m = n + 2*numberOfContours; // a loose bound on how many vertices we might need + vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); + if (vertices == 0) + return 0; + + next_move = 0; + flagcount=0; + + // in first pass, we load uninterpreted data into the allocated array + // above, shifted to the end of the array so we won't overwrite it when + // we create our final data starting from the front + + off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated + + // first load flags + + for (i=0; i < n; ++i) { + if (flagcount == 0) { + flags = *points++; + if (flags & 8) + flagcount = *points++; + } else + --flagcount; + vertices[off+i].type = flags; + } + + // now load x coordinates + x=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 2) { + stbtt_int16 dx = *points++; + x += (flags & 16) ? dx : -dx; // ??? + } else { + if (!(flags & 16)) { + x = x + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].x = (stbtt_int16) x; + } + + // now load y coordinates + y=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 4) { + stbtt_int16 dy = *points++; + y += (flags & 32) ? dy : -dy; // ??? + } else { + if (!(flags & 32)) { + y = y + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].y = (stbtt_int16) y; + } + + // now convert them to our format + num_vertices=0; + sx = sy = cx = cy = scx = scy = 0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + x = (stbtt_int16) vertices[off+i].x; + y = (stbtt_int16) vertices[off+i].y; + + if (next_move == i) { + if (i != 0) + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + + // now start the new one + start_off = !(flags & 1); + if (start_off) { + // if we start off with an off-curve point, then when we need to find a point on the curve + // where we can start, and we need to save some state for when we wraparound. + scx = x; + scy = y; + if (!(vertices[off+i+1].type & 1)) { + // next point is also a curve point, so interpolate an on-point curve + sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; + sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; + } else { + // otherwise just use the next point as our start point + sx = (stbtt_int32) vertices[off+i+1].x; + sy = (stbtt_int32) vertices[off+i+1].y; + ++i; // we're using point i+1 as the starting point, so skip it + } + } else { + sx = x; + sy = y; + } + stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); + was_off = 0; + next_move = 1 + ttUSHORT(endPtsOfContours+j*2); + ++j; + } else { + if (!(flags & 1)) { // if it's a curve + if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); + cx = x; + cy = y; + was_off = 1; + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); + was_off = 0; + } + } + } + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + } else if (numberOfContours == -1) { + // Compound shapes. + int more = 1; + stbtt_uint8 *comp = data + g + 10; + num_vertices = 0; + vertices = 0; + while (more) { + stbtt_uint16 flags, gidx; + int comp_num_verts = 0, i; + stbtt_vertex *comp_verts = 0, *tmp = 0; + float mtx[6] = {1,0,0,1,0,0}, m, n; + + flags = ttSHORT(comp); comp+=2; + gidx = ttSHORT(comp); comp+=2; + + if (flags & 2) { // XY values + if (flags & 1) { // shorts + mtx[4] = ttSHORT(comp); comp+=2; + mtx[5] = ttSHORT(comp); comp+=2; + } else { + mtx[4] = ttCHAR(comp); comp+=1; + mtx[5] = ttCHAR(comp); comp+=1; + } + } + else { + // @TODO handle matching point + STBTT_assert(0); + } + if (flags & (1<<3)) { // WE_HAVE_A_SCALE + mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } + + // Find transformation scales. + m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); + n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + + // Get indexed glyph. + comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); + if (comp_num_verts > 0) { + // Transform vertices. + for (i = 0; i < comp_num_verts; ++i) { + stbtt_vertex* v = &comp_verts[i]; + stbtt_vertex_type x,y; + x=v->x; y=v->y; + v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + x=v->cx; y=v->cy; + v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); + } + // Append vertices. + tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); + if (!tmp) { + if (vertices) STBTT_free(vertices, info->userdata); + if (comp_verts) STBTT_free(comp_verts, info->userdata); + return 0; + } + if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); + STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); + if (vertices) STBTT_free(vertices, info->userdata); + vertices = tmp; + STBTT_free(comp_verts, info->userdata); + num_vertices += comp_num_verts; + } + // More components ? + more = flags & (1<<5); + } + } else if (numberOfContours < 0) { + // @TODO other compound variations? + STBTT_assert(0); + } else { + // numberOfCounters == 0, do nothing + } + + *pvertices = vertices; + return num_vertices; +} + +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) stbtt__new_buf(NULL, 0); + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // fallthrough + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) { + *x0 = r ? c.min_x : 0; + *y0 = r ? c.min_y : 0; + *x1 = r ? c.max_x : 0; + *y1 = r ? c.max_y : 0; + } + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) +{ + stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + if (glyph_index < numOfLongHorMetrics) { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); + } else { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); + } +} + +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint8 *data = info->data + info->kern; + stbtt_uint32 needle, straw; + int l, r, m; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + l = 0; + r = ttUSHORT(data+10) - 1; + needle = glyph1 << 16 | glyph2; + while (l <= r) { + m = (l + r) >> 1; + straw = ttULONG(data+18+(m*6)); // note: unaligned read + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else + return ttSHORT(data+22+(m*6)); + } + return 0; +} + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) +{ + if (!info->kern) // if no kerning table, don't waste time looking up both codepoint->glyphs + return 0; + return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); +} + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) +{ + stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); +} + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) +{ + if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); + if (descent) *descent = ttSHORT(info->data+info->hhea + 6); + if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); +} + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) +{ + *x0 = ttSHORT(info->data + info->head + 36); + *y0 = ttSHORT(info->data + info->head + 38); + *x1 = ttSHORT(info->data + info->head + 40); + *y1 = ttSHORT(info->data + info->head + 42); +} + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) +{ + int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + return (float) height / fheight; +} + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) +{ + int unitsPerEm = ttUSHORT(info->data + info->head + 18); + return pixels / unitsPerEm; +} + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) +{ + STBTT_free(v, info->userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// antialiasing software rasterizer +// + +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning + if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { + // e.g. space character + if (ix0) *ix0 = 0; + if (iy0) *iy0 = 0; + if (ix1) *ix1 = 0; + if (iy1) *iy1 = 0; + } else { + // move to integral bboxes (treating pixels as little squares, what pixels get touched)? + if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); + if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); + if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); + if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); + } +} + +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + +typedef struct stbtt__edge { + float x0,y0, x1,y1; + int invert; +} stbtt__edge; + + +typedef struct stbtt__active_edge +{ + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 + int x,dx; + float ey; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif +} stbtt__active_edge; + +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) + +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + if (!z) return z; + + // round dx down to avoid overshooting + if (dxdy < 0) + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); + else + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + + z->ey = e->y1; + z->next = 0; + z->direction = e->invert ? 1 : -1; + return z; +} +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#if STBTT_RASTERIZER_VERSION == 1 +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) +{ + // non-zero winding fill + int x0=0, w=0; + + while (e) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->direction; + } else { + int x1 = e->x; w += e->direction; + // if we went to zero, we need to draw + if (w == 0) { + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; + + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = scanline[i] + (stbtt_uint8) max_weight; + } + } + } + } + + e = e->next; + } +} + +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0; + int max_weight = (255 / vsubsample); // weight per vertical scanline + int s; // vertical subsample index + unsigned char scanline_data[512], *scanline; + + if (result->w > 512) + scanline = (unsigned char *) STBTT_malloc(result->w, userdata); + else + scanline = scanline_data; + + y = off_y * vsubsample; + e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; + + while (j < result->h) { + STBTT_memset(scanline, 0, result->w); + for (s=0; s < vsubsample; ++s) { + // find center of pixel for this scanline + float scan_y = y + 0.5f; + stbtt__active_edge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for(;;) { + int changed=0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + stbtt__active_edge *t = *step; + stbtt__active_edge *q = t->next; + + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e->y0 <= scan_y) { + if (e->y1 > scan_y) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + } + ++e; + } + + // now process all active edges in XOR fashion + if (active) + stbtt__fill_active_edges(scanline, result->w, active, max_weight); + + ++y; + } + STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = sy1 - sy0; + STBTT_assert(x >= 0 && x < len); + scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; + scanline_fill[x] += e->direction * height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = (x1+1 - x0) * dy + y_top; + + sign = e->direction; + // area of the rectangle covered from y0..y_crossing + area = sign * (y_crossing-sy0); + // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) + scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2); + + step = sign * dy; + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; + area += step; + } + y_crossing += dy * (x2 - (x1+1)); + + STBTT_assert(STBTT_fabs(area) <= 1.01f); + + scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing); + + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clear pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + float y1,y2; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + y1 = (x - x0) / dx + y_top; + y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + STBTT__NOTUSED(vsubsample); + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + STBTT_assert(z->ey >= scan_y_top); + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshhold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); +} + +typedef struct +{ + float x,y; +} stbtt__point; + +static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) +{ + float y_scale_inv = invert ? -scale_y : scale_y; + stbtt__edge *e; + int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 + int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + // vsubsample should divide 255 evenly; otherwise we won't reach full opacity + + // now we have to blow out the windings into explicit edge lists + n = 0; + for (i=0; i < windings; ++i) + n += wcount[i]; + + e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel + if (e == 0) return; + n = 0; + + m=0; + for (i=0; i < windings; ++i) { + stbtt__point *p = pts + m; + m += wcount[i]; + j = wcount[i]-1; + for (k=0; k < wcount[i]; j=k++) { + int a=k,b=j; + // skip the edge if horizontal + if (p[j].y == p[k].y) + continue; + // add edge from j to k to the list + e[n].invert = 0; + if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { + e[n].invert = 1; + a=j,b=k; + } + e[n].x0 = p[a].x * scale_x + shift_x; + e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; + e[n].x1 = p[b].x * scale_x + shift_x; + e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; + ++n; + } + } + + // now sort the edges by their highest point (should snap to integer, and then by x) + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); + + // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule + stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); + + STBTT_free(e, userdata); +} + +static void stbtt__add_point(stbtt__point *points, int n, float x, float y) +{ + if (!points) return; // during first pass, it's unallocated + points[n].x = x; + points[n].y = y; +} + +// tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching +static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) +{ + // midpoint + float mx = (x0 + 2*x1 + x2)/4; + float my = (y0 + 2*y1 + y2)/4; + // versus directly drawn line + float dx = (x0+x2)/2 - mx; + float dy = (y0+y2)/2 - my; + if (n > 16) // 65536 segments on one curve better be enough! + return 1; + if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA + stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x2,y2); + *num_points = *num_points+1; + } + return 1; +} + +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + +// returns number of contours +static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) +{ + stbtt__point *points=0; + int num_points=0; + + float objspace_flatness_squared = objspace_flatness * objspace_flatness; + int i,n=0,start=0, pass; + + // count how many "moves" there are to get the contour count + for (i=0; i < num_verts; ++i) + if (vertices[i].type == STBTT_vmove) + ++n; + + *num_contours = n; + if (n == 0) return 0; + + *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); + + if (*contour_lengths == 0) { + *num_contours = 0; + return 0; + } + + // make two passes through the points so we don't need to realloc + for (pass=0; pass < 2; ++pass) { + float x=0,y=0; + if (pass == 1) { + points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); + if (points == NULL) goto error; + } + num_points = 0; + n= -1; + for (i=0; i < num_verts; ++i) { + switch (vertices[i].type) { + case STBTT_vmove: + // start the next contour + if (n >= 0) + (*contour_lengths)[n] = num_points - start; + ++n; + start = num_points; + + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x,y); + break; + case STBTT_vline: + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x, y); + break; + case STBTT_vcurve: + stbtt__tesselate_curve(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + } + } + (*contour_lengths)[n] = num_points - start; + } + + return points; +error: + STBTT_free(points, userdata); + STBTT_free(*contour_lengths, userdata); + *contour_lengths = 0; + *num_contours = 0; + return NULL; +} + +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) +{ + float scale = scale_x > scale_y ? scale_y : scale_x; + int winding_count, *winding_lengths; + stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); + if (windings) { + stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); + STBTT_free(winding_lengths, userdata); + STBTT_free(windings, userdata); + } +} + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + int ix0,iy0,ix1,iy1; + stbtt__bitmap gbm; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); + + // now we get the size + gbm.w = (ix1 - ix0); + gbm.h = (iy1 - iy0); + gbm.pixels = NULL; // in case we error + + if (width ) *width = gbm.w; + if (height) *height = gbm.h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + if (gbm.w && gbm.h) { + gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); + if (gbm.pixels) { + gbm.stride = gbm.w; + + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); + } + } + STBTT_free(vertices, info->userdata); + return gbm.pixels; +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) +{ + int ix0,iy0; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt__bitmap gbm; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); + gbm.pixels = output; + gbm.w = out_w; + gbm.h = out_h; + gbm.stride = out_stride; + + if (gbm.w && gbm.h) + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); + + STBTT_free(vertices, info->userdata); +} + +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) +{ + stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); +} + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-CRAPPY packing to keep source code small + +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata) +{ + float scale; + int x,y,bottom_y, i; + stbtt_fontinfo f; + f.userdata = NULL; + if (!stbtt_InitFont(&f, data, offset)) + return -1; + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + x=y=1; + bottom_y = 1; + + scale = stbtt_ScaleForPixelHeight(&f, pixel_height); + + for (i=0; i < num_chars; ++i) { + int advance, lsb, x0,y0,x1,y1,gw,gh; + int g = stbtt_FindGlyphIndex(&f, first_char + i); + stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); + stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); + gw = x1-x0; + gh = y1-y0; + if (x + gw + 1 >= pw) + y = bottom_y, x = 1; // advance to next row + if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row + return -i; + STBTT_assert(x+gw < pw); + STBTT_assert(y+gh < ph); + stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); + chardata[i].x0 = (stbtt_int16) x; + chardata[i].y0 = (stbtt_int16) y; + chardata[i].x1 = (stbtt_int16) (x + gw); + chardata[i].y1 = (stbtt_int16) (y + gh); + chardata[i].xadvance = scale * advance; + chardata[i].xoff = (float) x0; + chardata[i].yoff = (float) y0; + x = x + gw + 1; + if (y+gh+1 > bottom_y) + bottom_y = y+gh+1; + } + return bottom_y; +} + +STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) +{ + float d3d_bias = opengl_fillrule ? 0 : -0.5f; + float ipw = 1.0f / pw, iph = 1.0f / ph; + stbtt_bakedchar *b = chardata + char_index; + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + + q->x0 = round_x + d3d_bias; + q->y0 = round_y + d3d_bias; + q->x1 = round_x + b->x1 - b->x0 + d3d_bias; + q->y1 = round_y + b->y1 - b->y0 + d3d_bias; + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// rectangle packing replacement routines if you don't have stb_rect_pack.h +// + +#ifndef STB_RECT_PACK_VERSION + +typedef int stbrp_coord; + +//////////////////////////////////////////////////////////////////////////////////// +// // +// // +// COMPILER WARNING ?!?!? // +// // +// // +// if you get a compile warning due to these symbols being defined more than // +// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // +// // +//////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int width,height; + int x,y,bottom_y; +} stbrp_context; + +typedef struct +{ + unsigned char x; +} stbrp_node; + +struct stbrp_rect +{ + stbrp_coord x,y; + int id,w,h,was_packed; +}; + +static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) +{ + con->width = pw; + con->height = ph; + con->x = 0; + con->y = 0; + con->bottom_y = 0; + STBTT__NOTUSED(nodes); + STBTT__NOTUSED(num_nodes); +} + +static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) +{ + int i; + for (i=0; i < num_rects; ++i) { + if (con->x + rects[i].w > con->width) { + con->x = 0; + con->y = con->bottom_y; + } + if (con->y + rects[i].h > con->height) + break; + rects[i].x = con->x; + rects[i].y = con->y; + rects[i].was_packed = 1; + con->x += rects[i].w; + if (con->y + rects[i].h > con->bottom_y) + con->bottom_y = con->y + rects[i].h; + } + for ( ; i < num_rects; ++i) + rects[i].was_packed = 0; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If +// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) +{ + stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); + int num_nodes = pw - padding; + stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); + + if (context == NULL || nodes == NULL) { + if (context != NULL) STBTT_free(context, alloc_context); + if (nodes != NULL) STBTT_free(nodes , alloc_context); + return 0; + } + + spc->user_allocator_context = alloc_context; + spc->width = pw; + spc->height = ph; + spc->pixels = pixels; + spc->pack_info = context; + spc->nodes = nodes; + spc->padding = padding; + spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; + spc->h_oversample = 1; + spc->v_oversample = 1; + + stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); + + if (pixels) + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + + return 1; +} + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) +{ + STBTT_free(spc->nodes , spc->user_allocator_context); + STBTT_free(spc->pack_info, spc->user_allocator_context); +} + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) +{ + STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); + STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); + if (h_oversample <= STBTT_MAX_OVERSAMPLE) + spc->h_oversample = h_oversample; + if (v_oversample <= STBTT_MAX_OVERSAMPLE) + spc->v_oversample = v_oversample; +} + +#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) + +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_w = w - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < h; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < w; ++i) { + STBTT_assert(pixels[i] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i] = (unsigned char) (total / kernel_width); + } + + pixels += stride_in_bytes; + } +} + +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_h = h - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < w; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < h; ++i) { + STBTT_assert(pixels[i*stride_in_bytes] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + + pixels += 1; + } +} + +static float stbtt__oversample_shift(int oversample) +{ + if (!oversample) + return 0.0f; + + // The prefilter is a box filter of width "oversample", + // which shifts phase by (oversample - 1)/2 pixels in + // oversampled space. We want to shift in the opposite + // direction to counter this. + return (float)-(oversample - 1) / (2.0f * (float)oversample); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k; + + k=0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { + int x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + ++k; + } + } + + return k; +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k, return_value = 1; + + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + + k = 0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { + stbrp_rect *r = &rects[k]; + if (r->was_packed) { + stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; + int advance, lsb, x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbrp_coord pad = (stbrp_coord) spc->padding; + + // pad on left and top + r->x += pad; + r->y += pad; + r->w -= pad; + r->h -= pad; + stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); + stbtt_GetGlyphBitmapBox(info, glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + &x0,&y0,&x1,&y1); + stbtt_MakeGlyphBitmapSubpixel(info, + spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w - spc->h_oversample+1, + r->h - spc->v_oversample+1, + spc->stride_in_bytes, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + glyph); + + if (spc->h_oversample > 1) + stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->h_oversample); + + if (spc->v_oversample > 1) + stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->v_oversample); + + bc->x0 = (stbtt_int16) r->x; + bc->y0 = (stbtt_int16) r->y; + bc->x1 = (stbtt_int16) (r->x + r->w); + bc->y1 = (stbtt_int16) (r->y + r->h); + bc->xadvance = scale * advance; + bc->xoff = (float) x0 * recip_h + sub_x; + bc->yoff = (float) y0 * recip_v + sub_y; + bc->xoff2 = (x0 + r->w) * recip_h + sub_x; + bc->yoff2 = (y0 + r->h) * recip_v + sub_y; + } else { + return_value = 0; // if any fail, report failure + } + + ++k; + } + } + + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + + return return_value; +} + +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) +{ + stbtt_fontinfo info; + int i,j,n, return_value = 1; + //stbrp_context *context = (stbrp_context *) spc->pack_info; + stbrp_rect *rects; + + // flag all characters as NOT packed + for (i=0; i < num_ranges; ++i) + for (j=0; j < ranges[i].num_chars; ++j) + ranges[i].chardata_for_range[j].x0 = + ranges[i].chardata_for_range[j].y0 = + ranges[i].chardata_for_range[j].x1 = + ranges[i].chardata_for_range[j].y1 = 0; + + n = 0; + for (i=0; i < num_ranges; ++i) + n += ranges[i].num_chars; + + rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); + if (rects == NULL) + return 0; + + info.userdata = spc->user_allocator_context; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); + + n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); + + stbtt_PackFontRangesPackRects(spc, rects, n); + + return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + + STBTT_free(rects, spc->user_allocator_context); + return return_value; +} + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size, + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) +{ + stbtt_pack_range range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; + range.chardata_for_range = chardata_for_range; + range.font_size = font_size; + return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); +} + +STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) +{ + float ipw = 1.0f / pw, iph = 1.0f / ph; + stbtt_packedchar *b = chardata + char_index; + + if (align_to_integer) { + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + q->x0 = x; + q->y0 = y; + q->x1 = x + b->xoff2 - b->xoff; + q->y1 = y + b->yoff2 - b->yoff; + } else { + q->x0 = *xpos + b->xoff; + q->y0 = *ypos + b->yoff; + q->x1 = *xpos + b->xoff2; + q->y1 = *ypos + b->yoff2; + } + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + + +////////////////////////////////////////////////////////////////////////////// +// +// font name matching -- recommended not to use this +// + +// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) +{ + stbtt_int32 i=0; + + // convert utf16 to utf8 and compare the results while converting + while (len2) { + stbtt_uint16 ch = s2[0]*256 + s2[1]; + if (ch < 0x80) { + if (i >= len1) return -1; + if (s1[i++] != ch) return -1; + } else if (ch < 0x800) { + if (i+1 >= len1) return -1; + if (s1[i++] != 0xc0 + (ch >> 6)) return -1; + if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = s2[2]*256 + s2[3]; + if (i+3 >= len1) return -1; + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + if (s1[i++] != 0xf0 + (c >> 18)) return -1; + if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; + s2 += 2; // plus another 2 below + len2 -= 2; + } else if (ch >= 0xdc00 && ch < 0xe000) { + return -1; + } else { + if (i+2 >= len1) return -1; + if (s1[i++] != 0xe0 + (ch >> 12)) return -1; + if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; + } + s2 += 2; + len2 -= 2; + } + return i; +} + +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) +{ + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); +} + +// returns results in whatever encoding you request... but note that 2-byte encodings +// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return NULL; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) + && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { + *length = ttUSHORT(fc+loc+8); + return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + } + } + return NULL; +} + +static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) +{ + stbtt_int32 i; + stbtt_int32 count = ttUSHORT(fc+nm+2); + stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + stbtt_int32 id = ttUSHORT(fc+loc+6); + if (id == target_id) { + // find the encoding + stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); + + // is this a Unicode encoding? + if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { + stbtt_int32 slen = ttUSHORT(fc+loc+8); + stbtt_int32 off = ttUSHORT(fc+loc+10); + + // check if there's a prefix match + stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); + if (matchlen >= 0) { + // check for target_id+1 immediately following, with same encoding & language + if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { + slen = ttUSHORT(fc+loc+12+8); + off = ttUSHORT(fc+loc+12+10); + if (slen == 0) { + if (matchlen == nlen) + return 1; + } else if (matchlen < nlen && name[matchlen] == ' ') { + ++matchlen; + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + return 1; + } + } else { + // if nothing immediately following + if (matchlen == nlen) + return 1; + } + } + } + + // @TODO handle other encodings + } + } + return 0; +} + +static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) +{ + stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + stbtt_uint32 nm,hd; + if (!stbtt__isfont(fc+offset)) return 0; + + // check italics/bold/underline flags in macStyle... + if (flags) { + hd = stbtt__find_table(fc, offset, "head"); + if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; + } + + nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return 0; + + if (flags) { + // if we checked the macStyle flags, then just check the family and ignore the subfamily + if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } else { + if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } + + return 0; +} + +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) +{ + stbtt_int32 i; + for (i=0;;++i) { + stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); + if (off < 0) return off; + if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) + return off; + } +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// diff --git a/src/init.cpp b/src/init.cpp new file mode 100644 index 00000000..0f6516c9 --- /dev/null +++ b/src/init.cpp @@ -0,0 +1,17 @@ +/* + * init.cpp + * + * Created on: Jul 27, 2017 + * Author: nullifiedcat + */ + +#include "init.hpp" + +std::stack& init_stack() { + static std::stack stack; + return stack; +} + +InitRoutine::InitRoutine(void(*func)()) { + init_stack().push(func); +} diff --git a/src/init.hpp b/src/init.hpp new file mode 100644 index 00000000..92f6469f --- /dev/null +++ b/src/init.hpp @@ -0,0 +1,19 @@ +/* + * init.hpp + * + * Created on: Jul 27, 2017 + * Author: nullifiedcat + */ + +#pragma once + +#include "beforecheaders.h" +#include +#include "aftercheaders.h" + +std::stack& init_stack(); + +class InitRoutine { +public: + InitRoutine(void(*func)()); +}; diff --git a/src/interfaces.cpp b/src/interfaces.cpp index 5a1d1e06..0ea76c7c 100644 --- a/src/interfaces.cpp +++ b/src/interfaces.cpp @@ -48,9 +48,12 @@ IVRenderView* g_IVRenderView = nullptr; IMaterialSystem* g_IMaterialSystemHL = nullptr; IMoveHelperServer* g_IMoveHelperServer = nullptr; CBaseClientState* g_IBaseClientState = nullptr; +IGameEventManager* g_IGameEventManager = nullptr; +TFGCClientSystem* g_TFGCClientSystem = nullptr; +CHud* g_CHUD = nullptr; template -T* BruteforceInterface(std::string name, sharedobj::SharedObject* object, int start) { +T* BruteforceInterface(std::string name, sharedobj::SharedObject& object, int start = 0) { T* result = nullptr; std::stringstream stream; for (int i = start; i < 100; i++) { @@ -61,7 +64,7 @@ T* BruteforceInterface(std::string name, sharedobj::SharedObject* object, int st else if (i < 100) zeros = 1; for (int j = 0; j < zeros; j++) stream << '0'; stream << i; - result = reinterpret_cast(object->CreateInterface(stream.str())); + result = reinterpret_cast(object.CreateInterface(stream.str())); if (result) return result; } logging::Info("RIP Software: can't create interface %s!", name.c_str()); @@ -70,37 +73,70 @@ T* BruteforceInterface(std::string name, sharedobj::SharedObject* object, int st } void CreateInterfaces() { - g_ICvar = BruteforceInterface("VEngineCvar", sharedobj::vstdlib); - g_IEngine = BruteforceInterface("VEngineClient", sharedobj::engine); + g_ICvar = BruteforceInterface("VEngineCvar", sharedobj::vstdlib()); + g_IEngine = BruteforceInterface("VEngineClient", sharedobj::engine()); g_AppID = g_IEngine->GetAppID(); - g_IEntityList = BruteforceInterface("VClientEntityList", sharedobj::client); - g_IPanel = BruteforceInterface("VGUI_Panel", sharedobj::vgui2); - g_ISteamClient = BruteforceInterface("SteamClient", sharedobj::steamclient, 17); - g_ISurface = BruteforceInterface("VGUI_Surface", sharedobj::vguimatsurface); - g_IEventManager2 = BruteforceInterface("GAMEEVENTSMANAGER", sharedobj::engine, 2); - g_IBaseClient = BruteforceInterface("VClient", sharedobj::client); - g_ITrace = BruteforceInterface("EngineTraceClient", sharedobj::engine); - g_IModelInfo = BruteforceInterface("VModelInfoClient", sharedobj::engine); - g_IInputSystem = BruteforceInterface("InputSystemVersion", sharedobj::inputsystem); - g_IStudioRender = BruteforceInterface("VStudioRender", sharedobj::studiorender); - g_IVDebugOverlay = BruteforceInterface("VDebugOverlay", sharedobj::engine); + g_IEntityList = BruteforceInterface("VClientEntityList", sharedobj::client()); + g_ISteamClient = BruteforceInterface("SteamClient", sharedobj::steamclient(), 17); + g_IEventManager2 = BruteforceInterface("GAMEEVENTSMANAGER", sharedobj::engine(), 2); + g_IGameEventManager = BruteforceInterface("GAMEEVENTSMANAGER", sharedobj::engine(), 1); + g_IBaseClient = BruteforceInterface("VClient", sharedobj::client()); + g_ITrace = BruteforceInterface("EngineTraceClient", sharedobj::engine()); + g_IInputSystem = BruteforceInterface("InputSystemVersion", sharedobj::inputsystem()); HSteamPipe sp = g_ISteamClient->CreateSteamPipe(); HSteamUser su = g_ISteamClient->ConnectToGlobalUser(sp); - g_IVModelRender = BruteforceInterface("VEngineModel", sharedobj::engine, 16); + g_IVModelRender = BruteforceInterface("VEngineModel", sharedobj::engine(), 16); + g_ISteamFriends = nullptr; IF_GAME (IsTF2()) { uintptr_t sig_steamapi = gSignatures.GetEngineSignature("55 0F 57 C0 89 E5 83 EC 18 F3 0F 11 05 ? ? ? ? F3 0F 11 05 ? ? ? ? F3 0F 10 05 ? ? ? ? C7 04 24 ? ? ? ? F3 0F 11 05 ? ? ? ? F3 0F 11 05 ? ? ? ? E8 ? ? ? ? C7 44 24 08 ? ? ? ? C7 44 24 04 ? ? ? ? C7 04 24 ? ? ? ? E8 ? ? ? ? C9 C3"); logging::Info("SteamAPI: 0x%08x", sig_steamapi); void** SteamAPI_engine = *reinterpret_cast(sig_steamapi + 36); g_ISteamFriends = (ISteamFriends*)(SteamAPI_engine[1]);// - } else { + } + if (g_ISteamFriends == nullptr) { // FIXME SIGNATURE g_ISteamFriends = g_ISteamClient->GetISteamFriends(su, sp, "SteamFriends002"); } g_GlobalVars = **(reinterpret_cast((uintptr_t)11 + gSignatures.GetClientSignature("55 89 E5 83 EC ? 8B 45 08 8B 15 ? ? ? ? F3 0F 10"))); - g_IPrediction = BruteforceInterface("VClientPrediction", sharedobj::client); - g_IGameMovement = BruteforceInterface("GameMovement", sharedobj::client); - g_IVRenderView = BruteforceInterface("VEngineRenderView", sharedobj::engine); - g_IMaterialSystem = BruteforceInterface("VMaterialSystem", sharedobj::materialsystem); + g_IPrediction = BruteforceInterface("VClientPrediction", sharedobj::client()); + g_IGameMovement = BruteforceInterface("GameMovement", sharedobj::client()); + IF_GAME (IsTF2()) { + //g_IMoveHelper = *(reinterpret_cast(gSignatures.GetClientSignature("? ? ? ? 8B 10 89 04 24 FF 52 28 0F B7 CF 8B 10 89 4C 24 04 89 04 24 FF 52 1C 8B 13 89 1C 24 89 44 24 04 FF 92 74 05 00 00 8D 95 C8 FE FF FF C7 44 24 08 00 00 00 00"))); + } + IF_GAME (IsTF2()) { + g_IInput = **(reinterpret_cast((uintptr_t)1 + gSignatures.GetClientSignature("A1 ? ? ? ? C6 05 ? ? ? ? 01 8B 10 89 04 24 FF 92 B4 00 00 00 A1 ? ? ? ? 8B 10"))); + } else IF_GAME (IsTF2C()) { + g_IInput = **(reinterpret_cast((uintptr_t)1 + gSignatures.GetClientSignature("A1 ? ? ? ? C6 05 ? ? ? ? 01 8B 10 89 04 24 FF 92 A8 00 00 00 A1 ? ? ? ? 8B 10"))); + } else { + g_IInput = **(reinterpret_cast((uintptr_t)1 + gSignatures.GetClientSignature("A1 ? ? ? ? 8B 10 89 04 24 FF 52 78 A1 ? ? ? ? 8B 10"))); + } + g_ISteamUser = g_ISteamClient->GetISteamUser(su, sp, "SteamUser018"); + g_IModelInfo = BruteforceInterface("VModelInfoClient", sharedobj::engine()); + g_IBaseClientState = *(reinterpret_cast(gSignatures.GetEngineSignature("55 89 E5 83 EC 18 C7 44 24 04 01 00 00 00 C7 04 24 ? ? ? ? E8 ? ? ? ? C7 04 24 ? ? ? ? 89 44 24 04 E8 ? ? ? ? A1 ? ? ? ? 85 C0 74 15 A1 ? ? ? ? 8B 10 89 04 24 FF 52 38 C9 C3") + 17)); + logging::Info("BaseClientState: 0x%08x", g_IBaseClientState); + g_IAchievementMgr = g_IEngine->GetAchievementMgr(); + g_ISteamUserStats = g_ISteamClient->GetISteamUserStats(su, sp, "STEAMUSERSTATS_INTERFACE_VERSION011"); + IF_GAME (IsTF2()) { + uintptr_t sig = gSignatures.GetClientSignature("89 1C 24 D9 5D D4 FF 90 3C 01 00 00 89 C7 8B 06 89 34 24 C1 E7 08 FF 90 3C 01 00 00 09 C7 33 3D ? ? ? ? 39 BB 34 0B 00 00 74 0E 89 BB 34 0B 00 00 89 3C 24 E8 ? ? ? ? C7 44 24 04 0F 27 00 00"); + g_PredictionRandomSeed = *reinterpret_cast(sig + (uintptr_t)32); + } + IF_GAME (IsTF2()) { + uintptr_t gcsystem_sig = gSignatures.GetClientSignature("E8 ? ? ? ? C7 44 24 04 04 00 00 00 89 04 24 E8 ? ? ? ? E9 17 FF FF FF") + 1; + typedef TFGCClientSystem*(*func_t)(void); + logging::Info("GCSystem = 0x%08x", gcsystem_sig); + uintptr_t gcc_p = *(uintptr_t*)(gcsystem_sig); + func_t get_gc = (gcc_p + gcsystem_sig + 4); + logging::Info("GTFGCClientSystem() = 0x%08x", get_gc); + g_TFGCClientSystem = get_gc(); + } + g_IMaterialSystem = BruteforceInterface("VMaterialSystem", sharedobj::materialsystem()); + +#ifndef TEXTMODE + g_IVDebugOverlay = BruteforceInterface("VDebugOverlay", sharedobj::engine()); + g_IPanel = BruteforceInterface("VGUI_Panel", sharedobj::vgui2()); + g_ISurface = BruteforceInterface("VGUI_Surface", sharedobj::vguimatsurface()); + g_IStudioRender = BruteforceInterface("VStudioRender", sharedobj::studiorender()); + g_IVRenderView = BruteforceInterface("VEngineRenderView", sharedobj::engine()); g_IMaterialSystemHL = (IMaterialSystem*)g_IMaterialSystem; IF_GAME (IsTF2()) { g_pScreenSpaceEffects = **(IScreenSpaceEffectManager***)(gSignatures.GetClientSignature("F3 0F 10 83 40 05 00 00 C7 44 24 04 ? ? ? ? 89 34 24 F3 0F 11 44 24 08 E8 ? ? ? ? A1 ? ? ? ? 8B 10 89 04 24 89 74 24 08 C7 44 24 04 ? ? ? ? FF 52 0C A1 ? ? ? ? 8B 10 C7 44 24 04 ? ? ? ? 89 04 24 FF 52 14") + 31); @@ -113,25 +149,11 @@ void CreateInterfaces() { g_pScreenSpaceEffects = **(IScreenSpaceEffectManager***)(gSignatures.GetClientSignature("FF 52 14 E9 E0 FE FF FF 8D 76 00 A1 ? ? ? ? 8B 5D F4 8B 75 F8 8B 7D FC 8B 10 C7 45 0C ? ? ? ? 89 45 08 8B 42 1C 89 EC 5D FF E0") + 12); g_ppScreenSpaceRegistrationHead = *(CScreenSpaceEffectRegistration***)(gSignatures.GetClientSignature("E8 ? ? ? ? 8B 10 C7 44 24 04 ? ? ? ? 89 04 24 FF 52 28 85 C0 75 4B 8B 35 ? ? ? ? 85 F6 74 31 90 8B 5E 04 85 DB 74 22 8B 03 89 1C 24") + 27); } - IF_GAME (IsTF2()) { - //g_IMoveHelper = *(reinterpret_cast(gSignatures.GetClientSignature("? ? ? ? 8B 10 89 04 24 FF 52 28 0F B7 CF 8B 10 89 4C 24 04 89 04 24 FF 52 1C 8B 13 89 1C 24 89 44 24 04 FF 92 74 05 00 00 8D 95 C8 FE FF FF C7 44 24 08 00 00 00 00"))); - } - IF_GAME (IsTF2()) { - g_IInput = **(reinterpret_cast((uintptr_t)1 + gSignatures.GetClientSignature("A1 ? ? ? ? C6 05 ? ? ? ? 01 8B 10 89 04 24 FF 92 B4 00 00 00 A1 ? ? ? ? 8B 10"))); - } else IF_GAME (IsTF2C()) { - g_IInput = **(reinterpret_cast((uintptr_t)1 + gSignatures.GetClientSignature("A1 ? ? ? ? C6 05 ? ? ? ? 01 8B 10 89 04 24 FF 92 A8 00 00 00 A1 ? ? ? ? 8B 10"))); - } else { - g_IInput = **(reinterpret_cast((uintptr_t)1 + gSignatures.GetClientSignature("A1 ? ? ? ? 8B 10 89 04 24 FF 52 78 A1 ? ? ? ? 8B 10"))); - } - g_ISteamUser = g_ISteamClient->GetISteamUser(su, sp, "SteamUser018"); - g_IBaseClientState = *(reinterpret_cast(gSignatures.GetEngineSignature("55 89 E5 83 EC 18 C7 44 24 04 01 00 00 00 C7 04 24 ? ? ? ? E8 ? ? ? ? C7 04 24 ? ? ? ? 89 44 24 04 E8 ? ? ? ? A1 ? ? ? ? 85 C0 74 15 A1 ? ? ? ? 8B 10 89 04 24 FF 52 38 C9 C3") + 17)); - logging::Info("BaseClientState: 0x%08x", g_IBaseClientState); - g_IAchievementMgr = g_IEngine->GetAchievementMgr(); - g_ISteamUserStats = g_ISteamClient->GetISteamUserStats(su, sp, "STEAMUSERSTATS_INTERFACE_VERSION011"); - if (!g_PredictionRandomSeed) { - uintptr_t sig = gSignatures.GetClientSignature("89 1C 24 D9 5D D4 FF 90 3C 01 00 00 89 C7 8B 06 89 34 24 C1 E7 08 FF 90 3C 01 00 00 09 C7 33 3D ? ? ? ? 39 BB 34 0B 00 00 74 0E 89 BB 34 0B 00 00 89 3C 24 E8 ? ? ? ? C7 44 24 04 0F 27 00 00"); - logging::Info("Random Seed: 0x%08x", sig + 32); - logging::Info("Random Seed: 0x%08x", *(int**)(sig + 32)); - g_PredictionRandomSeed = *reinterpret_cast(sig + (uintptr_t)32); + logging::Info("Finding HUD"); + { + uintptr_t hud_sig = gSignatures.GetClientSignature("FF 50 08 D9 9D 24 FE FF FF 89 3C 24 E8 ? ? ? ? C7 44 24 04 ? ? ? ? C7 04 24 ? ? ? ? D9 9D 20 FE FF FF E8 ? ? ? ? 85 C0 74 3B 66 0F 6E C3 C7 44 24 10 00 00 00 00 F3 0F 5C 85 20 FE FF FF") + 28; + g_CHUD = *reinterpret_cast(hud_sig); + logging::Info("HUD 0x%08x 0x%08x", hud_sig, g_CHUD); } +#endif } diff --git a/src/interfaces.h b/src/interfaces.h index b32a082c..1407c5c3 100644 --- a/src/interfaces.h +++ b/src/interfaces.h @@ -49,7 +49,12 @@ class IMaterialSystemFixed; class IMaterialSystem; class IMoveHelperServer; class CBaseClientState; +class CHud; +class IGameEventManager; +class TFGCClientSystem; +extern TFGCClientSystem* g_TFGCClientSystem; +extern CHud* g_CHUD; extern ISteamClient* g_ISteamClient; extern ISteamFriends* g_ISteamFriends; extern IVEngineClient013* g_IEngine; @@ -77,9 +82,7 @@ extern IVModelRender* g_IVModelRender; extern IVRenderView* g_IVRenderView; extern IMoveHelperServer* g_IMoveHelperServer; extern CBaseClientState* g_IBaseClientState; - -template -T* BruteforceInterface(std::string name, sharedobj::SharedObject* object, int start = 0); +extern IGameEventManager* g_IGameEventManager; void CreateInterfaces(); diff --git a/src/ipc.cpp b/src/ipc.cpp index ce4bce6c..ec49303b 100644 --- a/src/ipc.cpp +++ b/src/ipc.cpp @@ -121,19 +121,94 @@ CatVar server_name(CV_STRING, "ipc_server", "cathook_followbot_server", "IPC ser peer_t* peer { nullptr }; -void StoreClientData() { +CatCommand debug_get_ingame_ipc("ipc_debug_dump_server", "Show other bots on server", []() { + std::vector players {}; + for (int j = 1; j < 32; j++) { + player_info_s info; + if (g_IEngine->GetPlayerInfo(j, &info)) { + if (info.friendsID) + players.push_back(info.friendsID); + } + } + int count = 0; + unsigned highest = 0; + std::vector botlist {}; + for (unsigned i = 1; i < cat_ipc::max_peers; i++) { + if (!ipc::peer->memory->peer_data[i].free) { + for (auto& k : players) { + if (ipc::peer->memory->peer_user_data[i].friendid && k == ipc::peer->memory->peer_user_data[i].friendid) { + botlist.push_back(i); + logging::Info("-> %u (%u)", i, ipc::peer->memory->peer_user_data[i].friendid); + count++; + highest = i; + } + } + } + } + logging::Info("%d other IPC players on server", count); +}); + +void UpdateServerAddress(bool shutdown) { + if (not peer) + return; + const char* s_addr = "0.0.0.0"; + if (not shutdown and g_IEngine->GetNetChannelInfo()) { + s_addr = g_IEngine->GetNetChannelInfo()->GetAddress(); + } + peer_t::MutexLock lock(peer); user_data_s& data = peer->memory->peer_user_data[peer->client_id]; data.friendid = g_ISteamUser->GetSteamID().GetAccountID(); - strncpy(data.name, g_ISteamFriends->GetPersonaName(), sizeof(data.name)); + strncpy(data.server, s_addr, sizeof(data.server)); } +void UpdateTemporaryData() { + user_data_s& data = peer->memory->peer_user_data[peer->client_id]; + data.connected = g_IEngine->IsInGame(); + if (data.connected) { + IClientEntity* player = g_IEntityList->GetClientEntity(g_IEngine->GetLocalPlayer()); + if (player) { + data.good = true; + data.health = NET_INT(player, netvar.iHealth); + data.health_max = g_pPlayerResource->GetMaxHealth(LOCAL_E); + data.clazz = g_pPlayerResource->GetClass(LOCAL_E); + data.life_state = NET_BYTE(player, netvar.iLifeState); + data.score = g_pPlayerResource->GetScore(g_IEngine->GetLocalPlayer()); + if (data.last_score != data.score) { + if (data.last_score > data.score) { + data.total_score += data.score; + } else { + data.total_score += (data.score - data.last_score); + } + data.last_score = data.score; + } + data.team = g_pPlayerResource->GetTeam(g_IEngine->GetLocalPlayer()); + } else { + data.good = false; + } + } +} + +void StoreClientData() { + UpdateServerAddress(); + user_data_s& data = peer->memory->peer_user_data[peer->client_id]; + data.friendid = g_ISteamUser->GetSteamID().GetAccountID(); + strncpy(data.name, GetFriendPersonaName_hook(g_ISteamFriends, g_ISteamUser->GetSteamID()), sizeof(data.name)); +} + + +void Heartbeat() { + user_data_s& data = peer->memory->peer_user_data[peer->client_id]; + data.heartbeat = time(nullptr); +} + +static CatVar ipc_update_list(CV_SWITCH, "ipc_update_list", "1", "IPC Auto-Ignore", "Automaticly assign playerstates for bots"); void UpdatePlayerlist() { - if (peer) { + if (peer && ipc_update_list) { for (unsigned i = 1; i < cat_ipc::max_peers; i++) { if (!peer->memory->peer_data[i].free) { playerlist::userdata& info = playerlist::AccessData(peer->memory->peer_user_data[i].friendid); - if (info.state != playerlist::k_EState::DEFAULT) + if (info.state == playerlist::k_EState::DEFAULT) info.state = playerlist::k_EState::IPC; } } diff --git a/src/ipc.h b/src/ipc.h index 5f7da201..9a3b7254 100644 --- a/src/ipc.h +++ b/src/ipc.h @@ -13,6 +13,7 @@ #include "beforecheaders.h" #include "ipcb.hpp" #include "pthread.h" +#include #include "aftercheaders.h" class CatCommand; @@ -47,13 +48,28 @@ struct server_data_s { struct user_data_s { char name[32]; + char server[22]; unsigned friendid; + bool connected; + bool good; + int health; + int health_max; + char life_state; + int team; + int clazz; + int score; + int last_score; + int total_score; + time_t heartbeat; }; using peer_t = cat_ipc::Peer; extern peer_t* peer; +void Heartbeat(); +void UpdateTemporaryData(); +void UpdateServerAddress(bool shutdown = false); void StoreClientData(); void UpdatePlayerlist(); diff --git a/src/itemtypes.cpp b/src/itemtypes.cpp index 05180f79..f6c7b1e5 100644 --- a/src/itemtypes.cpp +++ b/src/itemtypes.cpp @@ -61,6 +61,10 @@ ItemManager::ItemManager() : mapper() { RegisterModelMapping("models/items/healthkit.mdl", ITEM_HEALTH_MEDIUM); //RegisterModelMapping("models/pickups/pickup_powerup_reflect.mdl", ITEM_POWERUP_REFLECT); + // Spellbooks + RegisterModelMapping("models/props_halloween/hwn_spellbook_upright.mdl", ITEM_SPELL); + RegisterModelMapping("models/props_halloween/hwn_spellbook_upright_major.mdl", ITEM_SPELL_RARE); + RegisterSpecialMapping([](CachedEntity* ent) -> bool { return ent->m_iClassID == CL_CLASS(CTFAmmoPack); }, ITEM_AMMO_MEDIUM); diff --git a/src/itemtypes.h b/src/itemtypes.h index 3e47eab8..d6d2913f 100644 --- a/src/itemtypes.h +++ b/src/itemtypes.h @@ -144,6 +144,9 @@ enum k_EItemType { ITEM_HL_BATTERY, + ITEM_SPELL, + ITEM_SPELL_RARE, + ITEM_COUNT }; diff --git a/src/json.hpp b/src/json.hpp new file mode 100644 index 00000000..6dfc1831 --- /dev/null +++ b/src/json.hpp @@ -0,0 +1,13003 @@ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 2.1.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +Copyright (c) 2013-2017 Niels Lohmann . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +#ifndef NLOHMANN_JSON_HPP +#define NLOHMANN_JSON_HPP + +#include // all_of, copy, fill, find, for_each, none_of, remove, reverse, transform +#include // array +#include // assert +#include // isdigit +#include // and, not, or +#include // isfinite, labs, ldexp, signbit +#include // nullptr_t, ptrdiff_t, size_t +#include // int64_t, uint64_t +#include // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull +#include // strlen +#include // forward_list +#include // function, hash, less +#include // initializer_list +#include // setw +#include // istream, ostream +#include // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator +#include // numeric_limits +#include // locale +#include // map +#include // addressof, allocator, allocator_traits, unique_ptr +#include // accumulate +#include // stringstream +#include // domain_error, invalid_argument, out_of_range +#include // getline, stoi, string, to_string +#include // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type +#include // declval, forward, make_pair, move, pair, swap +#include // vector + +// exclude unsupported compilers +#if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif +#elif defined(__GNUC__) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif +#endif + +// disable float-equal warnings on GCC/clang +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" +#endif + +// allow for portable deprecation warnings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #define JSON_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) + #define JSON_DEPRECATED __declspec(deprecated) +#else + #define JSON_DEPRECATED +#endif + +// allow to disable exceptions +#if not defined(JSON_NOEXCEPTION) || defined(__EXCEPTIONS) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) +#else + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) +#endif + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ + +/*! +@brief unnamed namespace with internal helper functions + +This namespace collects some functions that could not be defined inside the +@ref basic_json class. + +@since version 2.1.0 +*/ +namespace detail +{ +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + discarded ///< discarded by the the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string +- furthermore, each type is not smaller than itself + +@since version 1.0.0 +*/ +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + static constexpr std::array order = {{ + 0, // null + 3, // object + 4, // array + 5, // string + 1, // boolean + 2, // integer + 2, // unsigned + 2, // float + } + }; + + // discarded values are not comparable + if (lhs == value_t::discarded or rhs == value_t::discarded) + { + return false; + } + + return order[static_cast(lhs)] < + order[static_cast(rhs)]; +} + + +///////////// +// helpers // +///////////// + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +template +using uncvref_t = typename std::remove_cv::type>::type; + +// taken from http://stackoverflow.com/a/26936864/266378 +template +using is_unscoped_enum = + std::integral_constant::value and + std::is_enum::value>; + +/* +Implementation of two C++17 constructs: conjunction, negation. This is needed +to avoid evaluating all the traits in a condition + +For example: not std::is_same::value and has_value_type::value +will not compile when T = void (on MSVC at least). Whereas +conjunction>, has_value_type>::value will +stop evaluating if negation<...>::value == false + +Please note that those constructs must be used with caution, since symbols can +become very long quickly (which can slow down compilation and cause MSVC +internal compiler errors). Only use it when you have to (see example ahead). +*/ +template struct conjunction : std::true_type {}; +template struct conjunction : B1 {}; +template +struct conjunction : std::conditional, B1>::type {}; + +template struct negation : std::integral_constant < bool, !B::value > {}; + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + + +////////////////// +// constructors // +////////////////// + +template struct external_constructor; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept + { + j.m_type = value_t::boolean; + j.m_value = b; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) + { + j.m_type = value_t::string; + j.m_value = s; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept + { + // replace infinity and NAN by null + if (not std::isfinite(val)) + { + j = BasicJsonType{}; + } + else + { + j.m_type = value_t::number_float; + j.m_value = val; + } + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept + { + j.m_type = value_t::number_unsigned; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept + { + j.m_type = value_t::number_integer; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) + { + j.m_type = value_t::array; + j.m_value = arr; + j.assert_invariant(); + } + + template::value, + int> = 0> + static void construct(BasicJsonType& j, const CompatibleArrayType& arr) + { + using std::begin; + using std::end; + j.m_type = value_t::array; + j.m_value.array = j.template create(begin(arr), end(arr)); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) + { + j.m_type = value_t::object; + j.m_value = obj; + j.assert_invariant(); + } + + template::value, + int> = 0> + static void construct(BasicJsonType& j, const CompatibleObjectType& obj) + { + using std::begin; + using std::end; + + j.m_type = value_t::object; + j.m_value.object = j.template create(begin(obj), end(obj)); + j.assert_invariant(); + } +}; + + +//////////////////////// +// has_/is_ functions // +//////////////////////// + +/*! +@brief Helper to determine whether there's a key_type for T. + +This helper is used to tell associative containers apart from other containers +such as sequence containers. For instance, `std::map` passes the test as it +contains a `mapped_type`, whereas `std::vector` fails the test. + +@sa http://stackoverflow.com/a/7728728/266378 +@since version 1.0.0, overworked in version 2.0.6 +*/ +#define NLOHMANN_JSON_HAS_HELPER(type) \ + template struct has_##type { \ + private: \ + template \ + static int detect(U &&); \ + static void detect(...); \ + public: \ + static constexpr bool value = \ + std::is_integral()))>::value; \ + } + +NLOHMANN_JSON_HAS_HELPER(mapped_type); +NLOHMANN_JSON_HAS_HELPER(key_type); +NLOHMANN_JSON_HAS_HELPER(value_type); +NLOHMANN_JSON_HAS_HELPER(iterator); + +#undef NLOHMANN_JSON_HAS_HELPER + + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl +{ + static constexpr auto value = + std::is_constructible::value and + std::is_constructible::value; +}; + +template +struct is_compatible_object_type +{ + static auto constexpr value = is_compatible_object_type_impl < + conjunction>, + has_mapped_type, + has_key_type>::value, + typename BasicJsonType::object_t, CompatibleObjectType >::value; +}; + +template +struct is_basic_json_nested_type +{ + static auto constexpr value = std::is_same::value or + std::is_same::value or + std::is_same::value or + std::is_same::value or + std::is_same::value; +}; + +template +struct is_compatible_array_type +{ + static auto constexpr value = + conjunction>, + negation>, + negation>, + negation>, + has_value_type, + has_iterator>::value; +}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + std::is_constructible::value and + CompatibleLimits::is_integer and + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type +{ + static constexpr auto value = + is_compatible_integer_type_impl < + std::is_integral::value and + not std::is_same::value, + RealIntegerType, CompatibleNumberIntegerType > ::value; +}; + + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json +{ + private: + // also check the return type of from_json + template::from_json( + std::declval(), std::declval()))>::value>> + static int detect(U&&); + static void detect(...); + + public: + static constexpr bool value = std::is_integral>()))>::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json +{ + private: + template < + typename U, + typename = enable_if_t::from_json(std::declval()))>::value >> + static int detect(U&&); + static void detect(...); + + public: + static constexpr bool value = std::is_integral>()))>::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +template +struct has_to_json +{ + private: + template::to_json( + std::declval(), std::declval()))> + static int detect(U&&); + static void detect(...); + + public: + static constexpr bool value = std::is_integral>()))>::value; +}; + + +///////////// +// to_json // +///////////// + +template::value, int> = 0> +void to_json(BasicJsonType& j, T b) noexcept +{ + external_constructor::construct(j, b); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const CompatibleString& s) +{ + external_constructor::construct(j, s); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, FloatType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template < + typename BasicJsonType, typename CompatibleNumberUnsignedType, + enable_if_t::value, int> = 0 > +void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template < + typename BasicJsonType, typename CompatibleNumberIntegerType, + enable_if_t::value, int> = 0 > +void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, UnscopedEnumType e) noexcept +{ + external_constructor::construct(j, e); +} + +template < + typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < + is_compatible_array_type::value or + std::is_same::value, + int > = 0 > +void to_json(BasicJsonType& j, const CompatibleArrayType& arr) +{ + external_constructor::construct(j, arr); +} + +template < + typename BasicJsonType, typename CompatibleObjectType, + enable_if_t::value, + int> = 0 > +void to_json(BasicJsonType& j, const CompatibleObjectType& arr) +{ + external_constructor::construct(j, arr); +} + + +/////////////// +// from_json // +/////////////// + +// overloads for basic_json template parameters +template::value and + not std::is_same::value, + int> = 0> +void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast( + *j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast( + *j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast( + *j.template get_ptr()); + break; + } + default: + { + JSON_THROW( + std::domain_error("type must be number, but is " + j.type_name())); + } + } +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) +{ + if (not j.is_boolean()) + { + JSON_THROW(std::domain_error("type must be boolean, but is " + j.type_name())); + } + b = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) +{ + if (not j.is_string()) + { + JSON_THROW(std::domain_error("type must be string, but is " + j.type_name())); + } + s = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) +{ + get_arithmetic_value(j, val); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, UnscopedEnumType& e) +{ + typename std::underlying_type::type val; + get_arithmetic_value(j, val); + e = static_cast(val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) +{ + if (not j.is_array()) + { + JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); + } + arr = *j.template get_ptr(); +} + +// forward_list doesn't have an insert method +template +void from_json(const BasicJsonType& j, std::forward_list& l) +{ + // do not perform the check when user wants to retrieve jsons + // (except when it's null.. ?) + if (j.is_null()) + { + JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); + } + if (not std::is_same::value) + { + if (not j.is_array()) + { + JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); + } + } + for (auto it = j.rbegin(), end = j.rend(); it != end; ++it) + { + l.push_front(it->template get()); + } +} + +template +void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0>) +{ + using std::begin; + using std::end; + + std::transform(j.begin(), j.end(), + std::inserter(arr, end(arr)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); +} + +template +auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1>) +-> decltype( + arr.reserve(std::declval()), + void()) +{ + using std::begin; + using std::end; + + arr.reserve(j.size()); + std::transform( + j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); +} + +template::value and + not std::is_same::value, int> = 0> +void from_json(const BasicJsonType& j, CompatibleArrayType& arr) +{ + if (j.is_null()) + { + JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); + } + + // when T == BasicJsonType, do not check if value_t is correct + if (not std::is_same::value) + { + if (not j.is_array()) + { + JSON_THROW(std::domain_error("type must be array, but is " + j.type_name())); + } + } + from_json_array_impl(j, arr, priority_tag<1> {}); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, CompatibleObjectType& obj) +{ + if (not j.is_object()) + { + JSON_THROW(std::domain_error("type must be object, but is " + j.type_name())); + } + + auto inner_object = j.template get_ptr(); + using std::begin; + using std::end; + // we could avoid the assignment, but this might require a for loop, which + // might be less efficient than the container constructor for some + // containers (would it?) + obj = CompatibleObjectType(begin(*inner_object), end(*inner_object)); +} + +// overload for arithmetic types, not chosen for basic_json template arguments +// (BooleanType, etc..); note: Is it really necessary to provide explicit +// overloads for boolean_t etc. in case of a custom BooleanType which is not +// an arithmetic type? +template::value and + not std::is_same::value and + not std::is_same::value and + not std::is_same::value and + not std::is_same::value, + int> = 0> +void from_json(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::boolean: + { + val = static_cast(*j.template get_ptr()); + break; + } + default: + { + JSON_THROW(std::domain_error("type must be number, but is " + j.type_name())); + } + } +} + +struct to_json_fn +{ + private: + template + auto call(BasicJsonType& j, T&& val, priority_tag<1>) const noexcept(noexcept(to_json(j, std::forward(val)))) + -> decltype(to_json(j, std::forward(val)), void()) + { + return to_json(j, std::forward(val)); + } + + template + void call(BasicJsonType&, T&&, priority_tag<0>) const noexcept + { + static_assert(sizeof(BasicJsonType) == 0, + "could not find to_json() method in T's namespace"); + } + + public: + template + void operator()(BasicJsonType& j, T&& val) const + noexcept(noexcept(std::declval().call(j, std::forward(val), priority_tag<1> {}))) + { + return call(j, std::forward(val), priority_tag<1> {}); + } +}; + +struct from_json_fn +{ + private: + template + auto call(const BasicJsonType& j, T& val, priority_tag<1>) const + noexcept(noexcept(from_json(j, val))) + -> decltype(from_json(j, val), void()) + { + return from_json(j, val); + } + + template + void call(const BasicJsonType&, T&, priority_tag<0>) const noexcept + { + static_assert(sizeof(BasicJsonType) == 0, + "could not find from_json() method in T's namespace"); + } + + public: + template + void operator()(const BasicJsonType& j, T& val) const + noexcept(noexcept(std::declval().call(j, val, priority_tag<1> {}))) + { + return call(j, val, priority_tag<1> {}); + } +}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; +} // namespace detail + + +/// namespace to hold default `to_json` / `from_json` functions +namespace +{ +constexpr const auto& to_json = detail::static_const::value; +constexpr const auto& from_json = detail::static_const::value; +} + + +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer +{ + /*! + @brief convert a JSON value to any value type + + This function is usually called by the `get()` function of the + @ref basic_json class (either explicit or via conversion operators). + + @param[in] j JSON value to read from + @param[in,out] val value to write to + */ + template + static void from_json(BasicJsonType&& j, ValueType& val) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), val))) + { + ::nlohmann::from_json(std::forward(j), val); + } + + /*! + @brief convert any value type to a JSON value + + This function is usually called by the constructors of the @ref basic_json + class. + + @param[in,out] j JSON value to write to + @param[in] val value to read from + */ + template + static void to_json(BasicJsonType& j, ValueType&& val) noexcept( + noexcept(::nlohmann::to_json(j, std::forward(val)))) + { + ::nlohmann::to_json(j, std::forward(val)); + } +}; + + +/*! +@brief a class to store JSON values + +@tparam ObjectType type for JSON objects (`std::map` by default; will be used +in @ref object_t) +@tparam ArrayType type for JSON arrays (`std::vector` by default; will be used +in @ref array_t) +@tparam StringType type for JSON strings and object keys (`std::string` by +default; will be used in @ref string_t) +@tparam BooleanType type for JSON booleans (`bool` by default; will be used +in @ref boolean_t) +@tparam NumberIntegerType type for JSON integer numbers (`int64_t` by +default; will be used in @ref number_integer_t) +@tparam NumberUnsignedType type for JSON unsigned integer numbers (@c +`uint64_t` by default; will be used in @ref number_unsigned_t) +@tparam NumberFloatType type for JSON floating-point numbers (`double` by +default; will be used in @ref number_float_t) +@tparam AllocatorType type of the allocator to use (`std::allocator` by +default) +@tparam JSONSerializer the serializer to resolve internal calls to `to_json()` +and `from_json()` (@ref adl_serializer by default) + +@requirement The class satisfies the following concept requirements: +- Basic + - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible): + JSON values can be default constructed. The result will be a JSON null + value. + - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible): + A JSON value can be constructed from an rvalue argument. + - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible): + A JSON value can be copy-constructed from an lvalue expression. + - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable): + A JSON value van be assigned from an rvalue argument. + - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable): + A JSON value can be copy-assigned from an lvalue expression. + - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible): + JSON values can be destructed. +- Layout + - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType): + JSON values have + [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout): + All non-static data members are private and standard layout types, the + class has no virtual functions or (virtual) base classes. +- Library-wide + - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable): + JSON values can be compared with `==`, see @ref + operator==(const_reference,const_reference). + - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable): + JSON values can be compared with `<`, see @ref + operator<(const_reference,const_reference). + - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable): + Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of + other compatible types, using unqualified function call @ref swap(). + - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer): + JSON values can be compared against `std::nullptr_t` objects which are used + to model the `null` value. +- Container + - [Container](http://en.cppreference.com/w/cpp/concept/Container): + JSON values can be used like STL containers and provide iterator access. + - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer); + JSON values can be used like STL containers and provide reverse iterator + access. + +@invariant The member variables @a m_value and @a m_type have the following +relationship: +- If `m_type == value_t::object`, then `m_value.object != nullptr`. +- If `m_type == value_t::array`, then `m_value.array != nullptr`. +- If `m_type == value_t::string`, then `m_value.string != nullptr`. +The invariants are checked by member function assert_invariant(). + +@internal +@note ObjectType trick from http://stackoverflow.com/a/9860911 +@endinternal + +@see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange +Format](http://rfc7159.net/rfc7159) + +@since version 1.0.0 + +@nosubgrouping +*/ +template < + template class ObjectType = std::map, + template class ArrayType = std::vector, + class StringType = std::string, + class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = adl_serializer + > +class basic_json +{ + private: + template friend struct detail::external_constructor; + /// workaround type for MSVC + using basic_json_t = basic_json; + + public: + using value_t = detail::value_t; + // forward declarations + template class iter_impl; + template class json_reverse_iterator; + class json_pointer; + template + using json_serializer = JSONSerializer; + + ///////////////////// + // container types // + ///////////////////// + + /// @name container types + /// The canonic container types to use @ref basic_json like any other STL + /// container. + /// @{ + + /// the type of elements in a basic_json container + using value_type = basic_json; + + /// the type of an element reference + using reference = value_type&; + /// the type of an element const reference + using const_reference = const value_type&; + + /// a type to represent differences between iterators + using difference_type = std::ptrdiff_t; + /// a type to represent container sizes + using size_type = std::size_t; + + /// the allocator type + using allocator_type = AllocatorType; + + /// the type of an element pointer + using pointer = typename std::allocator_traits::pointer; + /// the type of an element const pointer + using const_pointer = typename std::allocator_traits::const_pointer; + + /// an iterator for a basic_json container + using iterator = iter_impl; + /// a const iterator for a basic_json container + using const_iterator = iter_impl; + /// a reverse iterator for a basic_json container + using reverse_iterator = json_reverse_iterator; + /// a const reverse iterator for a basic_json container + using const_reverse_iterator = json_reverse_iterator; + + /// @} + + + /*! + @brief returns the allocator associated with the container + */ + static allocator_type get_allocator() + { + return allocator_type(); + } + + /*! + @brief returns version information on the library + + This function returns a JSON object with information about the library, + including the version number and information on the platform and compiler. + + @return JSON object holding version information + key | description + ----------- | --------------- + `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). + `copyright` | The copyright line for the library as string. + `name` | The name of the library as string. + `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. + `url` | The URL of the project as string. + `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). + + @liveexample{The following code shows an example output of the `meta()` + function.,meta} + + @complexity Constant. + + @since 2.1.0 + */ + static basic_json meta() + { + basic_json result; + + result["copyright"] = "(C) 2013-2017 Niels Lohmann"; + result["name"] = "JSON for Modern C++"; + result["url"] = "https://github.com/nlohmann/json"; + result["version"] = + { + {"string", "2.1.1"}, + {"major", 2}, + {"minor", 1}, + {"patch", 1} + }; + +#ifdef _WIN32 + result["platform"] = "win32"; +#elif defined __linux__ + result["platform"] = "linux"; +#elif defined __APPLE__ + result["platform"] = "apple"; +#elif defined __unix__ + result["platform"] = "unix"; +#else + result["platform"] = "unknown"; +#endif + +#if defined(__clang__) + result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; +#elif defined(__ICC) || defined(__INTEL_COMPILER) + result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; +#elif defined(__GNUC__) || defined(__GNUG__) + result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; +#elif defined(__HP_cc) || defined(__HP_aCC) + result["compiler"] = "hp" +#elif defined(__IBMCPP__) + result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; +#elif defined(_MSC_VER) + result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; +#elif defined(__PGI) + result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; +#elif defined(__SUNPRO_CC) + result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; +#else + result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; +#endif + +#ifdef __cplusplus + result["compiler"]["c++"] = std::to_string(__cplusplus); +#else + result["compiler"]["c++"] = "unknown"; +#endif + return result; + } + + + /////////////////////////// + // JSON value data types // + /////////////////////////// + + /// @name JSON value data types + /// The data types to store a JSON value. These types are derived from + /// the template arguments passed to class @ref basic_json. + /// @{ + + /*! + @brief a type for an object + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: + > An object is an unordered collection of zero or more name/value pairs, + > where a name is a string and a value is a string, number, boolean, null, + > object, or array. + + To store objects in C++, a type is defined by the template parameters + described below. + + @tparam ObjectType the container to store objects (e.g., `std::map` or + `std::unordered_map`) + @tparam StringType the type of the keys or names (e.g., `std::string`). + The comparison function `std::less` is used to order elements + inside the container. + @tparam AllocatorType the allocator to use for objects (e.g., + `std::allocator`) + + #### Default type + + With the default values for @a ObjectType (`std::map`), @a StringType + (`std::string`), and @a AllocatorType (`std::allocator`), the default + value for @a object_t is: + + @code {.cpp} + std::map< + std::string, // key_type + basic_json, // value_type + std::less, // key_compare + std::allocator> // allocator_type + > + @endcode + + #### Behavior + + The choice of @a object_t influences the behavior of the JSON class. With + the default type, objects have the following behavior: + + - When all names are unique, objects will be interoperable in the sense + that all software implementations receiving that object will agree on + the name-value mappings. + - When the names within an object are not unique, later stored name/value + pairs overwrite previously stored name/value pairs, leaving the used + names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will + be treated as equal and both stored as `{"key": 1}`. + - Internally, name/value pairs are stored in lexicographical order of the + names. Objects will also be serialized (see @ref dump) in this order. + For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored + and serialized as `{"a": 2, "b": 1}`. + - When comparing objects, the order of the name/value pairs is irrelevant. + This makes objects interoperable in the sense that they will not be + affected by these differences. For instance, `{"b": 1, "a": 2}` and + `{"a": 2, "b": 1}` will be treated as equal. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the object's limit of nesting is not constraint explicitly. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON object. + + #### Storage + + Objects are stored as pointers in a @ref basic_json type. That is, for any + access to object values, a pointer of type `object_t*` must be + dereferenced. + + @sa @ref array_t -- type for an array value + + @since version 1.0.0 + + @note The order name/value pairs are added to the object is *not* + preserved by the library. Therefore, iterating an object may return + name/value pairs in a different order than they were originally stored. In + fact, keys will be traversed in alphabetical order as `std::map` with + `std::less` is used by default. Please note this behavior conforms to [RFC + 7159](http://rfc7159.net/rfc7159), because any order implements the + specified "unordered" nature of JSON objects. + */ + using object_t = ObjectType, + AllocatorType>>; + + /*! + @brief a type for an array + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: + > An array is an ordered sequence of zero or more values. + + To store objects in C++, a type is defined by the template parameters + explained below. + + @tparam ArrayType container type to store arrays (e.g., `std::vector` or + `std::list`) + @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) + + #### Default type + + With the default values for @a ArrayType (`std::vector`) and @a + AllocatorType (`std::allocator`), the default value for @a array_t is: + + @code {.cpp} + std::vector< + basic_json, // value_type + std::allocator // allocator_type + > + @endcode + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the array's limit of nesting is not constraint explicitly. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON array. + + #### Storage + + Arrays are stored as pointers in a @ref basic_json type. That is, for any + access to array values, a pointer of type `array_t*` must be dereferenced. + + @sa @ref object_t -- type for an object value + + @since version 1.0.0 + */ + using array_t = ArrayType>; + + /*! + @brief a type for a string + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: + > A string is a sequence of zero or more Unicode characters. + + To store objects in C++, a type is defined by the template parameter + described below. Unicode values are split by the JSON class into + byte-sized characters during deserialization. + + @tparam StringType the container to store strings (e.g., `std::string`). + Note this container is used for keys/names in objects, see @ref object_t. + + #### Default type + + With the default values for @a StringType (`std::string`), the default + value for @a string_t is: + + @code {.cpp} + std::string + @endcode + + #### Encoding + + Strings are stored in UTF-8 encoding. Therefore, functions like + `std::string::size()` or `std::string::length()` return the number of + bytes in the string rather than the number of characters or glyphs. + + #### String comparison + + [RFC 7159](http://rfc7159.net/rfc7159) states: + > Software implementations are typically required to test names of object + > members for equality. Implementations that transform the textual + > representation into sequences of Unicode code units and then perform the + > comparison numerically, code unit by code unit, are interoperable in the + > sense that implementations will agree in all cases on equality or + > inequality of two strings. For example, implementations that compare + > strings with escaped characters unconverted may incorrectly find that + > `"a\\b"` and `"a\u005Cb"` are not equal. + + This implementation is interoperable as it does compare strings code unit + by code unit. + + #### Storage + + String values are stored as pointers in a @ref basic_json type. That is, + for any access to string values, a pointer of type `string_t*` must be + dereferenced. + + @since version 1.0.0 + */ + using string_t = StringType; + + /*! + @brief a type for a boolean + + [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a + type which differentiates the two literals `true` and `false`. + + To store objects in C++, a type is defined by the template parameter @a + BooleanType which chooses the type to use. + + #### Default type + + With the default values for @a BooleanType (`bool`), the default value for + @a boolean_t is: + + @code {.cpp} + bool + @endcode + + #### Storage + + Boolean values are stored directly inside a @ref basic_json type. + + @since version 1.0.0 + */ + using boolean_t = BooleanType; + + /*! + @brief a type for a number (integer) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store integer numbers in C++, a type is defined by the template + parameter @a NumberIntegerType which chooses the type to use. + + #### Default type + + With the default values for @a NumberIntegerType (`int64_t`), the default + value for @a number_integer_t is: + + @code {.cpp} + int64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `9223372036854775807` (INT64_MAX) and the minimal integer number + that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers + that are out of range will yield over/underflow when used in a + constructor. During deserialization, too large or small integer numbers + will be automatically be stored as @ref number_unsigned_t or @ref + number_float_t. + + [RFC 7159](http://rfc7159.net/rfc7159) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange of the exactly supported range [INT64_MIN, + INT64_MAX], this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa @ref number_float_t -- type for number values (floating-point) + + @sa @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_integer_t = NumberIntegerType; + + /*! + @brief a type for a number (unsigned) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store unsigned integer numbers in C++, a type is defined by the + template parameter @a NumberUnsignedType which chooses the type to use. + + #### Default type + + With the default values for @a NumberUnsignedType (`uint64_t`), the + default value for @a number_unsigned_t is: + + @code {.cpp} + uint64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `18446744073709551615` (UINT64_MAX) and the minimal integer + number that can be stored is `0`. Integer numbers that are out of range + will yield over/underflow when used in a constructor. During + deserialization, too large or small integer numbers will be automatically + be stored as @ref number_integer_t or @ref number_float_t. + + [RFC 7159](http://rfc7159.net/rfc7159) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange (when considered in conjunction with the + number_integer_t type) of the exactly supported range [0, UINT64_MAX], + this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa @ref number_float_t -- type for number values (floating-point) + @sa @ref number_integer_t -- type for number values (integer) + + @since version 2.0.0 + */ + using number_unsigned_t = NumberUnsignedType; + + /*! + @brief a type for a number (floating-point) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store floating-point numbers in C++, a type is defined by the template + parameter @a NumberFloatType which chooses the type to use. + + #### Default type + + With the default values for @a NumberFloatType (`double`), the default + value for @a number_float_t is: + + @code {.cpp} + double + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in floating-point literals will be ignored. Internally, + the value will be stored as decimal number. For instance, the C++ + floating-point literal `01.2` will be serialized to `1.2`. During + deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) states: + > This specification allows implementations to set limits on the range and + > precision of numbers accepted. Since software that implements IEEE + > 754-2008 binary64 (double precision) numbers is generally available and + > widely used, good interoperability can be achieved by implementations + > that expect no more precision or range than these provide, in the sense + > that implementations will approximate JSON numbers within the expected + > precision. + + This implementation does exactly follow this approach, as it uses double + precision floating-point numbers. Note values smaller than + `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` + will be stored as NaN internally and be serialized to `null`. + + #### Storage + + Floating-point number values are stored directly inside a @ref basic_json + type. + + @sa @ref number_integer_t -- type for number values (integer) + + @sa @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_float_t = NumberFloatType; + + /// @} + + private: + + /// helper for exception-safe object creation + template + static T* create(Args&& ... args) + { + AllocatorType alloc; + auto deleter = [&](T * object) + { + alloc.deallocate(object, 1); + }; + std::unique_ptr object(alloc.allocate(1), deleter); + alloc.construct(object.get(), std::forward(args)...); + assert(object != nullptr); + return object.release(); + } + + //////////////////////// + // JSON value storage // + //////////////////////// + + /*! + @brief a JSON value + + The actual storage for a JSON value of the @ref basic_json class. This + union combines the different storage types for the JSON value types + defined in @ref value_t. + + JSON type | value_t type | used type + --------- | --------------- | ------------------------ + object | object | pointer to @ref object_t + array | array | pointer to @ref array_t + string | string | pointer to @ref string_t + boolean | boolean | @ref boolean_t + number | number_integer | @ref number_integer_t + number | number_unsigned | @ref number_unsigned_t + number | number_float | @ref number_float_t + null | null | *no value is stored* + + @note Variable-length types (objects, arrays, and strings) are stored as + pointers. The size of the union should not exceed 64 bits if the default + value types are used. + + @since version 1.0.0 + */ + union json_value + { + /// object (stored with pointer to save storage) + object_t* object; + /// array (stored with pointer to save storage) + array_t* array; + /// string (stored with pointer to save storage) + string_t* string; + /// boolean + boolean_t boolean; + /// number (integer) + number_integer_t number_integer; + /// number (unsigned integer) + number_unsigned_t number_unsigned; + /// number (floating-point) + number_float_t number_float; + + /// default constructor (for null values) + json_value() = default; + /// constructor for booleans + json_value(boolean_t v) noexcept : boolean(v) {} + /// constructor for numbers (integer) + json_value(number_integer_t v) noexcept : number_integer(v) {} + /// constructor for numbers (unsigned) + json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} + /// constructor for numbers (floating-point) + json_value(number_float_t v) noexcept : number_float(v) {} + /// constructor for empty values of a given type + json_value(value_t t) + { + switch (t) + { + case value_t::object: + { + object = create(); + break; + } + + case value_t::array: + { + array = create(); + break; + } + + case value_t::string: + { + string = create(""); + break; + } + + case value_t::boolean: + { + boolean = boolean_t(false); + break; + } + + case value_t::number_integer: + { + number_integer = number_integer_t(0); + break; + } + + case value_t::number_unsigned: + { + number_unsigned = number_unsigned_t(0); + break; + } + + case value_t::number_float: + { + number_float = number_float_t(0.0); + break; + } + + case value_t::null: + { + break; + } + + default: + { + if (t == value_t::null) + { + JSON_THROW(std::domain_error("961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE + } + break; + } + } + } + + /// constructor for strings + json_value(const string_t& value) + { + string = create(value); + } + + /// constructor for objects + json_value(const object_t& value) + { + object = create(value); + } + + /// constructor for arrays + json_value(const array_t& value) + { + array = create(value); + } + }; + + /*! + @brief checks the class invariants + + This function asserts the class invariants. It needs to be called at the + end of every constructor to make sure that created objects respect the + invariant. Furthermore, it has to be called each time the type of a JSON + value is changed, because the invariant expresses a relationship between + @a m_type and @a m_value. + */ + void assert_invariant() const + { + assert(m_type != value_t::object or m_value.object != nullptr); + assert(m_type != value_t::array or m_value.array != nullptr); + assert(m_type != value_t::string or m_value.string != nullptr); + } + + public: + ////////////////////////// + // JSON parser callback // + ////////////////////////// + + /*! + @brief JSON callback events + + This enumeration lists the parser events that can trigger calling a + callback function of type @ref parser_callback_t during parsing. + + @image html callback_events.png "Example when certain parse events are triggered" + + @since version 1.0.0 + */ + enum class parse_event_t : uint8_t + { + /// the parser read `{` and started to process a JSON object + object_start, + /// the parser read `}` and finished processing a JSON object + object_end, + /// the parser read `[` and started to process a JSON array + array_start, + /// the parser read `]` and finished processing a JSON array + array_end, + /// the parser read a key of a value in an object + key, + /// the parser finished reading a JSON value + value + }; + + /*! + @brief per-element parser callback type + + With a parser callback function, the result of parsing a JSON text can be + influenced. When passed to @ref parse(std::istream&, const + parser_callback_t) or @ref parse(const CharT, const parser_callback_t), + it is called on certain events (passed as @ref parse_event_t via parameter + @a event) with a set recursion depth @a depth and context JSON value + @a parsed. The return value of the callback function is a boolean + indicating whether the element that emitted the callback shall be kept or + not. + + We distinguish six scenarios (determined by the event type) in which the + callback function can be called. The following table describes the values + of the parameters @a depth, @a event, and @a parsed. + + parameter @a event | description | parameter @a depth | parameter @a parsed + ------------------ | ----------- | ------------------ | ------------------- + parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded + parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key + parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object + parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded + parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array + parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value + + @image html callback_events.png "Example when certain parse events are triggered" + + Discarding a value (i.e., returning `false`) has different effects + depending on the context in which function was called: + + - Discarded values in structured types are skipped. That is, the parser + will behave as if the discarded value was never read. + - In case a value outside a structured type is skipped, it is replaced + with `null`. This case happens if the top-level element is skipped. + + @param[in] depth the depth of the recursion during parsing + + @param[in] event an event of type parse_event_t indicating the context in + the callback function has been called + + @param[in,out] parsed the current intermediate parse result; note that + writing to this value has no effect for parse_event_t::key events + + @return Whether the JSON value which called the function during parsing + should be kept (`true`) or not (`false`). In the latter case, it is either + skipped completely or replaced by an empty discarded object. + + @sa @ref parse(std::istream&, parser_callback_t) or + @ref parse(const CharT, const parser_callback_t) for examples + + @since version 1.0.0 + */ + using parser_callback_t = std::function; + + + ////////////////// + // constructors // + ////////////////// + + /// @name constructors and destructors + /// Constructors of class @ref basic_json, copy/move constructor, copy + /// assignment, static functions creating objects, and the destructor. + /// @{ + + /*! + @brief create an empty value with a given type + + Create an empty JSON value with a given type. The value will be default + initialized with an empty value which depends on the type: + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + object | `{}` + array | `[]` + + @param[in] value_type the type of the value to create + + @complexity Constant. + + @throw std::bad_alloc if allocation for object, array, or string value + fails + + @liveexample{The following code shows the constructor for different @ref + value_t values,basic_json__value_t} + + @since version 1.0.0 + */ + basic_json(const value_t value_type) + : m_type(value_type), m_value(value_type) + { + assert_invariant(); + } + + /*! + @brief create a null object + + Create a `null` JSON value. It either takes a null pointer as parameter + (explicitly creating `null`) or no parameter (implicitly creating `null`). + The passed null pointer itself is not read -- it is only used to choose + the right constructor. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this constructor never throws + exceptions. + + @liveexample{The following code shows the constructor with and without a + null pointer parameter.,basic_json__nullptr_t} + + @since version 1.0.0 + */ + basic_json(std::nullptr_t = nullptr) noexcept + : basic_json(value_t::null) + { + assert_invariant(); + } + + /*! + @brief create a JSON value + + This is a "catch all" constructor for all compatible JSON types; that is, + types for which a `to_json()` method exsits. The constructor forwards the + parameter @a val to that method (to `json_serializer::to_json` method + with `U = uncvref_t`, to be exact). + + Template type @a CompatibleType includes, but is not limited to, the + following types: + - **arrays**: @ref array_t and all kinds of compatible containers such as + `std::vector`, `std::deque`, `std::list`, `std::forward_list`, + `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and + `unordered_multiset` with a `value_type` from which a @ref basic_json + value can be constructed. + - **objects**: @ref object_t and all kinds of compatible associative + containers such as `std::map`, `std::unordered_map`, `std::multimap`, + and `std::unordered_multimap` with a `key_type` compatible to + @ref string_t and a `value_type` from which a @ref basic_json value can + be constructed. + - **strings**: @ref string_t, string literals, and all compatible string + containers can be used. + - **numbers**: @ref number_integer_t, @ref number_unsigned_t, + @ref number_float_t, and all convertible number types such as `int`, + `size_t`, `int64_t`, `float` or `double` can be used. + - **boolean**: @ref boolean_t / `bool` can be used. + + See the examples below. + + @tparam CompatibleType a type such that: + - @a CompatibleType is not derived from `std::istream`, + - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move + constructors), + - @a CompatibleType is not a @ref basic_json nested type (e.g., + @ref json_pointer, @ref iterator, etc ...) + - @ref @ref json_serializer has a + `to_json(basic_json_t&, CompatibleType&&)` method + + @tparam U = `uncvref_t` + + @param[in] val the value to be forwarded + + @complexity Usually linear in the size of the passed @a val, also + depending on the implementation of the called `to_json()` + method. + + @throw what `json_serializer::to_json()` throws + + @liveexample{The following code shows the constructor with several + compatible types.,basic_json__CompatibleType} + + @since version 2.1.0 + */ + template, + detail::enable_if_t::value and + not std::is_same::value and + not detail::is_basic_json_nested_type< + basic_json_t, U>::value and + detail::has_to_json::value, + int> = 0> + basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer::to_json( + std::declval(), std::forward(val)))) + { + JSONSerializer::to_json(*this, std::forward(val)); + assert_invariant(); + } + + /*! + @brief create a container (array or object) from an initializer list + + Creates a JSON value of type array or object from the passed initializer + list @a init. In case @a type_deduction is `true` (default), the type of + the JSON value to be created is deducted from the initializer list @a init + according to the following rules: + + 1. If the list is empty, an empty JSON object value `{}` is created. + 2. If the list consists of pairs whose first element is a string, a JSON + object value is created where the first elements of the pairs are + treated as keys and the second elements are as values. + 3. In all other cases, an array is created. + + The rules aim to create the best fit between a C++ initializer list and + JSON values. The rationale is as follows: + + 1. The empty initializer list is written as `{}` which is exactly an empty + JSON object. + 2. C++ has now way of describing mapped types other than to list a list of + pairs. As JSON requires that keys must be of type string, rule 2 is the + weakest constraint one can pose on initializer lists to interpret them + as an object. + 3. In all other cases, the initializer list could not be interpreted as + JSON object type, so interpreting it as JSON array type is safe. + + With the rules described above, the following JSON values cannot be + expressed by an initializer list: + + - the empty array (`[]`): use @ref array(std::initializer_list) + with an empty initializer list in this case + - arrays whose elements satisfy rule 2: use @ref + array(std::initializer_list) with the same initializer list + in this case + + @note When used without parentheses around an empty initializer list, @ref + basic_json() is called instead of this function, yielding the JSON null + value. + + @param[in] init initializer list with JSON values + + @param[in] type_deduction internal parameter; when set to `true`, the type + of the JSON value is deducted from the initializer list @a init; when set + to `false`, the type provided via @a manual_type is forced. This mode is + used by the functions @ref array(std::initializer_list) and + @ref object(std::initializer_list). + + @param[in] manual_type internal parameter; when @a type_deduction is set + to `false`, the created JSON value will use the provided type (only @ref + value_t::array and @ref value_t::object are valid); when @a type_deduction + is set to `true`, this parameter has no effect + + @throw std::domain_error if @a type_deduction is `false`, @a manual_type + is `value_t::object`, but @a init contains an element which is not a pair + whose first element is a string; example: `"cannot create object from + initializer list"` + + @complexity Linear in the size of the initializer list @a init. + + @liveexample{The example below shows how JSON values are created from + initializer lists.,basic_json__list_init_t} + + @sa @ref array(std::initializer_list) -- create a JSON array + value from an initializer list + @sa @ref object(std::initializer_list) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + basic_json(std::initializer_list init, + bool type_deduction = true, + value_t manual_type = value_t::array) + { + // check if each element is an array with two elements whose first + // element is a string + bool is_an_object = std::all_of(init.begin(), init.end(), + [](const basic_json & element) + { + return element.is_array() and element.size() == 2 and element[0].is_string(); + }); + + // adjust type if type deduction is not wanted + if (not type_deduction) + { + // if array is wanted, do not create an object though possible + if (manual_type == value_t::array) + { + is_an_object = false; + } + + // if object is wanted but impossible, throw an exception + if (manual_type == value_t::object and not is_an_object) + { + JSON_THROW(std::domain_error("cannot create object from initializer list")); + } + } + + if (is_an_object) + { + // the initializer list is a list of pairs -> create object + m_type = value_t::object; + m_value = value_t::object; + + std::for_each(init.begin(), init.end(), [this](const basic_json & element) + { + m_value.object->emplace(*(element[0].m_value.string), element[1]); + }); + } + else + { + // the initializer list describes an array -> create array + m_type = value_t::array; + m_value.array = create(init); + } + + assert_invariant(); + } + + /*! + @brief explicitly create an array from an initializer list + + Creates a JSON array value from a given initializer list. That is, given a + list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the + initializer list is empty, the empty array `[]` is created. + + @note This function is only needed to express two edge cases that cannot + be realized with the initializer list constructor (@ref + basic_json(std::initializer_list, bool, value_t)). These cases + are: + 1. creating an array whose elements are all pairs whose first element is a + string -- in this case, the initializer list constructor would create an + object, taking the first elements as keys + 2. creating an empty array -- passing the empty initializer list to the + initializer list constructor yields an empty object + + @param[in] init initializer list with JSON values to create an array from + (optional) + + @return JSON array value + + @complexity Linear in the size of @a init. + + @liveexample{The following code shows an example for the `array` + function.,array} + + @sa @ref basic_json(std::initializer_list, bool, value_t) -- + create a JSON value from an initializer list + @sa @ref object(std::initializer_list) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + static basic_json array(std::initializer_list init = + std::initializer_list()) + { + return basic_json(init, false, value_t::array); + } + + /*! + @brief explicitly create an object from an initializer list + + Creates a JSON object value from a given initializer list. The initializer + lists elements must be pairs, and their first elements must be strings. If + the initializer list is empty, the empty object `{}` is created. + + @note This function is only added for symmetry reasons. In contrast to the + related function @ref array(std::initializer_list), there are + no cases which can only be expressed by this function. That is, any + initializer list @a init can also be passed to the initializer list + constructor @ref basic_json(std::initializer_list, bool, + value_t). + + @param[in] init initializer list to create an object from (optional) + + @return JSON object value + + @throw std::domain_error if @a init is not a pair whose first elements are + strings; thrown by + @ref basic_json(std::initializer_list, bool, value_t) + + @complexity Linear in the size of @a init. + + @liveexample{The following code shows an example for the `object` + function.,object} + + @sa @ref basic_json(std::initializer_list, bool, value_t) -- + create a JSON value from an initializer list + @sa @ref array(std::initializer_list) -- create a JSON array + value from an initializer list + + @since version 1.0.0 + */ + static basic_json object(std::initializer_list init = + std::initializer_list()) + { + return basic_json(init, false, value_t::object); + } + + /*! + @brief construct an array with count copies of given value + + Constructs a JSON array value by creating @a cnt copies of a passed value. + In case @a cnt is `0`, an empty array is created. As postcondition, + `std::distance(begin(),end()) == cnt` holds. + + @param[in] cnt the number of JSON copies of @a val to create + @param[in] val the JSON value to copy + + @complexity Linear in @a cnt. + + @liveexample{The following code shows examples for the @ref + basic_json(size_type\, const basic_json&) + constructor.,basic_json__size_type_basic_json} + + @since version 1.0.0 + */ + basic_json(size_type cnt, const basic_json& val) + : m_type(value_t::array) + { + m_value.array = create(cnt, val); + assert_invariant(); + } + + /*! + @brief construct a JSON container given an iterator range + + Constructs the JSON value with the contents of the range `[first, last)`. + The semantics depends on the different types a JSON value can have: + - In case of primitive types (number, boolean, or string), @a first must + be `begin()` and @a last must be `end()`. In this case, the value is + copied. Otherwise, std::out_of_range is thrown. + - In case of structured types (array, object), the constructor behaves as + similar versions for `std::vector`. + - In case of a null type, std::domain_error is thrown. + + @tparam InputIT an input iterator type (@ref iterator or @ref + const_iterator) + + @param[in] first begin of the range to copy from (included) + @param[in] last end of the range to copy from (excluded) + + @pre Iterators @a first and @a last must be initialized. **This + precondition is enforced with an assertion.** + + @throw std::domain_error if iterators are not compatible; that is, do not + belong to the same JSON value; example: `"iterators are not compatible"` + @throw std::out_of_range if iterators are for a primitive type (number, + boolean, or string) where an out of range error can be detected easily; + example: `"iterators out of range"` + @throw std::bad_alloc if allocation for object, array, or string fails + @throw std::domain_error if called with a null value; example: `"cannot + use construct with iterators from null"` + + @complexity Linear in distance between @a first and @a last. + + @liveexample{The example below shows several ways to create JSON values by + specifying a subrange with iterators.,basic_json__InputIt_InputIt} + + @since version 1.0.0 + */ + template::value or + std::is_same::value, int>::type = 0> + basic_json(InputIT first, InputIT last) + { + assert(first.m_object != nullptr); + assert(last.m_object != nullptr); + + // make sure iterator fits the current value + if (first.m_object != last.m_object) + { + JSON_THROW(std::domain_error("iterators are not compatible")); + } + + // copy type from first iterator + m_type = first.m_object->m_type; + + // check if iterator range is complete for primitive values + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end()) + { + JSON_THROW(std::out_of_range("iterators out of range")); + } + break; + } + + default: + { + break; + } + } + + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = first.m_object->m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = first.m_object->m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value.number_float = first.m_object->m_value.number_float; + break; + } + + case value_t::boolean: + { + m_value.boolean = first.m_object->m_value.boolean; + break; + } + + case value_t::string: + { + m_value = *first.m_object->m_value.string; + break; + } + + case value_t::object: + { + m_value.object = create(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + m_value.array = create(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + default: + { + JSON_THROW(std::domain_error("cannot use construct with iterators from " + first.m_object->type_name())); + } + } + + assert_invariant(); + } + + /*! + @brief construct a JSON value given an input stream + + @param[in,out] i stream to read a serialized JSON value from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @deprecated This constructor is deprecated and will be removed in version + 3.0.0 to unify the interface of the library. Deserialization will be + done by stream operators or by calling one of the `parse` functions, + e.g. @ref parse(std::istream&, const parser_callback_t). That is, calls + like `json j(i);` for an input stream @a i need to be replaced by + `json j = json::parse(i);`. See the example below. + + @liveexample{The example below demonstrates constructing a JSON value from + a `std::stringstream` with and without callback + function.,basic_json__istream} + + @since version 2.0.0, deprecated in version 2.0.3, to be removed in + version 3.0.0 + */ + JSON_DEPRECATED + explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr) + { + *this = parser(i, cb).parse(); + assert_invariant(); + } + + /////////////////////////////////////// + // other constructors and destructor // + /////////////////////////////////////// + + /*! + @brief copy constructor + + Creates a copy of a given JSON value. + + @param[in] other the JSON value to copy + + @complexity Linear in the size of @a other. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is linear. + - As postcondition, it holds: `other == basic_json(other)`. + + @throw std::bad_alloc if allocation for object, array, or string fails. + + @liveexample{The following code shows an example for the copy + constructor.,basic_json__basic_json} + + @since version 1.0.0 + */ + basic_json(const basic_json& other) + : m_type(other.m_type) + { + // check of passed value is valid + other.assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + m_value = *other.m_value.object; + break; + } + + case value_t::array: + { + m_value = *other.m_value.array; + break; + } + + case value_t::string: + { + m_value = *other.m_value.string; + break; + } + + case value_t::boolean: + { + m_value = other.m_value.boolean; + break; + } + + case value_t::number_integer: + { + m_value = other.m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value = other.m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value = other.m_value.number_float; + break; + } + + default: + { + break; + } + } + + assert_invariant(); + } + + /*! + @brief move constructor + + Move constructor. Constructs a JSON value with the contents of the given + value @a other using move semantics. It "steals" the resources from @a + other and leaves it as JSON null value. + + @param[in,out] other value to move to this object + + @post @a other is a JSON null value + + @complexity Constant. + + @liveexample{The code below shows the move constructor explicitly called + via std::move.,basic_json__moveconstructor} + + @since version 1.0.0 + */ + basic_json(basic_json&& other) noexcept + : m_type(std::move(other.m_type)), + m_value(std::move(other.m_value)) + { + // check that passed value is valid + other.assert_invariant(); + + // invalidate payload + other.m_type = value_t::null; + other.m_value = {}; + + assert_invariant(); + } + + /*! + @brief copy assignment + + Copy assignment operator. Copies a JSON value via the "copy and swap" + strategy: It is expressed in terms of the copy constructor, destructor, + and the swap() member function. + + @param[in] other value to copy from + + @complexity Linear. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is linear. + + @liveexample{The code below shows and example for the copy assignment. It + creates a copy of value `a` which is then swapped with `b`. Finally\, the + copy of `a` (which is the null value after the swap) is + destroyed.,basic_json__copyassignment} + + @since version 1.0.0 + */ + reference& operator=(basic_json other) noexcept ( + std::is_nothrow_move_constructible::value and + std::is_nothrow_move_assignable::value and + std::is_nothrow_move_constructible::value and + std::is_nothrow_move_assignable::value + ) + { + // check that passed value is valid + other.assert_invariant(); + + using std::swap; + swap(m_type, other.m_type); + swap(m_value, other.m_value); + + assert_invariant(); + return *this; + } + + /*! + @brief destructor + + Destroys the JSON value and frees all allocated memory. + + @complexity Linear. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is linear. + - All stored elements are destroyed and all memory is freed. + + @since version 1.0.0 + */ + ~basic_json() + { + assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + AllocatorType alloc; + alloc.destroy(m_value.object); + alloc.deallocate(m_value.object, 1); + break; + } + + case value_t::array: + { + AllocatorType alloc; + alloc.destroy(m_value.array); + alloc.deallocate(m_value.array, 1); + break; + } + + case value_t::string: + { + AllocatorType alloc; + alloc.destroy(m_value.string); + alloc.deallocate(m_value.string, 1); + break; + } + + default: + { + // all other types need no specific destructor + break; + } + } + } + + /// @} + + public: + /////////////////////// + // object inspection // + /////////////////////// + + /// @name object inspection + /// Functions to inspect the type of a JSON value. + /// @{ + + /*! + @brief serialization + + Serialization function for JSON values. The function tries to mimic + Python's `json.dumps()` function, and currently supports its @a indent + parameter. + + @param[in] indent If indent is nonnegative, then array elements and object + members will be pretty-printed with that indent level. An indent level of + `0` will only insert newlines. `-1` (the default) selects the most compact + representation. + + @return string containing the serialization of the JSON value + + @complexity Linear. + + @liveexample{The following example shows the effect of different @a indent + parameters to the result of the serialization.,dump} + + @see https://docs.python.org/2/library/json.html#json.dump + + @since version 1.0.0 + */ + string_t dump(const int indent = -1) const + { + std::stringstream ss; + + if (indent >= 0) + { + dump(ss, true, static_cast(indent)); + } + else + { + dump(ss, false, 0); + } + + return ss.str(); + } + + /*! + @brief return the type of the JSON value (explicit) + + Return the type of the JSON value as a value from the @ref value_t + enumeration. + + @return the type of the JSON value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `type()` for all JSON + types.,type} + + @since version 1.0.0 + */ + constexpr value_t type() const noexcept + { + return m_type; + } + + /*! + @brief return whether type is primitive + + This function returns true iff the JSON type is primitive (string, number, + boolean, or null). + + @return `true` if type is primitive (string, number, boolean, or null), + `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_primitive()` for all JSON + types.,is_primitive} + + @sa @ref is_structured() -- returns whether JSON value is structured + @sa @ref is_null() -- returns whether JSON value is `null` + @sa @ref is_string() -- returns whether JSON value is a string + @sa @ref is_boolean() -- returns whether JSON value is a boolean + @sa @ref is_number() -- returns whether JSON value is a number + + @since version 1.0.0 + */ + constexpr bool is_primitive() const noexcept + { + return is_null() or is_string() or is_boolean() or is_number(); + } + + /*! + @brief return whether type is structured + + This function returns true iff the JSON type is structured (array or + object). + + @return `true` if type is structured (array or object), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_structured()` for all JSON + types.,is_structured} + + @sa @ref is_primitive() -- returns whether value is primitive + @sa @ref is_array() -- returns whether value is an array + @sa @ref is_object() -- returns whether value is an object + + @since version 1.0.0 + */ + constexpr bool is_structured() const noexcept + { + return is_array() or is_object(); + } + + /*! + @brief return whether value is null + + This function returns true iff the JSON value is null. + + @return `true` if type is null, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_null()` for all JSON + types.,is_null} + + @since version 1.0.0 + */ + constexpr bool is_null() const noexcept + { + return m_type == value_t::null; + } + + /*! + @brief return whether value is a boolean + + This function returns true iff the JSON value is a boolean. + + @return `true` if type is boolean, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_boolean()` for all JSON + types.,is_boolean} + + @since version 1.0.0 + */ + constexpr bool is_boolean() const noexcept + { + return m_type == value_t::boolean; + } + + /*! + @brief return whether value is a number + + This function returns true iff the JSON value is a number. This includes + both integer and floating-point values. + + @return `true` if type is number (regardless whether integer, unsigned + integer or floating-type), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number()` for all JSON + types.,is_number} + + @sa @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + constexpr bool is_number() const noexcept + { + return is_number_integer() or is_number_float(); + } + + /*! + @brief return whether value is an integer number + + This function returns true iff the JSON value is an integer or unsigned + integer number. This excludes floating-point values. + + @return `true` if type is an integer or unsigned integer number, `false` + otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_integer()` for all + JSON types.,is_number_integer} + + @sa @ref is_number() -- check if value is a number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + constexpr bool is_number_integer() const noexcept + { + return m_type == value_t::number_integer or m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is an unsigned integer number + + This function returns true iff the JSON value is an unsigned integer + number. This excludes floating-point and (signed) integer values. + + @return `true` if type is an unsigned integer number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_unsigned()` for all + JSON types.,is_number_unsigned} + + @sa @ref is_number() -- check if value is a number + @sa @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 2.0.0 + */ + constexpr bool is_number_unsigned() const noexcept + { + return m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is a floating-point number + + This function returns true iff the JSON value is a floating-point number. + This excludes integer and unsigned integer values. + + @return `true` if type is a floating-point number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_float()` for all + JSON types.,is_number_float} + + @sa @ref is_number() -- check if value is number + @sa @ref is_number_integer() -- check if value is an integer number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + + @since version 1.0.0 + */ + constexpr bool is_number_float() const noexcept + { + return m_type == value_t::number_float; + } + + /*! + @brief return whether value is an object + + This function returns true iff the JSON value is an object. + + @return `true` if type is object, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_object()` for all JSON + types.,is_object} + + @since version 1.0.0 + */ + constexpr bool is_object() const noexcept + { + return m_type == value_t::object; + } + + /*! + @brief return whether value is an array + + This function returns true iff the JSON value is an array. + + @return `true` if type is array, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_array()` for all JSON + types.,is_array} + + @since version 1.0.0 + */ + constexpr bool is_array() const noexcept + { + return m_type == value_t::array; + } + + /*! + @brief return whether value is a string + + This function returns true iff the JSON value is a string. + + @return `true` if type is string, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_string()` for all JSON + types.,is_string} + + @since version 1.0.0 + */ + constexpr bool is_string() const noexcept + { + return m_type == value_t::string; + } + + /*! + @brief return whether value is discarded + + This function returns true iff the JSON value was discarded during parsing + with a callback function (see @ref parser_callback_t). + + @note This function will always be `false` for JSON values after parsing. + That is, discarded values can only occur during parsing, but will be + removed when inside a structured value or replaced by null in other cases. + + @return `true` if type is discarded, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_discarded()` for all JSON + types.,is_discarded} + + @since version 1.0.0 + */ + constexpr bool is_discarded() const noexcept + { + return m_type == value_t::discarded; + } + + /*! + @brief return the type of the JSON value (implicit) + + Implicitly return the type of the JSON value as a value from the @ref + value_t enumeration. + + @return the type of the JSON value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies the @ref value_t operator for + all JSON types.,operator__value_t} + + @since version 1.0.0 + */ + constexpr operator value_t() const noexcept + { + return m_type; + } + + /// @} + + private: + ////////////////// + // value access // + ////////////////// + + /// get a boolean (explicit) + boolean_t get_impl(boolean_t* /*unused*/) const + { + if (is_boolean()) + { + return m_value.boolean; + } + + JSON_THROW(std::domain_error("type must be boolean, but is " + type_name())); + } + + /// get a pointer to the value (object) + object_t* get_impl_ptr(object_t* /*unused*/) noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (object) + constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (array) + array_t* get_impl_ptr(array_t* /*unused*/) noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (array) + constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (string) + string_t* get_impl_ptr(string_t* /*unused*/) noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (string) + constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (boolean) + boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (boolean) + constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (integer number) + number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (integer number) + constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (unsigned number) + number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (unsigned number) + constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (floating-point number) + number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (floating-point number) + constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /*! + @brief helper function to implement get_ref() + + This funcion helps to implement get_ref() without code duplication for + const and non-const overloads + + @tparam ThisType will be deduced as `basic_json` or `const basic_json` + + @throw std::domain_error if ReferenceType does not match underlying value + type of the current JSON + */ + template + static ReferenceType get_ref_impl(ThisType& obj) + { + // helper type + using PointerType = typename std::add_pointer::type; + + // delegate the call to get_ptr<>() + auto ptr = obj.template get_ptr(); + + if (ptr != nullptr) + { + return *ptr; + } + + JSON_THROW(std::domain_error("incompatible ReferenceType for get_ref, actual type is " + + obj.type_name())); + } + + public: + /// @name value access + /// Direct access to the stored value of a JSON value. + /// @{ + + /*! + @brief get special-case overload + + This overloads avoids a lot of template boilerplate, it can be seen as the + identity method + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this + + @complexity Constant. + + @since version 2.1.0 + */ + template < + typename BasicJsonType, + detail::enable_if_t::type, + basic_json_t>::value, + int> = 0 > + basic_json get() const + { + return *this; + } + + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value + which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) + and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType ret; + JSONSerializer::from_json(*this, ret); + return ret; + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const @ref basic_json&, ValueType&)`, and + - @ref json_serializer does not have a `from_json()` method of + the form `ValueType from_json(const @ref basic_json&)` + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get__ValueType_const} + + @since version 2.1.0 + */ + template < + typename ValueTypeCV, + typename ValueType = detail::uncvref_t, + detail::enable_if_t < + not std::is_same::value and + detail::has_from_json::value and + not detail::has_non_default_from_json::value, + int > = 0 > + ValueType get() const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), std::declval()))) + { + // we cannot static_assert on ValueTypeCV being non-const, because + // there is support for get(), which is why we + // still need the uncvref + static_assert(not std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + static_assert(std::is_default_constructible::value, + "types must be DefaultConstructible when used with get()"); + + ValueType ret; + JSONSerializer::from_json(*this, ret); + return ret; + } + + /*! + @brief get a value (explicit); special case + + Explicit type conversion between the JSON value and a compatible value + which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) + and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + return JSONSerializer::from_json(*this); + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json and + - @ref json_serializer has a `from_json()` method of the form + `ValueType from_json(const @ref basic_json&)` + + @note If @ref json_serializer has both overloads of + `from_json()`, this one is chosen. + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @since version 2.1.0 + */ + template < + typename ValueTypeCV, + typename ValueType = detail::uncvref_t, + detail::enable_if_t::value and + detail::has_non_default_from_json::value, int> = 0 > + ValueType get() const noexcept(noexcept( + JSONSerializer::from_json(std::declval()))) + { + static_assert(not std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + return JSONSerializer::from_json(*this); + } + + /*! + @brief get a pointer value (explicit) + + Explicit pointer access to the internally stored JSON value. No copies are + made. + + @warning The pointer becomes invalid if the underlying JSON object + changes. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get__PointerType} + + @sa @ref get_ptr() for explicit pointer-member access + + @since version 1.0.0 + */ + template::value, int>::type = 0> + PointerType get() noexcept + { + // delegate the call to get_ptr + return get_ptr(); + } + + /*! + @brief get a pointer value (explicit) + @copydoc get() + */ + template::value, int>::type = 0> + constexpr const PointerType get() const noexcept + { + // delegate the call to get_ptr + return get_ptr(); + } + + /*! + @brief get a pointer value (implicit) + + Implicit pointer access to the internally stored JSON value. No copies are + made. + + @warning Writing data to the pointee of the result yields an undefined + state. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. Enforced by a static + assertion. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get_ptr} + + @since version 1.0.0 + */ + template::value, int>::type = 0> + PointerType get_ptr() noexcept + { + // get the type of the PointerType (remove pointer and const) + using pointee_t = typename std::remove_const::type>::type>::type; + // make sure the type matches the allowed types + static_assert( + std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + , "incompatible pointer type"); + + // delegate the call to get_impl_ptr<>() + return get_impl_ptr(static_cast(nullptr)); + } + + /*! + @brief get a pointer value (implicit) + @copydoc get_ptr() + */ + template::value and + std::is_const::type>::value, int>::type = 0> + constexpr const PointerType get_ptr() const noexcept + { + // get the type of the PointerType (remove pointer and const) + using pointee_t = typename std::remove_const::type>::type>::type; + // make sure the type matches the allowed types + static_assert( + std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + or std::is_same::value + , "incompatible pointer type"); + + // delegate the call to get_impl_ptr<>() const + return get_impl_ptr(static_cast(nullptr)); + } + + /*! + @brief get a reference value (implicit) + + Implicit reference access to the internally stored JSON value. No copies + are made. + + @warning Writing data to the referee of the result yields an undefined + state. + + @tparam ReferenceType reference type; must be a reference to @ref array_t, + @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or + @ref number_float_t. Enforced by static assertion. + + @return reference to the internally stored JSON value if the requested + reference type @a ReferenceType fits to the JSON value; throws + std::domain_error otherwise + + @throw std::domain_error in case passed type @a ReferenceType is + incompatible with the stored JSON value + + @complexity Constant. + + @liveexample{The example shows several calls to `get_ref()`.,get_ref} + + @since version 1.1.0 + */ + template::value, int>::type = 0> + ReferenceType get_ref() + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a reference value (implicit) + @copydoc get_ref() + */ + template::value and + std::is_const::type>::value, int>::type = 0> + ReferenceType get_ref() const + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a value (implicit) + + Implicit type conversion between the JSON value and a compatible value. + The call is realized by calling @ref get() const. + + @tparam ValueType non-pointer type compatible to the JSON value, for + instance `int` for JSON integer numbers, `bool` for JSON booleans, or + `std::vector` types for JSON arrays. The character type of @ref string_t + as well as an initializer list of this type is excluded to avoid + ambiguities as these types implicitly convert to `std::string`. + + @return copy of the JSON value, converted to type @a ValueType + + @throw std::domain_error in case passed type @a ValueType is incompatible + to JSON, thrown by @ref get() const + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,operator__ValueType} + + @since version 1.0.0 + */ + template < typename ValueType, typename std::enable_if < + not std::is_pointer::value and + not std::is_same::value +#ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 + and not std::is_same>::value +#endif + , int >::type = 0 > + operator ValueType() const + { + // delegate the call to get<>() const + return get(); + } + + /// @} + + + //////////////////// + // element access // + //////////////////// + + /// @name element access + /// Access to the JSON value. + /// @{ + + /*! + @brief access specified array element with bounds checking + + Returns a reference to the element at specified location @a idx, with + bounds checking. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw std::domain_error if the JSON value is not an array; example: + `"cannot use at() with string"` + @throw std::out_of_range if the index @a idx is out of range of the array; + that is, `idx >= size()`; example: `"array index 7 is out of range"` + + @complexity Constant. + + @liveexample{The example below shows how array elements can be read and + written using `at()`.,at__size_type} + + @since version 1.0.0 + */ + reference at(size_type idx) + { + // at only works for arrays + if (is_array()) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); + } + } + else + { + JSON_THROW(std::domain_error("cannot use at() with " + type_name())); + } + } + + /*! + @brief access specified array element with bounds checking + + Returns a const reference to the element at specified location @a idx, + with bounds checking. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw std::domain_error if the JSON value is not an array; example: + `"cannot use at() with string"` + @throw std::out_of_range if the index @a idx is out of range of the array; + that is, `idx >= size()`; example: `"array index 7 is out of range"` + + @complexity Constant. + + @liveexample{The example below shows how array elements can be read using + `at()`.,at__size_type_const} + + @since version 1.0.0 + */ + const_reference at(size_type idx) const + { + // at only works for arrays + if (is_array()) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); + } + } + else + { + JSON_THROW(std::domain_error("cannot use at() with " + type_name())); + } + } + + /*! + @brief access specified object element with bounds checking + + Returns a reference to the element at with specified key @a key, with + bounds checking. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw std::domain_error if the JSON value is not an object; example: + `"cannot use at() with boolean"` + @throw std::out_of_range if the key @a key is is not stored in the object; + that is, `find(key) == end()`; example: `"key "the fast" not found"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using `at()`.,at__object_t_key_type} + + @sa @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + reference at(const typename object_t::key_type& key) + { + // at only works for objects + if (is_object()) + { + JSON_TRY + { + return m_value.object->at(key); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(std::out_of_range("key '" + key + "' not found")); + } + } + else + { + JSON_THROW(std::domain_error("cannot use at() with " + type_name())); + } + } + + /*! + @brief access specified object element with bounds checking + + Returns a const reference to the element at with specified key @a key, + with bounds checking. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @throw std::domain_error if the JSON value is not an object; example: + `"cannot use at() with boolean"` + @throw std::out_of_range if the key @a key is is not stored in the object; + that is, `find(key) == end()`; example: `"key "the fast" not found"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + `at()`.,at__object_t_key_type_const} + + @sa @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + const_reference at(const typename object_t::key_type& key) const + { + // at only works for objects + if (is_object()) + { + JSON_TRY + { + return m_value.object->at(key); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(std::out_of_range("key '" + key + "' not found")); + } + } + else + { + JSON_THROW(std::domain_error("cannot use at() with " + type_name())); + } + } + + /*! + @brief access specified array element + + Returns a reference to the element at specified location @a idx. + + @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), + then the array is silently filled up with `null` values to make `idx` a + valid reference to the last stored element. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw std::domain_error if JSON is not an array or null; example: + `"cannot use operator[] with string"` + + @complexity Constant if @a idx is in the range of the array. Otherwise + linear in `idx - size()`. + + @liveexample{The example below shows how array elements can be read and + written using `[]` operator. Note the addition of `null` + values.,operatorarray__size_type} + + @since version 1.0.0 + */ + reference operator[](size_type idx) + { + // implicitly convert null value to an empty array + if (is_null()) + { + m_type = value_t::array; + m_value.array = create(); + assert_invariant(); + } + + // operator[] only works for arrays + if (is_array()) + { + // fill up array with null values if given idx is outside range + if (idx >= m_value.array->size()) + { + m_value.array->insert(m_value.array->end(), + idx - m_value.array->size() + 1, + basic_json()); + } + + return m_value.array->operator[](idx); + } + + JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); + } + + /*! + @brief access specified array element + + Returns a const reference to the element at specified location @a idx. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw std::domain_error if JSON is not an array; example: `"cannot use + operator[] with null"` + + @complexity Constant. + + @liveexample{The example below shows how array elements can be read using + the `[]` operator.,operatorarray__size_type_const} + + @since version 1.0.0 + */ + const_reference operator[](size_type idx) const + { + // const operator[] only works for arrays + if (is_array()) + { + return m_value.array->operator[](idx); + } + + JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw std::domain_error if JSON is not an object or null; example: + `"cannot use operator[] with string"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + reference operator[](const typename object_t::key_type& key) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + // operator[] only works for objects + if (is_object()) + { + return m_value.object->operator[](key); + } + + JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw std::domain_error if JSON is not an object; example: `"cannot use + operator[] with null"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + const_reference operator[](const typename object_t::key_type& key) const + { + // const operator[] only works for objects + if (is_object()) + { + assert(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw std::domain_error if JSON is not an object or null; example: + `"cannot use operator[] with string"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + template + reference operator[](T * (&key)[n]) + { + return operator[](static_cast(key)); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @note This function is required for compatibility reasons with Clang. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @throw std::domain_error if JSON is not an object; example: `"cannot use + operator[] with null"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + template + const_reference operator[](T * (&key)[n]) const + { + return operator[](static_cast(key)); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw std::domain_error if JSON is not an object or null; example: + `"cannot use operator[] with string"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + reference operator[](T* key) + { + // implicitly convert null to object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // at only works for objects + if (is_object()) + { + return m_value.object->operator[](key); + } + + JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw std::domain_error if JSON is not an object; example: `"cannot use + operator[] with null"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + const_reference operator[](T* key) const + { + // at only works for objects + if (is_object()) + { + assert(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(std::domain_error("cannot use operator[] with " + type_name())); + } + + /*! + @brief access specified object element with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(key); + } catch(std::out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(const typename object_t::key_type&), this function + does not throw if the given key @a key was not found. + + @note Unlike @ref operator[](const typename object_t::key_type& key), this + function does not implicitly add an element to the position defined by @a + key. This function is furthermore also applicable to const objects. + + @param[in] key key of the element to access + @param[in] default_value the value to return if @a key is not found + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw std::domain_error if JSON is not an object; example: `"cannot use + value() with null"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,basic_json__value} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + + @since version 1.0.0 + */ + template::value, int>::type = 0> + ValueType value(const typename object_t::key_type& key, ValueType default_value) const + { + // at only works for objects + if (is_object()) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return *it; + } + + return default_value; + } + else + { + JSON_THROW(std::domain_error("cannot use value() with " + type_name())); + } + } + + /*! + @brief overload for a default value of type const char* + @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const + */ + string_t value(const typename object_t::key_type& key, const char* default_value) const + { + return value(key, string_t(default_value)); + } + + /*! + @brief access specified object element via JSON Pointer with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(ptr); + } catch(std::out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(const json_pointer&), this function does not throw + if the given key @a key was not found. + + @param[in] ptr a JSON pointer to the element to access + @param[in] default_value the value to return if @a ptr found no value + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw std::domain_error if JSON is not an object; example: `"cannot use + value() with null"` + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,basic_json__value_ptr} + + @sa @ref operator[](const json_pointer&) for unchecked access by reference + + @since version 2.0.2 + */ + template::value, int>::type = 0> + ValueType value(const json_pointer& ptr, ValueType default_value) const + { + // at only works for objects + if (is_object()) + { + // if pointer resolves a value, return it or use default value + JSON_TRY + { + return ptr.get_checked(this); + } + JSON_CATCH (std::out_of_range&) + { + return default_value; + } + } + + JSON_THROW(std::domain_error("cannot use value() with " + type_name())); + } + + /*! + @brief overload for a default value of type const char* + @copydoc basic_json::value(const json_pointer&, ValueType) const + */ + string_t value(const json_pointer& ptr, const char* default_value) const + { + return value(ptr, string_t(default_value)); + } + + /*! + @brief access the first element + + Returns a reference to the first element in the container. For a JSON + container `c`, the expression `c.front()` is equivalent to `*c.begin()`. + + @return In case of a structured type (array or object), a reference to the + first element is returned. In case of number, string, or boolean values, a + reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw std::out_of_range when called on `null` value + + @liveexample{The following code shows an example for `front()`.,front} + + @sa @ref back() -- access the last element + + @since version 1.0.0 + */ + reference front() + { + return *begin(); + } + + /*! + @copydoc basic_json::front() + */ + const_reference front() const + { + return *cbegin(); + } + + /*! + @brief access the last element + + Returns a reference to the last element in the container. For a JSON + container `c`, the expression `c.back()` is equivalent to + @code {.cpp} + auto tmp = c.end(); + --tmp; + return *tmp; + @endcode + + @return In case of a structured type (array or object), a reference to the + last element is returned. In case of number, string, or boolean values, a + reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw std::out_of_range when called on `null` value. + + @liveexample{The following code shows an example for `back()`.,back} + + @sa @ref front() -- access the first element + + @since version 1.0.0 + */ + reference back() + { + auto tmp = end(); + --tmp; + return *tmp; + } + + /*! + @copydoc basic_json::back() + */ + const_reference back() const + { + auto tmp = cend(); + --tmp; + return *tmp; + } + + /*! + @brief remove element given an iterator + + Removes the element specified by iterator @a pos. The iterator @a pos must + be valid and dereferenceable. Thus the `end()` iterator (which is valid, + but is not dereferenceable) cannot be used as a value for @a pos. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] pos iterator to the element to remove + @return Iterator following the last removed element. If the iterator @a + pos refers to the last element, the `end()` iterator is returned. + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw std::domain_error if called on a `null` value; example: `"cannot + use erase() with null"` + @throw std::domain_error if called on an iterator which does not belong to + the current JSON value; example: `"iterator does not fit current value"` + @throw std::out_of_range if called on a primitive type with invalid + iterator (i.e., any iterator which is not `begin()`); example: `"iterator + out of range"` + + @complexity The complexity depends on the type: + - objects: amortized constant + - arrays: linear in distance between @a pos and the end of the container + - strings: linear in the length of the string + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType} + + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template::value or + std::is_same::value, int>::type + = 0> + IteratorType erase(IteratorType pos) + { + // make sure iterator fits the current value + if (this != pos.m_object) + { + JSON_THROW(std::domain_error("iterator does not fit current value")); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (not pos.m_it.primitive_iterator.is_begin()) + { + JSON_THROW(std::out_of_range("iterator out of range")); + } + + if (is_string()) + { + AllocatorType alloc; + alloc.destroy(m_value.string); + alloc.deallocate(m_value.string, 1); + m_value.string = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); + break; + } + + default: + { + JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); + } + } + + return result; + } + + /*! + @brief remove elements given an iterator range + + Removes the element specified by the range `[first; last)`. The iterator + @a first does not need to be dereferenceable if `first == last`: erasing + an empty range is a no-op. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] first iterator to the beginning of the range to remove + @param[in] last iterator past the end of the range to remove + @return Iterator following the last removed element. If the iterator @a + second refers to the last element, the `end()` iterator is returned. + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw std::domain_error if called on a `null` value; example: `"cannot + use erase() with null"` + @throw std::domain_error if called on iterators which does not belong to + the current JSON value; example: `"iterators do not fit current value"` + @throw std::out_of_range if called on a primitive type with invalid + iterators (i.e., if `first != begin()` and `last != end()`); example: + `"iterators out of range"` + + @complexity The complexity depends on the type: + - objects: `log(size()) + std::distance(first, last)` + - arrays: linear in the distance between @a first and @a last, plus linear + in the distance between @a last and end of the container + - strings: linear in the length of the string + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType_IteratorType} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template::value or + std::is_same::value, int>::type + = 0> + IteratorType erase(IteratorType first, IteratorType last) + { + // make sure iterator fits the current value + if (this != first.m_object or this != last.m_object) + { + JSON_THROW(std::domain_error("iterators do not fit current value")); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end()) + { + JSON_THROW(std::out_of_range("iterators out of range")); + } + + if (is_string()) + { + AllocatorType alloc; + alloc.destroy(m_value.string); + alloc.deallocate(m_value.string, 1); + m_value.string = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + default: + { + JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); + } + } + + return result; + } + + /*! + @brief remove element from a JSON object given a key + + Removes elements from a JSON object with the key value @a key. + + @param[in] key value of the elements to remove + + @return Number of elements removed. If @a ObjectType is the default + `std::map` type, the return value will always be `0` (@a key was not + found) or `1` (@a key was found). + + @post References and iterators to the erased elements are invalidated. + Other references and iterators are not affected. + + @throw std::domain_error when called on a type other than JSON object; + example: `"cannot use erase() with null"` + + @complexity `log(size()) + count(key)` + + @liveexample{The example shows the effect of `erase()`.,erase__key_type} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + size_type erase(const typename object_t::key_type& key) + { + // this erase only works for objects + if (is_object()) + { + return m_value.object->erase(key); + } + + JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); + } + + /*! + @brief remove element from a JSON array given an index + + Removes element from a JSON array at the index @a idx. + + @param[in] idx index of the element to remove + + @throw std::domain_error when called on a type other than JSON array; + example: `"cannot use erase() with null"` + @throw std::out_of_range when `idx >= size()`; example: `"array index 17 + is out of range"` + + @complexity Linear in distance between @a idx and the end of the container. + + @liveexample{The example shows the effect of `erase()`.,erase__size_type} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + + @since version 1.0.0 + */ + void erase(const size_type idx) + { + // this erase only works for arrays + if (is_array()) + { + if (idx >= size()) + { + JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); + } + + m_value.array->erase(m_value.array->begin() + static_cast(idx)); + } + else + { + JSON_THROW(std::domain_error("cannot use erase() with " + type_name())); + } + } + + /// @} + + + //////////// + // lookup // + //////////// + + /// @name lookup + /// @{ + + /*! + @brief find an element in a JSON object + + Finds an element in a JSON object with key equivalent to @a key. If the + element is not found or the JSON value is not an object, end() is + returned. + + @note This method always returns @ref end() when executed on a JSON type + that is not an object. + + @param[in] key key value of the element to search for + + @return Iterator to an element with key equivalent to @a key. If no such + element is found or the JSON value is not an object, past-the-end (see + @ref end()) iterator is returned. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `find()` is used.,find__key_type} + + @since version 1.0.0 + */ + iterator find(typename object_t::key_type key) + { + auto result = end(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(key); + } + + return result; + } + + /*! + @brief find an element in a JSON object + @copydoc find(typename object_t::key_type) + */ + const_iterator find(typename object_t::key_type key) const + { + auto result = cend(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(key); + } + + return result; + } + + /*! + @brief returns the number of occurrences of a key in a JSON object + + Returns the number of elements with key @a key. If ObjectType is the + default `std::map` type, the return value will always be `0` (@a key was + not found) or `1` (@a key was found). + + @note This method always returns `0` when executed on a JSON type that is + not an object. + + @param[in] key key value of the element to count + + @return Number of elements with key @a key. If the JSON value is not an + object, the return value will be `0`. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `count()` is used.,count} + + @since version 1.0.0 + */ + size_type count(typename object_t::key_type key) const + { + // return 0 for all nonobject types + return is_object() ? m_value.object->count(key) : 0; + } + + /// @} + + + /////////////// + // iterators // + /////////////// + + /// @name iterators + /// @{ + + /*! + @brief returns an iterator to the first element + + Returns an iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator to the first element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `begin()`.,begin} + + @sa @ref cbegin() -- returns a const iterator to the beginning + @sa @ref end() -- returns an iterator to the end + @sa @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + iterator begin() noexcept + { + iterator result(this); + result.set_begin(); + return result; + } + + /*! + @copydoc basic_json::cbegin() + */ + const_iterator begin() const noexcept + { + return cbegin(); + } + + /*! + @brief returns a const iterator to the first element + + Returns a const iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator to the first element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).begin()`. + + @liveexample{The following code shows an example for `cbegin()`.,cbegin} + + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref end() -- returns an iterator to the end + @sa @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + const_iterator cbegin() const noexcept + { + const_iterator result(this); + result.set_begin(); + return result; + } + + /*! + @brief returns an iterator to one past the last element + + Returns an iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator one past the last element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `end()`.,end} + + @sa @ref cend() -- returns a const iterator to the end + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + iterator end() noexcept + { + iterator result(this); + result.set_end(); + return result; + } + + /*! + @copydoc basic_json::cend() + */ + const_iterator end() const noexcept + { + return cend(); + } + + /*! + @brief returns a const iterator to one past the last element + + Returns a const iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator one past the last element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).end()`. + + @liveexample{The following code shows an example for `cend()`.,cend} + + @sa @ref end() -- returns an iterator to the end + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + const_iterator cend() const noexcept + { + const_iterator result(this); + result.set_end(); + return result; + } + + /*! + @brief returns an iterator to the reverse-beginning + + Returns an iterator to the reverse-beginning; that is, the last element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `reverse_iterator(end())`. + + @liveexample{The following code shows an example for `rbegin()`.,rbegin} + + @sa @ref crbegin() -- returns a const reverse iterator to the beginning + @sa @ref rend() -- returns a reverse iterator to the end + @sa @ref crend() -- returns a const reverse iterator to the end + + @since version 1.0.0 + */ + reverse_iterator rbegin() noexcept + { + return reverse_iterator(end()); + } + + /*! + @copydoc basic_json::crbegin() + */ + const_reverse_iterator rbegin() const noexcept + { + return crbegin(); + } + + /*! + @brief returns an iterator to the reverse-end + + Returns an iterator to the reverse-end; that is, one before the first + element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `reverse_iterator(begin())`. + + @liveexample{The following code shows an example for `rend()`.,rend} + + @sa @ref crend() -- returns a const reverse iterator to the end + @sa @ref rbegin() -- returns a reverse iterator to the beginning + @sa @ref crbegin() -- returns a const reverse iterator to the beginning + + @since version 1.0.0 + */ + reverse_iterator rend() noexcept + { + return reverse_iterator(begin()); + } + + /*! + @copydoc basic_json::crend() + */ + const_reverse_iterator rend() const noexcept + { + return crend(); + } + + /*! + @brief returns a const reverse iterator to the last element + + Returns a const iterator to the reverse-beginning; that is, the last + element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).rbegin()`. + + @liveexample{The following code shows an example for `crbegin()`.,crbegin} + + @sa @ref rbegin() -- returns a reverse iterator to the beginning + @sa @ref rend() -- returns a reverse iterator to the end + @sa @ref crend() -- returns a const reverse iterator to the end + + @since version 1.0.0 + */ + const_reverse_iterator crbegin() const noexcept + { + return const_reverse_iterator(cend()); + } + + /*! + @brief returns a const reverse iterator to one before the first + + Returns a const reverse iterator to the reverse-end; that is, one before + the first element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).rend()`. + + @liveexample{The following code shows an example for `crend()`.,crend} + + @sa @ref rend() -- returns a reverse iterator to the end + @sa @ref rbegin() -- returns a reverse iterator to the beginning + @sa @ref crbegin() -- returns a const reverse iterator to the beginning + + @since version 1.0.0 + */ + const_reverse_iterator crend() const noexcept + { + return const_reverse_iterator(cbegin()); + } + + private: + // forward declaration + template class iteration_proxy; + + public: + /*! + @brief wrapper to access iterator member functions in range-based for + + This function allows to access @ref iterator::key() and @ref + iterator::value() during range-based for loops. In these loops, a + reference to the JSON values is returned, so there is no access to the + underlying iterator. + + @note The name of this function is not yet final and may change in the + future. + */ + static iteration_proxy iterator_wrapper(reference cont) + { + return iteration_proxy(cont); + } + + /*! + @copydoc iterator_wrapper(reference) + */ + static iteration_proxy iterator_wrapper(const_reference cont) + { + return iteration_proxy(cont); + } + + /// @} + + + ////////////// + // capacity // + ////////////// + + /// @name capacity + /// @{ + + /*! + @brief checks whether the container is empty + + Checks if a JSON value has no elements. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `true` + boolean | `false` + string | `false` + number | `false` + object | result of function `object_t::empty()` + array | result of function `array_t::empty()` + + @note This function does not return whether a string stored as JSON value + is empty - it returns whether the JSON container itself is empty which is + false in the case of a string. + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `empty()` functions have constant + complexity. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `begin() == end()`. + + @liveexample{The following code uses `empty()` to check if a JSON + object contains any elements.,empty} + + @sa @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + bool empty() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return true; + } + + case value_t::array: + { + // delegate call to array_t::empty() + return m_value.array->empty(); + } + + case value_t::object: + { + // delegate call to object_t::empty() + return m_value.object->empty(); + } + + default: + { + // all other types are nonempty + return false; + } + } + } + + /*! + @brief returns the number of elements + + Returns the number of elements in a JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` + boolean | `1` + string | `1` + number | `1` + object | result of function object_t::size() + array | result of function array_t::size() + + @note This function does not return the length of a string stored as JSON + value - it returns the number of elements in the JSON value which is 1 in + the case of a string. + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their size() functions have constant + complexity. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of `std::distance(begin(), end())`. + + @liveexample{The following code calls `size()` on the different value + types.,size} + + @sa @ref empty() -- checks whether the container is empty + @sa @ref max_size() -- returns the maximal number of elements + + @since version 1.0.0 + */ + size_type size() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return 0; + } + + case value_t::array: + { + // delegate call to array_t::size() + return m_value.array->size(); + } + + case value_t::object: + { + // delegate call to object_t::size() + return m_value.object->size(); + } + + default: + { + // all other types have size 1 + return 1; + } + } + } + + /*! + @brief returns the maximum possible number of elements + + Returns the maximum number of elements a JSON value is able to hold due to + system or library implementation limitations, i.e. `std::distance(begin(), + end())` for the JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` (same as `size()`) + boolean | `1` (same as `size()`) + string | `1` (same as `size()`) + number | `1` (same as `size()`) + object | result of function `object_t::max_size()` + array | result of function `array_t::max_size()` + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `max_size()` functions have constant + complexity. + + @requirement This function helps `basic_json` satisfying the + [Container](http://en.cppreference.com/w/cpp/concept/Container) + requirements: + - The complexity is constant. + - Has the semantics of returning `b.size()` where `b` is the largest + possible JSON value. + + @liveexample{The following code calls `max_size()` on the different value + types. Note the output is implementation specific.,max_size} + + @sa @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + size_type max_size() const noexcept + { + switch (m_type) + { + case value_t::array: + { + // delegate call to array_t::max_size() + return m_value.array->max_size(); + } + + case value_t::object: + { + // delegate call to object_t::max_size() + return m_value.object->max_size(); + } + + default: + { + // all other types have max_size() == size() + return size(); + } + } + } + + /// @} + + + /////////////// + // modifiers // + /////////////// + + /// @name modifiers + /// @{ + + /*! + @brief clears the contents + + Clears the content of a JSON value and resets it to the default value as + if @ref basic_json(value_t) would have been called: + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + object | `{}` + array | `[]` + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows the effect of `clear()` to different + JSON types.,clear} + + @since version 1.0.0 + */ + void clear() noexcept + { + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = 0; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = 0; + break; + } + + case value_t::number_float: + { + m_value.number_float = 0.0; + break; + } + + case value_t::boolean: + { + m_value.boolean = false; + break; + } + + case value_t::string: + { + m_value.string->clear(); + break; + } + + case value_t::array: + { + m_value.array->clear(); + break; + } + + case value_t::object: + { + m_value.object->clear(); + break; + } + + default: + { + break; + } + } + } + + /*! + @brief add an object to an array + + Appends the given element @a val to the end of the JSON value. If the + function is called on a JSON null value, an empty array is created before + appending @a val. + + @param[in] val the value to add to the JSON array + + @throw std::domain_error when called on a type other than JSON array or + null; example: `"cannot use push_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON array. Note how the `null` value was silently + converted to a JSON array.,push_back} + + @since version 1.0.0 + */ + void push_back(basic_json&& val) + { + // push_back only works for null objects or arrays + if (not(is_null() or is_array())) + { + JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (move semantics) + m_value.array->push_back(std::move(val)); + // invalidate object + val.m_type = value_t::null; + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + reference operator+=(basic_json&& val) + { + push_back(std::move(val)); + return *this; + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + void push_back(const basic_json& val) + { + // push_back only works for null objects or arrays + if (not(is_null() or is_array())) + { + JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array + m_value.array->push_back(val); + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + reference operator+=(const basic_json& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + Inserts the given element @a val to the JSON object. If the function is + called on a JSON null value, an empty object is created before inserting + @a val. + + @param[in] val the value to add to the JSON object + + @throw std::domain_error when called on a type other than JSON object or + null; example: `"cannot use push_back() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON object. Note how the `null` value was silently + converted to a JSON object.,push_back__object_t__value} + + @since version 1.0.0 + */ + void push_back(const typename object_t::value_type& val) + { + // push_back only works for null objects or objects + if (not(is_null() or is_object())) + { + JSON_THROW(std::domain_error("cannot use push_back() with " + type_name())); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array + m_value.object->insert(val); + } + + /*! + @brief add an object to an object + @copydoc push_back(const typename object_t::value_type&) + */ + reference operator+=(const typename object_t::value_type& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + This function allows to use `push_back` with an initializer list. In case + + 1. the current value is an object, + 2. the initializer list @a init contains only two elements, and + 3. the first element of @a init is a string, + + @a init is converted into an object element and added using + @ref push_back(const typename object_t::value_type&). Otherwise, @a init + is converted to a JSON value and added using @ref push_back(basic_json&&). + + @param init an initializer list + + @complexity Linear in the size of the initializer list @a init. + + @note This function is required to resolve an ambiguous overload error, + because pairs like `{"key", "value"}` can be both interpreted as + `object_t::value_type` or `std::initializer_list`, see + https://github.com/nlohmann/json/issues/235 for more information. + + @liveexample{The example shows how initializer lists are treated as + objects when possible.,push_back__initializer_list} + */ + void push_back(std::initializer_list init) + { + if (is_object() and init.size() == 2 and init.begin()->is_string()) + { + const string_t key = *init.begin(); + push_back(typename object_t::value_type(key, *(init.begin() + 1))); + } + else + { + push_back(basic_json(init)); + } + } + + /*! + @brief add an object to an object + @copydoc push_back(std::initializer_list) + */ + reference operator+=(std::initializer_list init) + { + push_back(init); + return *this; + } + + /*! + @brief add an object to an array + + Creates a JSON value from the passed parameters @a args to the end of the + JSON value. If the function is called on a JSON null value, an empty array + is created before appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref basic_json + @tparam Args compatible types to create a @ref basic_json object + + @throw std::domain_error when called on a type other than JSON array or + null; example: `"cannot use emplace_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` can be used to add + elements to a JSON array. Note how the `null` value was silently converted + to a JSON array.,emplace_back} + + @since version 2.0.8 + */ + template + void emplace_back(Args&& ... args) + { + // emplace_back only works for null objects or arrays + if (not(is_null() or is_array())) + { + JSON_THROW(std::domain_error("cannot use emplace_back() with " + type_name())); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (perfect forwarding) + m_value.array->emplace_back(std::forward(args)...); + } + + /*! + @brief add an object to an object if key does not exist + + Inserts a new element into a JSON object constructed in-place with the + given @a args if there is no element with the key in the container. If the + function is called on a JSON null value, an empty object is created before + appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref basic_json + @tparam Args compatible types to create a @ref basic_json object + + @return a pair consisting of an iterator to the inserted element, or the + already-existing element if no insertion happened, and a bool + denoting whether the insertion took place. + + @throw std::domain_error when called on a type other than JSON object or + null; example: `"cannot use emplace() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `emplace()` can be used to add elements + to a JSON object. Note how the `null` value was silently converted to a + JSON object. Further note how no value is added if there was already one + value stored with the same key.,emplace} + + @since version 2.0.8 + */ + template + std::pair emplace(Args&& ... args) + { + // emplace only works for null objects or arrays + if (not(is_null() or is_object())) + { + JSON_THROW(std::domain_error("cannot use emplace() with " + type_name())); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array (perfect forwarding) + auto res = m_value.object->emplace(std::forward(args)...); + // create result iterator and set iterator to the result of emplace + auto it = begin(); + it.m_it.object_iterator = res.first; + + // return pair of iterator and boolean + return {it, res.second}; + } + + /*! + @brief inserts element + + Inserts element @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] val element to insert + @return iterator pointing to the inserted @a val. + + @throw std::domain_error if called on JSON values other than arrays; + example: `"cannot use insert() with string"` + @throw std::domain_error if @a pos is not an iterator of *this; example: + `"iterator does not fit current value"` + + @complexity Constant plus linear in the distance between @a pos and end of + the container. + + @liveexample{The example shows how `insert()` is used.,insert} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const basic_json& val) + { + // insert only works for arrays + if (is_array()) + { + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(std::domain_error("iterator does not fit current value")); + } + + // insert to array and return iterator + iterator result(this); + result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); + return result; + } + + JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); + } + + /*! + @brief inserts element + @copydoc insert(const_iterator, const basic_json&) + */ + iterator insert(const_iterator pos, basic_json&& val) + { + return insert(pos, val); + } + + /*! + @brief inserts elements + + Inserts @a cnt copies of @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] cnt number of copies of @a val to insert + @param[in] val element to insert + @return iterator pointing to the first element inserted, or @a pos if + `cnt==0` + + @throw std::domain_error if called on JSON values other than arrays; + example: `"cannot use insert() with string"` + @throw std::domain_error if @a pos is not an iterator of *this; example: + `"iterator does not fit current value"` + + @complexity Linear in @a cnt plus linear in the distance between @a pos + and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__count} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, size_type cnt, const basic_json& val) + { + // insert only works for arrays + if (is_array()) + { + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(std::domain_error("iterator does not fit current value")); + } + + // insert to array and return iterator + iterator result(this); + result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); + return result; + } + + JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); + } + + /*! + @brief inserts elements + + Inserts elements from range `[first, last)` before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw std::domain_error if called on JSON values other than arrays; + example: `"cannot use insert() with string"` + @throw std::domain_error if @a pos is not an iterator of *this; example: + `"iterator does not fit current value"` + @throw std::domain_error if @a first and @a last do not belong to the same + JSON value; example: `"iterators do not fit"` + @throw std::domain_error if @a first or @a last are iterators into + container for which insert is called; example: `"passed iterators may not + belong to container"` + + @return iterator pointing to the first element inserted, or @a pos if + `first==last` + + @complexity Linear in `std::distance(first, last)` plus linear in the + distance between @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__range} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const_iterator first, const_iterator last) + { + // insert only works for arrays + if (not is_array()) + { + JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); + } + + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(std::domain_error("iterator does not fit current value")); + } + + // check if range iterators belong to the same JSON object + if (first.m_object != last.m_object) + { + JSON_THROW(std::domain_error("iterators do not fit")); + } + + if (first.m_object == this or last.m_object == this) + { + JSON_THROW(std::domain_error("passed iterators may not belong to container")); + } + + // insert to array and return iterator + iterator result(this); + result.m_it.array_iterator = m_value.array->insert( + pos.m_it.array_iterator, + first.m_it.array_iterator, + last.m_it.array_iterator); + return result; + } + + /*! + @brief inserts elements + + Inserts elements from initializer list @a ilist before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] ilist initializer list to insert the values from + + @throw std::domain_error if called on JSON values other than arrays; + example: `"cannot use insert() with string"` + @throw std::domain_error if @a pos is not an iterator of *this; example: + `"iterator does not fit current value"` + + @return iterator pointing to the first element inserted, or @a pos if + `ilist` is empty + + @complexity Linear in `ilist.size()` plus linear in the distance between + @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__ilist} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, std::initializer_list ilist) + { + // insert only works for arrays + if (not is_array()) + { + JSON_THROW(std::domain_error("cannot use insert() with " + type_name())); + } + + // check if iterator pos fits to this JSON value + if (pos.m_object != this) + { + JSON_THROW(std::domain_error("iterator does not fit current value")); + } + + // insert to array and return iterator + iterator result(this); + result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist); + return result; + } + + /*! + @brief exchanges the values + + Exchanges the contents of the JSON value with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other JSON value to exchange the contents with + + @complexity Constant. + + @liveexample{The example below shows how JSON values can be swapped with + `swap()`.,swap__reference} + + @since version 1.0.0 + */ + void swap(reference other) noexcept ( + std::is_nothrow_move_constructible::value and + std::is_nothrow_move_assignable::value and + std::is_nothrow_move_constructible::value and + std::is_nothrow_move_assignable::value + ) + { + std::swap(m_type, other.m_type); + std::swap(m_value, other.m_value); + assert_invariant(); + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON array with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other array to exchange the contents with + + @throw std::domain_error when JSON value is not an array; example: + `"cannot use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how arrays can be swapped with + `swap()`.,swap__array_t} + + @since version 1.0.0 + */ + void swap(array_t& other) + { + // swap only works for arrays + if (is_array()) + { + std::swap(*(m_value.array), other); + } + else + { + JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON object with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other object to exchange the contents with + + @throw std::domain_error when JSON value is not an object; example: + `"cannot use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how objects can be swapped with + `swap()`.,swap__object_t} + + @since version 1.0.0 + */ + void swap(object_t& other) + { + // swap only works for objects + if (is_object()) + { + std::swap(*(m_value.object), other); + } + else + { + JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON string with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other string to exchange the contents with + + @throw std::domain_error when JSON value is not a string; example: `"cannot + use swap() with boolean"` + + @complexity Constant. + + @liveexample{The example below shows how strings can be swapped with + `swap()`.,swap__string_t} + + @since version 1.0.0 + */ + void swap(string_t& other) + { + // swap only works for strings + if (is_string()) + { + std::swap(*(m_value.string), other); + } + else + { + JSON_THROW(std::domain_error("cannot use swap() with " + type_name())); + } + } + + /// @} + + public: + ////////////////////////////////////////// + // lexicographical comparison operators // + ////////////////////////////////////////// + + /// @name lexicographical comparison operators + /// @{ + + /*! + @brief comparison: equal + + Compares two JSON values for equality according to the following rules: + - Two JSON values are equal if (1) they are from the same type and (2) + their stored values are the same. + - Integer and floating-point numbers are automatically converted before + comparison. Floating-point numbers are compared indirectly: two + floating-point numbers `f1` and `f2` are considered equal if neither + `f1 > f2` nor `f2 > f1` holds. + - Two JSON null values are equal. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are equal + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__equal} + + @since version 1.0.0 + */ + friend bool operator==(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + { + return *lhs.m_value.array == *rhs.m_value.array; + } + case value_t::object: + { + return *lhs.m_value.object == *rhs.m_value.object; + } + case value_t::null: + { + return true; + } + case value_t::string: + { + return *lhs.m_value.string == *rhs.m_value.string; + } + case value_t::boolean: + { + return lhs.m_value.boolean == rhs.m_value.boolean; + } + case value_t::number_integer: + { + return lhs.m_value.number_integer == rhs.m_value.number_integer; + } + case value_t::number_unsigned: + { + return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; + } + case value_t::number_float: + { + return lhs.m_value.number_float == rhs.m_value.number_float; + } + default: + { + return false; + } + } + } + else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; + } + else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); + } + + return false; + } + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs == basic_json(rhs)); + } + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept + { + return (basic_json(lhs) == rhs); + } + + /*! + @brief comparison: not equal + + Compares two JSON values for inequality by calculating `not (lhs == rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are not equal + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__notequal} + + @since version 1.0.0 + */ + friend bool operator!=(const_reference lhs, const_reference rhs) noexcept + { + return not (lhs == rhs); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept + { + return (lhs != basic_json(rhs)); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept + { + return (basic_json(lhs) != rhs); + } + + /*! + @brief comparison: less than + + Compares whether one JSON value @a lhs is less than another JSON value @a + rhs according to the following rules: + - If @a lhs and @a rhs have the same type, the values are compared using + the default `<` operator. + - Integer and floating-point numbers are automatically converted before + comparison + - In case @a lhs and @a rhs have different types, the values are ignored + and the order of the types is considered, see + @ref operator<(const value_t, const value_t). + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__less} + + @since version 1.0.0 + */ + friend bool operator<(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + { + return *lhs.m_value.array < *rhs.m_value.array; + } + case value_t::object: + { + return *lhs.m_value.object < *rhs.m_value.object; + } + case value_t::null: + { + return false; + } + case value_t::string: + { + return *lhs.m_value.string < *rhs.m_value.string; + } + case value_t::boolean: + { + return lhs.m_value.boolean < rhs.m_value.boolean; + } + case value_t::number_integer: + { + return lhs.m_value.number_integer < rhs.m_value.number_integer; + } + case value_t::number_unsigned: + { + return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; + } + case value_t::number_float: + { + return lhs.m_value.number_float < rhs.m_value.number_float; + } + default: + { + return false; + } + } + } + else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; + } + + // We only reach this line if we cannot compare values. In that case, + // we compare types. Note we have to call the operator explicitly, + // because MSVC has problems otherwise. + return operator<(lhs_type, rhs_type); + } + + /*! + @brief comparison: less than or equal + + Compares whether one JSON value @a lhs is less than or equal to another + JSON value by calculating `not (rhs < lhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than or equal to @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greater} + + @since version 1.0.0 + */ + friend bool operator<=(const_reference lhs, const_reference rhs) noexcept + { + return not (rhs < lhs); + } + + /*! + @brief comparison: greater than + + Compares whether one JSON value @a lhs is greater than another + JSON value by calculating `not (lhs <= rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than to @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__lessequal} + + @since version 1.0.0 + */ + friend bool operator>(const_reference lhs, const_reference rhs) noexcept + { + return not (lhs <= rhs); + } + + /*! + @brief comparison: greater than or equal + + Compares whether one JSON value @a lhs is greater than or equal to another + JSON value by calculating `not (lhs < rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than or equal to @a rhs + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greaterequal} + + @since version 1.0.0 + */ + friend bool operator>=(const_reference lhs, const_reference rhs) noexcept + { + return not (lhs < rhs); + } + + /// @} + + + /////////////////// + // serialization // + /////////////////// + + /// @name serialization + /// @{ + + /*! + @brief serialize to stream + + Serialize the given JSON value @a j to the output stream @a o. The JSON + value will be serialized using the @ref dump member function. The + indentation of the output can be controlled with the member variable + `width` of the output stream @a o. For instance, using the manipulator + `std::setw(4)` on @a o sets the indentation level to `4` and the + serialization result is the same as calling `dump(4)`. + + @param[in,out] o stream to serialize to + @param[in] j JSON value to serialize + + @return the stream @a o + + @complexity Linear. + + @liveexample{The example below shows the serialization with different + parameters to `width` to adjust the indentation level.,operator_serialize} + + @since version 1.0.0 + */ + friend std::ostream& operator<<(std::ostream& o, const basic_json& j) + { + // read width member and use it as indentation parameter if nonzero + const bool pretty_print = (o.width() > 0); + const auto indentation = (pretty_print ? o.width() : 0); + + // reset width to 0 for subsequent calls to this stream + o.width(0); + + // do the actual serialization + j.dump(o, pretty_print, static_cast(indentation)); + + return o; + } + + /*! + @brief serialize to stream + @copydoc operator<<(std::ostream&, const basic_json&) + */ + friend std::ostream& operator>>(const basic_json& j, std::ostream& o) + { + return o << j; + } + + /// @} + + + ///////////////////// + // deserialization // + ///////////////////// + + /// @name deserialization + /// @{ + + /*! + @brief deserialize from an array + + This function reads from an array of 1-byte values. + + @pre Each element of the container has a size of 1 byte. Violating this + precondition yields undefined behavior. **This precondition is enforced + with a static assertion.** + + @param[in] array array to read from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @return result of the deserialization + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `parse()` function reading + from an array.,parse__array__parser_callback_t} + + @since version 2.0.3 + */ + template + static basic_json parse(T (&array)[N], + const parser_callback_t cb = nullptr) + { + // delegate the call to the iterator-range parse overload + return parse(std::begin(array), std::end(array), cb); + } + + /*! + @brief deserialize from string literal + + @tparam CharT character/literal type with size of 1 byte + @param[in] s string literal to read a serialized JSON value from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @return result of the deserialization + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + @note String containers like `std::string` or @ref string_t can be parsed + with @ref parse(const ContiguousContainer&, const parser_callback_t) + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__string__parser_callback_t} + + @sa @ref parse(std::istream&, const parser_callback_t) for a version that + reads from an input stream + + @since version 1.0.0 (originally for @ref string_t) + */ + template::value and + std::is_integral::type>::value and + sizeof(typename std::remove_pointer::type) == 1, int>::type = 0> + static basic_json parse(const CharT s, + const parser_callback_t cb = nullptr) + { + return parser(reinterpret_cast(s), cb).parse(); + } + + /*! + @brief deserialize from stream + + @param[in,out] i stream to read a serialized JSON value from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @return result of the deserialization + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__istream__parser_callback_t} + + @sa @ref parse(const CharT, const parser_callback_t) for a version + that reads from a string + + @since version 1.0.0 + */ + static basic_json parse(std::istream& i, + const parser_callback_t cb = nullptr) + { + return parser(i, cb).parse(); + } + + /*! + @copydoc parse(std::istream&, const parser_callback_t) + */ + static basic_json parse(std::istream&& i, + const parser_callback_t cb = nullptr) + { + return parser(i, cb).parse(); + } + + /*! + @brief deserialize from an iterator range with contiguous storage + + This function reads from an iterator range of a container with contiguous + storage of 1-byte values. Compatible container types include + `std::vector`, `std::string`, `std::array`, `std::valarray`, and + `std::initializer_list`. Furthermore, C-style arrays can be used with + `std::begin()`/`std::end()`. User-defined containers can be used as long + as they implement random-access iterators and a contiguous storage. + + @pre The iterator range is contiguous. Violating this precondition yields + undefined behavior. **This precondition is enforced with an assertion.** + @pre Each element in the range has a size of 1 byte. Violating this + precondition yields undefined behavior. **This precondition is enforced + with a static assertion.** + + @warning There is no way to enforce all preconditions at compile-time. If + the function is called with noncompliant iterators and with + assertions switched off, the behavior is undefined and will most + likely yield segmentation violation. + + @tparam IteratorType iterator of container with contiguous storage + @param[in] first begin of the range to parse (included) + @param[in] last end of the range to parse (excluded) + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @return result of the deserialization + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `parse()` function reading + from an iterator range.,parse__iteratortype__parser_callback_t} + + @since version 2.0.3 + */ + template::iterator_category>::value, int>::type = 0> + static basic_json parse(IteratorType first, IteratorType last, + const parser_callback_t cb = nullptr) + { + // assertion to check that the iterator range is indeed contiguous, + // see http://stackoverflow.com/a/35008842/266378 for more discussion + assert(std::accumulate(first, last, std::pair(true, 0), + [&first](std::pair res, decltype(*first) val) + { + res.first &= (val == *(std::next(std::addressof(*first), res.second++))); + return res; + }).first); + + // assertion to check that each element is 1 byte long + static_assert(sizeof(typename std::iterator_traits::value_type) == 1, + "each element in the iterator range must have the size of 1 byte"); + + // if iterator range is empty, create a parser with an empty string + // to generate "unexpected EOF" error message + if (std::distance(first, last) <= 0) + { + return parser("").parse(); + } + + return parser(first, last, cb).parse(); + } + + /*! + @brief deserialize from a container with contiguous storage + + This function reads from a container with contiguous storage of 1-byte + values. Compatible container types include `std::vector`, `std::string`, + `std::array`, and `std::initializer_list`. User-defined containers can be + used as long as they implement random-access iterators and a contiguous + storage. + + @pre The container storage is contiguous. Violating this precondition + yields undefined behavior. **This precondition is enforced with an + assertion.** + @pre Each element of the container has a size of 1 byte. Violating this + precondition yields undefined behavior. **This precondition is enforced + with a static assertion.** + + @warning There is no way to enforce all preconditions at compile-time. If + the function is called with a noncompliant container and with + assertions switched off, the behavior is undefined and will most + likely yield segmentation violation. + + @tparam ContiguousContainer container type with contiguous storage + @param[in] c container to read from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + + @return result of the deserialization + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `parse()` function reading + from a contiguous container.,parse__contiguouscontainer__parser_callback_t} + + @since version 2.0.3 + */ + template::value and + std::is_base_of< + std::random_access_iterator_tag, + typename std::iterator_traits()))>::iterator_category>::value + , int>::type = 0> + static basic_json parse(const ContiguousContainer& c, + const parser_callback_t cb = nullptr) + { + // delegate the call to the iterator-range parse overload + return parse(std::begin(c), std::end(c), cb); + } + + /*! + @brief deserialize from stream + + Deserializes an input stream to a JSON value. + + @param[in,out] i input stream to read a serialized JSON value from + @param[in,out] j JSON value to write the deserialized input to + + @throw std::invalid_argument in case of parse errors + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below shows how a JSON value is constructed by + reading a serialization from a stream.,operator_deserialize} + + @sa parse(std::istream&, const parser_callback_t) for a variant with a + parser callback function to filter values while parsing + + @since version 1.0.0 + */ + friend std::istream& operator<<(basic_json& j, std::istream& i) + { + j = parser(i).parse(); + return i; + } + + /*! + @brief deserialize from stream + @copydoc operator<<(basic_json&, std::istream&) + */ + friend std::istream& operator>>(std::istream& i, basic_json& j) + { + j = parser(i).parse(); + return i; + } + + /// @} + + ////////////////////////////////////////// + // binary serialization/deserialization // + ////////////////////////////////////////// + + /// @name binary serialization/deserialization support + /// @{ + + private: + /*! + @note Some code in the switch cases has been copied, because otherwise + copilers would complain about implicit fallthrough and there is no + portable attribute to mute such warnings. + */ + template + static void add_to_vector(std::vector& vec, size_t bytes, const T number) + { + assert(bytes == 1 or bytes == 2 or bytes == 4 or bytes == 8); + + switch (bytes) + { + case 8: + { + vec.push_back(static_cast((static_cast(number) >> 070) & 0xff)); + vec.push_back(static_cast((static_cast(number) >> 060) & 0xff)); + vec.push_back(static_cast((static_cast(number) >> 050) & 0xff)); + vec.push_back(static_cast((static_cast(number) >> 040) & 0xff)); + vec.push_back(static_cast((number >> 030) & 0xff)); + vec.push_back(static_cast((number >> 020) & 0xff)); + vec.push_back(static_cast((number >> 010) & 0xff)); + vec.push_back(static_cast(number & 0xff)); + break; + } + + case 4: + { + vec.push_back(static_cast((number >> 030) & 0xff)); + vec.push_back(static_cast((number >> 020) & 0xff)); + vec.push_back(static_cast((number >> 010) & 0xff)); + vec.push_back(static_cast(number & 0xff)); + break; + } + + case 2: + { + vec.push_back(static_cast((number >> 010) & 0xff)); + vec.push_back(static_cast(number & 0xff)); + break; + } + + case 1: + { + vec.push_back(static_cast(number & 0xff)); + break; + } + } + } + + /*! + @brief take sufficient bytes from a vector to fill an integer variable + + In the context of binary serialization formats, we need to read several + bytes from a byte vector and combine them to multi-byte integral data + types. + + @param[in] vec byte vector to read from + @param[in] current_index the position in the vector after which to read + + @return the next sizeof(T) bytes from @a vec, in reverse order as T + + @tparam T the integral return type + + @throw std::out_of_range if there are less than sizeof(T)+1 bytes in the + vector @a vec to read + + In the for loop, the bytes from the vector are copied in reverse order into + the return value. In the figures below, let sizeof(T)=4 and `i` be the loop + variable. + + Precondition: + + vec: | | | a | b | c | d | T: | | | | | + ^ ^ ^ ^ + current_index i ptr sizeof(T) + + Postcondition: + + vec: | | | a | b | c | d | T: | d | c | b | a | + ^ ^ ^ + | i ptr + current_index + + @sa Code adapted from . + */ + template + static T get_from_vector(const std::vector& vec, const size_t current_index) + { + if (current_index + sizeof(T) + 1 > vec.size()) + { + JSON_THROW(std::out_of_range("cannot read " + std::to_string(sizeof(T)) + " bytes from vector")); + } + + T result; + auto* ptr = reinterpret_cast(&result); + for (size_t i = 0; i < sizeof(T); ++i) + { + *ptr++ = vec[current_index + sizeof(T) - i]; + } + return result; + } + + /*! + @brief create a MessagePack serialization of a given JSON value + + This is a straightforward implementation of the MessagePack specification. + + @param[in] j JSON value to serialize + @param[in,out] v byte vector to write the serialization to + + @sa https://github.com/msgpack/msgpack/blob/master/spec.md + */ + static void to_msgpack_internal(const basic_json& j, std::vector& v) + { + switch (j.type()) + { + case value_t::null: + { + // nil + v.push_back(0xc0); + break; + } + + case value_t::boolean: + { + // true and false + v.push_back(j.m_value.boolean ? 0xc3 : 0xc2); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // MessagePack does not differentiate between positive + // signed integers and unsigned integers. Therefore, we + // used the code from the value_t::number_unsigned case + // here. + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + add_to_vector(v, 1, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 8 + v.push_back(0xcc); + add_to_vector(v, 1, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 16 + v.push_back(0xcd); + add_to_vector(v, 2, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 32 + v.push_back(0xce); + add_to_vector(v, 4, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 64 + v.push_back(0xcf); + add_to_vector(v, 8, j.m_value.number_unsigned); + } + } + else + { + if (j.m_value.number_integer >= -32) + { + // negative fixnum + add_to_vector(v, 1, j.m_value.number_integer); + } + else if (j.m_value.number_integer >= std::numeric_limits::min() and j.m_value.number_integer <= std::numeric_limits::max()) + { + // int 8 + v.push_back(0xd0); + add_to_vector(v, 1, j.m_value.number_integer); + } + else if (j.m_value.number_integer >= std::numeric_limits::min() and j.m_value.number_integer <= std::numeric_limits::max()) + { + // int 16 + v.push_back(0xd1); + add_to_vector(v, 2, j.m_value.number_integer); + } + else if (j.m_value.number_integer >= std::numeric_limits::min() and j.m_value.number_integer <= std::numeric_limits::max()) + { + // int 32 + v.push_back(0xd2); + add_to_vector(v, 4, j.m_value.number_integer); + } + else if (j.m_value.number_integer >= std::numeric_limits::min() and j.m_value.number_integer <= std::numeric_limits::max()) + { + // int 64 + v.push_back(0xd3); + add_to_vector(v, 8, j.m_value.number_integer); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + add_to_vector(v, 1, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 8 + v.push_back(0xcc); + add_to_vector(v, 1, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 16 + v.push_back(0xcd); + add_to_vector(v, 2, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 32 + v.push_back(0xce); + add_to_vector(v, 4, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= std::numeric_limits::max()) + { + // uint 64 + v.push_back(0xcf); + add_to_vector(v, 8, j.m_value.number_unsigned); + } + break; + } + + case value_t::number_float: + { + // float 64 + v.push_back(0xcb); + const auto* helper = reinterpret_cast(&(j.m_value.number_float)); + for (size_t i = 0; i < 8; ++i) + { + v.push_back(helper[7 - i]); + } + break; + } + + case value_t::string: + { + const auto N = j.m_value.string->size(); + if (N <= 31) + { + // fixstr + v.push_back(static_cast(0xa0 | N)); + } + else if (N <= 255) + { + // str 8 + v.push_back(0xd9); + add_to_vector(v, 1, N); + } + else if (N <= 65535) + { + // str 16 + v.push_back(0xda); + add_to_vector(v, 2, N); + } + else if (N <= 4294967295) + { + // str 32 + v.push_back(0xdb); + add_to_vector(v, 4, N); + } + + // append string + std::copy(j.m_value.string->begin(), j.m_value.string->end(), + std::back_inserter(v)); + break; + } + + case value_t::array: + { + const auto N = j.m_value.array->size(); + if (N <= 15) + { + // fixarray + v.push_back(static_cast(0x90 | N)); + } + else if (N <= 0xffff) + { + // array 16 + v.push_back(0xdc); + add_to_vector(v, 2, N); + } + else if (N <= 0xffffffff) + { + // array 32 + v.push_back(0xdd); + add_to_vector(v, 4, N); + } + + // append each element + for (const auto& el : *j.m_value.array) + { + to_msgpack_internal(el, v); + } + break; + } + + case value_t::object: + { + const auto N = j.m_value.object->size(); + if (N <= 15) + { + // fixmap + v.push_back(static_cast(0x80 | (N & 0xf))); + } + else if (N <= 65535) + { + // map 16 + v.push_back(0xde); + add_to_vector(v, 2, N); + } + else if (N <= 4294967295) + { + // map 32 + v.push_back(0xdf); + add_to_vector(v, 4, N); + } + + // append each element + for (const auto& el : *j.m_value.object) + { + to_msgpack_internal(el.first, v); + to_msgpack_internal(el.second, v); + } + break; + } + + default: + { + break; + } + } + } + + /*! + @brief create a CBOR serialization of a given JSON value + + This is a straightforward implementation of the CBOR specification. + + @param[in] j JSON value to serialize + @param[in,out] v byte vector to write the serialization to + + @sa https://tools.ietf.org/html/rfc7049 + */ + static void to_cbor_internal(const basic_json& j, std::vector& v) + { + switch (j.type()) + { + case value_t::null: + { + v.push_back(0xf6); + break; + } + + case value_t::boolean: + { + v.push_back(j.m_value.boolean ? 0xf5 : 0xf4); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // CBOR does not differentiate between positive signed + // integers and unsigned integers. Therefore, we used the + // code from the value_t::number_unsigned case here. + if (j.m_value.number_integer <= 0x17) + { + add_to_vector(v, 1, j.m_value.number_integer); + } + else if (j.m_value.number_integer <= std::numeric_limits::max()) + { + v.push_back(0x18); + // one-byte uint8_t + add_to_vector(v, 1, j.m_value.number_integer); + } + else if (j.m_value.number_integer <= std::numeric_limits::max()) + { + v.push_back(0x19); + // two-byte uint16_t + add_to_vector(v, 2, j.m_value.number_integer); + } + else if (j.m_value.number_integer <= std::numeric_limits::max()) + { + v.push_back(0x1a); + // four-byte uint32_t + add_to_vector(v, 4, j.m_value.number_integer); + } + else + { + v.push_back(0x1b); + // eight-byte uint64_t + add_to_vector(v, 8, j.m_value.number_integer); + } + } + else + { + // The conversions below encode the sign in the first + // byte, and the value is converted to a positive number. + const auto positive_number = -1 - j.m_value.number_integer; + if (j.m_value.number_integer >= -24) + { + v.push_back(static_cast(0x20 + positive_number)); + } + else if (positive_number <= std::numeric_limits::max()) + { + // int 8 + v.push_back(0x38); + add_to_vector(v, 1, positive_number); + } + else if (positive_number <= std::numeric_limits::max()) + { + // int 16 + v.push_back(0x39); + add_to_vector(v, 2, positive_number); + } + else if (positive_number <= std::numeric_limits::max()) + { + // int 32 + v.push_back(0x3a); + add_to_vector(v, 4, positive_number); + } + else + { + // int 64 + v.push_back(0x3b); + add_to_vector(v, 8, positive_number); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= 0x17) + { + v.push_back(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= 0xff) + { + v.push_back(0x18); + // one-byte uint8_t + add_to_vector(v, 1, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= 0xffff) + { + v.push_back(0x19); + // two-byte uint16_t + add_to_vector(v, 2, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= 0xffffffff) + { + v.push_back(0x1a); + // four-byte uint32_t + add_to_vector(v, 4, j.m_value.number_unsigned); + } + else if (j.m_value.number_unsigned <= 0xffffffffffffffff) + { + v.push_back(0x1b); + // eight-byte uint64_t + add_to_vector(v, 8, j.m_value.number_unsigned); + } + break; + } + + case value_t::number_float: + { + // Double-Precision Float + v.push_back(0xfb); + const auto* helper = reinterpret_cast(&(j.m_value.number_float)); + for (size_t i = 0; i < 8; ++i) + { + v.push_back(helper[7 - i]); + } + break; + } + + case value_t::string: + { + const auto N = j.m_value.string->size(); + if (N <= 0x17) + { + v.push_back(0x60 + static_cast(N)); // 1 byte for string + size + } + else if (N <= 0xff) + { + v.push_back(0x78); // one-byte uint8_t for N + add_to_vector(v, 1, N); + } + else if (N <= 0xffff) + { + v.push_back(0x79); // two-byte uint16_t for N + add_to_vector(v, 2, N); + } + else if (N <= 0xffffffff) + { + v.push_back(0x7a); // four-byte uint32_t for N + add_to_vector(v, 4, N); + } + // LCOV_EXCL_START + else if (N <= 0xffffffffffffffff) + { + v.push_back(0x7b); // eight-byte uint64_t for N + add_to_vector(v, 8, N); + } + // LCOV_EXCL_STOP + + // append string + std::copy(j.m_value.string->begin(), j.m_value.string->end(), + std::back_inserter(v)); + break; + } + + case value_t::array: + { + const auto N = j.m_value.array->size(); + if (N <= 0x17) + { + v.push_back(0x80 + static_cast(N)); // 1 byte for array + size + } + else if (N <= 0xff) + { + v.push_back(0x98); // one-byte uint8_t for N + add_to_vector(v, 1, N); + } + else if (N <= 0xffff) + { + v.push_back(0x99); // two-byte uint16_t for N + add_to_vector(v, 2, N); + } + else if (N <= 0xffffffff) + { + v.push_back(0x9a); // four-byte uint32_t for N + add_to_vector(v, 4, N); + } + // LCOV_EXCL_START + else if (N <= 0xffffffffffffffff) + { + v.push_back(0x9b); // eight-byte uint64_t for N + add_to_vector(v, 8, N); + } + // LCOV_EXCL_STOP + + // append each element + for (const auto& el : *j.m_value.array) + { + to_cbor_internal(el, v); + } + break; + } + + case value_t::object: + { + const auto N = j.m_value.object->size(); + if (N <= 0x17) + { + v.push_back(0xa0 + static_cast(N)); // 1 byte for object + size + } + else if (N <= 0xff) + { + v.push_back(0xb8); + add_to_vector(v, 1, N); // one-byte uint8_t for N + } + else if (N <= 0xffff) + { + v.push_back(0xb9); + add_to_vector(v, 2, N); // two-byte uint16_t for N + } + else if (N <= 0xffffffff) + { + v.push_back(0xba); + add_to_vector(v, 4, N); // four-byte uint32_t for N + } + // LCOV_EXCL_START + else if (N <= 0xffffffffffffffff) + { + v.push_back(0xbb); + add_to_vector(v, 8, N); // eight-byte uint64_t for N + } + // LCOV_EXCL_STOP + + // append each element + for (const auto& el : *j.m_value.object) + { + to_cbor_internal(el.first, v); + to_cbor_internal(el.second, v); + } + break; + } + + default: + { + break; + } + } + } + + + /* + @brief checks if given lengths do not exceed the size of a given vector + + To secure the access to the byte vector during CBOR/MessagePack + deserialization, bytes are copied from the vector into buffers. This + function checks if the number of bytes to copy (@a len) does not exceed + the size @s size of the vector. Additionally, an @a offset is given from + where to start reading the bytes. + + This function checks whether reading the bytes is safe; that is, offset is + a valid index in the vector, offset+len + + @param[in] size size of the byte vector + @param[in] len number of bytes to read + @param[in] offset offset where to start reading + + vec: x x x x x X X X X X + ^ ^ ^ + 0 offset len + + @throws out_of_range if `len > v.size()` + */ + static void check_length(const size_t size, const size_t len, const size_t offset) + { + // simple case: requested length is greater than the vector's length + if (len > size or offset > size) + { + JSON_THROW(std::out_of_range("len out of range")); + } + + // second case: adding offset would result in overflow + if ((size > (std::numeric_limits::max() - offset))) + { + JSON_THROW(std::out_of_range("len+offset out of range")); + } + + // last case: reading past the end of the vector + if (len + offset > size) + { + JSON_THROW(std::out_of_range("len+offset out of range")); + } + } + + /*! + @brief create a JSON value from a given MessagePack vector + + @param[in] v MessagePack serialization + @param[in] idx byte index to start reading from @a v + + @return deserialized JSON value + + @throw std::invalid_argument if unsupported features from MessagePack were + used in the given vector @a v or if the input is not valid MessagePack + @throw std::out_of_range if the given vector ends prematurely + + @sa https://github.com/msgpack/msgpack/blob/master/spec.md + */ + static basic_json from_msgpack_internal(const std::vector& v, size_t& idx) + { + // make sure reading 1 byte is safe + check_length(v.size(), 1, idx); + + // store and increment index + const size_t current_idx = idx++; + + if (v[current_idx] <= 0xbf) + { + if (v[current_idx] <= 0x7f) // positive fixint + { + return v[current_idx]; + } + if (v[current_idx] <= 0x8f) // fixmap + { + basic_json result = value_t::object; + const size_t len = v[current_idx] & 0x0f; + for (size_t i = 0; i < len; ++i) + { + std::string key = from_msgpack_internal(v, idx); + result[key] = from_msgpack_internal(v, idx); + } + return result; + } + else if (v[current_idx] <= 0x9f) // fixarray + { + basic_json result = value_t::array; + const size_t len = v[current_idx] & 0x0f; + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_msgpack_internal(v, idx)); + } + return result; + } + else // fixstr + { + const size_t len = v[current_idx] & 0x1f; + const size_t offset = current_idx + 1; + idx += len; // skip content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + } + else if (v[current_idx] >= 0xe0) // negative fixint + { + return static_cast(v[current_idx]); + } + else + { + switch (v[current_idx]) + { + case 0xc0: // nil + { + return value_t::null; + } + + case 0xc2: // false + { + return false; + } + + case 0xc3: // true + { + return true; + } + + case 0xca: // float 32 + { + // copy bytes in reverse order into the double variable + float res; + for (size_t byte = 0; byte < sizeof(float); ++byte) + { + reinterpret_cast(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte); + } + idx += sizeof(float); // skip content bytes + return res; + } + + case 0xcb: // float 64 + { + // copy bytes in reverse order into the double variable + double res; + for (size_t byte = 0; byte < sizeof(double); ++byte) + { + reinterpret_cast(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte); + } + idx += sizeof(double); // skip content bytes + return res; + } + + case 0xcc: // uint 8 + { + idx += 1; // skip content byte + return get_from_vector(v, current_idx); + } + + case 0xcd: // uint 16 + { + idx += 2; // skip 2 content bytes + return get_from_vector(v, current_idx); + } + + case 0xce: // uint 32 + { + idx += 4; // skip 4 content bytes + return get_from_vector(v, current_idx); + } + + case 0xcf: // uint 64 + { + idx += 8; // skip 8 content bytes + return get_from_vector(v, current_idx); + } + + case 0xd0: // int 8 + { + idx += 1; // skip content byte + return get_from_vector(v, current_idx); + } + + case 0xd1: // int 16 + { + idx += 2; // skip 2 content bytes + return get_from_vector(v, current_idx); + } + + case 0xd2: // int 32 + { + idx += 4; // skip 4 content bytes + return get_from_vector(v, current_idx); + } + + case 0xd3: // int 64 + { + idx += 8; // skip 8 content bytes + return get_from_vector(v, current_idx); + } + + case 0xd9: // str 8 + { + const auto len = static_cast(get_from_vector(v, current_idx)); + const size_t offset = current_idx + 2; + idx += len + 1; // skip size byte + content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0xda: // str 16 + { + const auto len = static_cast(get_from_vector(v, current_idx)); + const size_t offset = current_idx + 3; + idx += len + 2; // skip 2 size bytes + content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0xdb: // str 32 + { + const auto len = static_cast(get_from_vector(v, current_idx)); + const size_t offset = current_idx + 5; + idx += len + 4; // skip 4 size bytes + content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0xdc: // array 16 + { + basic_json result = value_t::array; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 2; // skip 2 size bytes + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_msgpack_internal(v, idx)); + } + return result; + } + + case 0xdd: // array 32 + { + basic_json result = value_t::array; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 4; // skip 4 size bytes + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_msgpack_internal(v, idx)); + } + return result; + } + + case 0xde: // map 16 + { + basic_json result = value_t::object; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 2; // skip 2 size bytes + for (size_t i = 0; i < len; ++i) + { + std::string key = from_msgpack_internal(v, idx); + result[key] = from_msgpack_internal(v, idx); + } + return result; + } + + case 0xdf: // map 32 + { + basic_json result = value_t::object; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 4; // skip 4 size bytes + for (size_t i = 0; i < len; ++i) + { + std::string key = from_msgpack_internal(v, idx); + result[key] = from_msgpack_internal(v, idx); + } + return result; + } + + default: + { + JSON_THROW(std::invalid_argument("error parsing a msgpack @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast(v[current_idx])))); + } + } + } + } + + /*! + @brief create a JSON value from a given CBOR vector + + @param[in] v CBOR serialization + @param[in] idx byte index to start reading from @a v + + @return deserialized JSON value + + @throw std::invalid_argument if unsupported features from CBOR were used in + the given vector @a v or if the input is not valid CBOR + @throw std::out_of_range if the given vector ends prematurely + + @sa https://tools.ietf.org/html/rfc7049 + */ + static basic_json from_cbor_internal(const std::vector& v, size_t& idx) + { + // store and increment index + const size_t current_idx = idx++; + + switch (v.at(current_idx)) + { + // Integer 0x00..0x17 (0..23) + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0a: + case 0x0b: + case 0x0c: + case 0x0d: + case 0x0e: + case 0x0f: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + { + return v[current_idx]; + } + + case 0x18: // Unsigned integer (one-byte uint8_t follows) + { + idx += 1; // skip content byte + return get_from_vector(v, current_idx); + } + + case 0x19: // Unsigned integer (two-byte uint16_t follows) + { + idx += 2; // skip 2 content bytes + return get_from_vector(v, current_idx); + } + + case 0x1a: // Unsigned integer (four-byte uint32_t follows) + { + idx += 4; // skip 4 content bytes + return get_from_vector(v, current_idx); + } + + case 0x1b: // Unsigned integer (eight-byte uint64_t follows) + { + idx += 8; // skip 8 content bytes + return get_from_vector(v, current_idx); + } + + // Negative integer -1-0x00..-1-0x17 (-1..-24) + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2a: + case 0x2b: + case 0x2c: + case 0x2d: + case 0x2e: + case 0x2f: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + { + return static_cast(0x20 - 1 - v[current_idx]); + } + + case 0x38: // Negative integer (one-byte uint8_t follows) + { + idx += 1; // skip content byte + // must be uint8_t ! + return static_cast(-1) - get_from_vector(v, current_idx); + } + + case 0x39: // Negative integer -1-n (two-byte uint16_t follows) + { + idx += 2; // skip 2 content bytes + return static_cast(-1) - get_from_vector(v, current_idx); + } + + case 0x3a: // Negative integer -1-n (four-byte uint32_t follows) + { + idx += 4; // skip 4 content bytes + return static_cast(-1) - get_from_vector(v, current_idx); + } + + case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows) + { + idx += 8; // skip 8 content bytes + return static_cast(-1) - static_cast(get_from_vector(v, current_idx)); + } + + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6a: + case 0x6b: + case 0x6c: + case 0x6d: + case 0x6e: + case 0x6f: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + const auto len = static_cast(v[current_idx] - 0x60); + const size_t offset = current_idx + 1; + idx += len; // skip content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + { + const auto len = static_cast(get_from_vector(v, current_idx)); + const size_t offset = current_idx + 2; + idx += len + 1; // skip size byte + content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + { + const auto len = static_cast(get_from_vector(v, current_idx)); + const size_t offset = current_idx + 3; + idx += len + 2; // skip 2 size bytes + content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) + { + const auto len = static_cast(get_from_vector(v, current_idx)); + const size_t offset = current_idx + 5; + idx += len + 4; // skip 4 size bytes + content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) + { + const auto len = static_cast(get_from_vector(v, current_idx)); + const size_t offset = current_idx + 9; + idx += len + 8; // skip 8 size bytes + content bytes + check_length(v.size(), len, offset); + return std::string(reinterpret_cast(v.data()) + offset, len); + } + + case 0x7f: // UTF-8 string (indefinite length) + { + std::string result; + while (v.at(idx) != 0xff) + { + string_t s = from_cbor_internal(v, idx); + result += s; + } + // skip break byte (0xFF) + idx += 1; + return result; + } + + // array (0x00..0x17 data items follow) + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8a: + case 0x8b: + case 0x8c: + case 0x8d: + case 0x8e: + case 0x8f: + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + { + basic_json result = value_t::array; + const auto len = static_cast(v[current_idx] - 0x80); + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_cbor_internal(v, idx)); + } + return result; + } + + case 0x98: // array (one-byte uint8_t for n follows) + { + basic_json result = value_t::array; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 1; // skip 1 size byte + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_cbor_internal(v, idx)); + } + return result; + } + + case 0x99: // array (two-byte uint16_t for n follow) + { + basic_json result = value_t::array; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 2; // skip 4 size bytes + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_cbor_internal(v, idx)); + } + return result; + } + + case 0x9a: // array (four-byte uint32_t for n follow) + { + basic_json result = value_t::array; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 4; // skip 4 size bytes + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_cbor_internal(v, idx)); + } + return result; + } + + case 0x9b: // array (eight-byte uint64_t for n follow) + { + basic_json result = value_t::array; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 8; // skip 8 size bytes + for (size_t i = 0; i < len; ++i) + { + result.push_back(from_cbor_internal(v, idx)); + } + return result; + } + + case 0x9f: // array (indefinite length) + { + basic_json result = value_t::array; + while (v.at(idx) != 0xff) + { + result.push_back(from_cbor_internal(v, idx)); + } + // skip break byte (0xFF) + idx += 1; + return result; + } + + // map (0x00..0x17 pairs of data items follow) + case 0xa0: + case 0xa1: + case 0xa2: + case 0xa3: + case 0xa4: + case 0xa5: + case 0xa6: + case 0xa7: + case 0xa8: + case 0xa9: + case 0xaa: + case 0xab: + case 0xac: + case 0xad: + case 0xae: + case 0xaf: + case 0xb0: + case 0xb1: + case 0xb2: + case 0xb3: + case 0xb4: + case 0xb5: + case 0xb6: + case 0xb7: + { + basic_json result = value_t::object; + const auto len = static_cast(v[current_idx] - 0xa0); + for (size_t i = 0; i < len; ++i) + { + std::string key = from_cbor_internal(v, idx); + result[key] = from_cbor_internal(v, idx); + } + return result; + } + + case 0xb8: // map (one-byte uint8_t for n follows) + { + basic_json result = value_t::object; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 1; // skip 1 size byte + for (size_t i = 0; i < len; ++i) + { + std::string key = from_cbor_internal(v, idx); + result[key] = from_cbor_internal(v, idx); + } + return result; + } + + case 0xb9: // map (two-byte uint16_t for n follow) + { + basic_json result = value_t::object; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 2; // skip 2 size bytes + for (size_t i = 0; i < len; ++i) + { + std::string key = from_cbor_internal(v, idx); + result[key] = from_cbor_internal(v, idx); + } + return result; + } + + case 0xba: // map (four-byte uint32_t for n follow) + { + basic_json result = value_t::object; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 4; // skip 4 size bytes + for (size_t i = 0; i < len; ++i) + { + std::string key = from_cbor_internal(v, idx); + result[key] = from_cbor_internal(v, idx); + } + return result; + } + + case 0xbb: // map (eight-byte uint64_t for n follow) + { + basic_json result = value_t::object; + const auto len = static_cast(get_from_vector(v, current_idx)); + idx += 8; // skip 8 size bytes + for (size_t i = 0; i < len; ++i) + { + std::string key = from_cbor_internal(v, idx); + result[key] = from_cbor_internal(v, idx); + } + return result; + } + + case 0xbf: // map (indefinite length) + { + basic_json result = value_t::object; + while (v.at(idx) != 0xff) + { + std::string key = from_cbor_internal(v, idx); + result[key] = from_cbor_internal(v, idx); + } + // skip break byte (0xFF) + idx += 1; + return result; + } + + case 0xf4: // false + { + return false; + } + + case 0xf5: // true + { + return true; + } + + case 0xf6: // null + { + return value_t::null; + } + + case 0xf9: // Half-Precision Float (two-byte IEEE 754) + { + idx += 2; // skip two content bytes + + // code from RFC 7049, Appendix D, Figure 3: + // As half-precision floating-point numbers were only added to + // IEEE 754 in 2008, today's programming platforms often still + // only have limited support for them. It is very easy to + // include at least decoding support for them even without such + // support. An example of a small decoder for half-precision + // floating-point numbers in the C language is shown in Fig. 3. + const int half = (v.at(current_idx + 1) << 8) + v.at(current_idx + 2); + const int exp = (half >> 10) & 0x1f; + const int mant = half & 0x3ff; + double val; + if (exp == 0) + { + val = std::ldexp(mant, -24); + } + else if (exp != 31) + { + val = std::ldexp(mant + 1024, exp - 25); + } + else + { + val = mant == 0 + ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + } + return (half & 0x8000) != 0 ? -val : val; + } + + case 0xfa: // Single-Precision Float (four-byte IEEE 754) + { + // copy bytes in reverse order into the float variable + float res; + for (size_t byte = 0; byte < sizeof(float); ++byte) + { + reinterpret_cast(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte); + } + idx += sizeof(float); // skip content bytes + return res; + } + + case 0xfb: // Double-Precision Float (eight-byte IEEE 754) + { + // copy bytes in reverse order into the double variable + double res; + for (size_t byte = 0; byte < sizeof(double); ++byte) + { + reinterpret_cast(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte); + } + idx += sizeof(double); // skip content bytes + return res; + } + + default: // anything else (0xFF is handled inside the other types) + { + JSON_THROW(std::invalid_argument("error parsing a CBOR @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast(v[current_idx])))); + } + } + } + + public: + /*! + @brief create a MessagePack serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the MessagePack + serialization format. MessagePack is a binary serialization format which + aims to be more compact than JSON itself, yet more efficient to parse. + + @param[in] j JSON value to serialize + @return MessagePack serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in MessagePack format.,to_msgpack} + + @sa http://msgpack.org + @sa @ref from_msgpack(const std::vector&, const size_t) for the + analogous deserialization + @sa @ref to_cbor(const basic_json& for the related CBOR format + + @since version 2.0.9 + */ + static std::vector to_msgpack(const basic_json& j) + { + std::vector result; + to_msgpack_internal(j, result); + return result; + } + + /*! + @brief create a JSON value from a byte vector in MessagePack format + + Deserializes a given byte vector @a v to a JSON value using the MessagePack + serialization format. + + @param[in] v a byte vector in MessagePack format + @param[in] start_index the index to start reading from @a v (0 by default) + @return deserialized JSON value + + @throw std::invalid_argument if unsupported features from MessagePack were + used in the given vector @a v or if the input is not valid MessagePack + @throw std::out_of_range if the given vector ends prematurely + + @complexity Linear in the size of the byte vector @a v. + + @liveexample{The example shows the deserialization of a byte vector in + MessagePack format to a JSON value.,from_msgpack} + + @sa http://msgpack.org + @sa @ref to_msgpack(const basic_json&) for the analogous serialization + @sa @ref from_cbor(const std::vector&, const size_t) for the + related CBOR format + + @since version 2.0.9, parameter @a start_index since 2.1.1 + */ + static basic_json from_msgpack(const std::vector& v, + const size_t start_index = 0) + { + size_t i = start_index; + return from_msgpack_internal(v, i); + } + + /*! + @brief create a MessagePack serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the CBOR (Concise + Binary Object Representation) serialization format. CBOR is a binary + serialization format which aims to be more compact than JSON itself, yet + more efficient to parse. + + @param[in] j JSON value to serialize + @return MessagePack serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in CBOR format.,to_cbor} + + @sa http://cbor.io + @sa @ref from_cbor(const std::vector&, const size_t) for the + analogous deserialization + @sa @ref to_msgpack(const basic_json& for the related MessagePack format + + @since version 2.0.9 + */ + static std::vector to_cbor(const basic_json& j) + { + std::vector result; + to_cbor_internal(j, result); + return result; + } + + /*! + @brief create a JSON value from a byte vector in CBOR format + + Deserializes a given byte vector @a v to a JSON value using the CBOR + (Concise Binary Object Representation) serialization format. + + @param[in] v a byte vector in CBOR format + @param[in] start_index the index to start reading from @a v (0 by default) + @return deserialized JSON value + + @throw std::invalid_argument if unsupported features from CBOR were used in + the given vector @a v or if the input is not valid MessagePack + @throw std::out_of_range if the given vector ends prematurely + + @complexity Linear in the size of the byte vector @a v. + + @liveexample{The example shows the deserialization of a byte vector in CBOR + format to a JSON value.,from_cbor} + + @sa http://cbor.io + @sa @ref to_cbor(const basic_json&) for the analogous serialization + @sa @ref from_msgpack(const std::vector&, const size_t) for the + related MessagePack format + + @since version 2.0.9, parameter @a start_index since 2.1.1 + */ + static basic_json from_cbor(const std::vector& v, + const size_t start_index = 0) + { + size_t i = start_index; + return from_cbor_internal(v, i); + } + + /// @} + + /////////////////////////// + // convenience functions // + /////////////////////////// + + /*! + @brief return the type as string + + Returns the type name as string to be used in error messages - usually to + indicate that a function was called on a wrong JSON type. + + @return basically a string representation of a the @a m_type member + + @complexity Constant. + + @liveexample{The following code exemplifies `type_name()` for all JSON + types.,type_name} + + @since version 1.0.0, public since 2.1.0 + */ + std::string type_name() const + { + { + switch (m_type) + { + case value_t::null: + return "null"; + case value_t::object: + return "object"; + case value_t::array: + return "array"; + case value_t::string: + return "string"; + case value_t::boolean: + return "boolean"; + case value_t::discarded: + return "discarded"; + default: + return "number"; + } + } + } + + private: + /*! + @brief calculates the extra space to escape a JSON string + + @param[in] s the string to escape + @return the number of characters required to escape string @a s + + @complexity Linear in the length of string @a s. + */ + static std::size_t extra_space(const string_t& s) noexcept + { + return std::accumulate(s.begin(), s.end(), size_t{}, + [](size_t res, typename string_t::value_type c) + { + switch (c) + { + case '"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + { + // from c (1 byte) to \x (2 bytes) + return res + 1; + } + + default: + { + if (c >= 0x00 and c <= 0x1f) + { + // from c (1 byte) to \uxxxx (6 bytes) + return res + 5; + } + + return res; + } + } + }); + } + + /*! + @brief escape a string + + Escape a string by replacing certain special characters by a sequence of + an escape character (backslash) and another character and other control + characters by a sequence of "\u" followed by a four-digit hex + representation. + + @param[in] s the string to escape + @return the escaped string + + @complexity Linear in the length of string @a s. + */ + static string_t escape_string(const string_t& s) + { + const auto space = extra_space(s); + if (space == 0) + { + return s; + } + + // create a result string of necessary size + string_t result(s.size() + space, '\\'); + std::size_t pos = 0; + + for (const auto& c : s) + { + switch (c) + { + // quotation mark (0x22) + case '"': + { + result[pos + 1] = '"'; + pos += 2; + break; + } + + // reverse solidus (0x5c) + case '\\': + { + // nothing to change + pos += 2; + break; + } + + // backspace (0x08) + case '\b': + { + result[pos + 1] = 'b'; + pos += 2; + break; + } + + // formfeed (0x0c) + case '\f': + { + result[pos + 1] = 'f'; + pos += 2; + break; + } + + // newline (0x0a) + case '\n': + { + result[pos + 1] = 'n'; + pos += 2; + break; + } + + // carriage return (0x0d) + case '\r': + { + result[pos + 1] = 'r'; + pos += 2; + break; + } + + // horizontal tab (0x09) + case '\t': + { + result[pos + 1] = 't'; + pos += 2; + break; + } + + default: + { + if (c >= 0x00 and c <= 0x1f) + { + // convert a number 0..15 to its hex representation + // (0..f) + static const char hexify[16] = + { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + + // print character c as \uxxxx + for (const char m : + { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f] + }) + { + result[++pos] = m; + } + + ++pos; + } + else + { + // all other characters are added as-is + result[pos++] = c; + } + break; + } + } + } + + return result; + } + + + /*! + @brief locale-independent serialization for built-in arithmetic types + */ + struct numtostr + { + public: + template + numtostr(NumberType value) + { + x_write(value, std::is_integral()); + } + + const char* c_str() const + { + return m_buf.data(); + } + + private: + /// a (hopefully) large enough character buffer + std::array < char, 64 > m_buf{{}}; + + template + void x_write(NumberType x, /*is_integral=*/std::true_type) + { + // special case for "0" + if (x == 0) + { + m_buf[0] = '0'; + return; + } + + const bool is_negative = x < 0; + size_t i = 0; + + // spare 1 byte for '\0' + while (x != 0 and i < m_buf.size() - 1) + { + const auto digit = std::labs(static_cast(x % 10)); + m_buf[i++] = static_cast('0' + digit); + x /= 10; + } + + // make sure the number has been processed completely + assert(x == 0); + + if (is_negative) + { + // make sure there is capacity for the '-' + assert(i < m_buf.size() - 2); + m_buf[i++] = '-'; + } + + std::reverse(m_buf.begin(), m_buf.begin() + i); + } + + template + void x_write(NumberType x, /*is_integral=*/std::false_type) + { + // special case for 0.0 and -0.0 + if (x == 0) + { + size_t i = 0; + if (std::signbit(x)) + { + m_buf[i++] = '-'; + } + m_buf[i++] = '0'; + m_buf[i++] = '.'; + m_buf[i] = '0'; + return; + } + + // get number of digits for a text -> float -> text round-trip + static constexpr auto d = std::numeric_limits::digits10; + + // the actual conversion + const auto written_bytes = snprintf(m_buf.data(), m_buf.size(), "%.*g", d, x); + + // negative value indicates an error + assert(written_bytes > 0); + // check if buffer was large enough + assert(static_cast(written_bytes) < m_buf.size()); + + // read information from locale + const auto loc = localeconv(); + assert(loc != nullptr); + const char thousands_sep = !loc->thousands_sep ? '\0' + : loc->thousands_sep[0]; + + const char decimal_point = !loc->decimal_point ? '\0' + : loc->decimal_point[0]; + + // erase thousands separator + if (thousands_sep != '\0') + { + const auto end = std::remove(m_buf.begin(), m_buf.begin() + written_bytes, thousands_sep); + std::fill(end, m_buf.end(), '\0'); + } + + // convert decimal point to '.' + if (decimal_point != '\0' and decimal_point != '.') + { + for (auto& c : m_buf) + { + if (c == decimal_point) + { + c = '.'; + break; + } + } + } + + // determine if need to append ".0" + size_t i = 0; + bool value_is_int_like = true; + for (i = 0; i < m_buf.size(); ++i) + { + // break when end of number is reached + if (m_buf[i] == '\0') + { + break; + } + + // check if we find non-int character + value_is_int_like = value_is_int_like and m_buf[i] != '.' and + m_buf[i] != 'e' and m_buf[i] != 'E'; + } + + if (value_is_int_like) + { + // there must be 2 bytes left for ".0" + assert((i + 2) < m_buf.size()); + // we write to the end of the number + assert(m_buf[i] == '\0'); + assert(m_buf[i - 1] != '\0'); + + // add ".0" + m_buf[i] = '.'; + m_buf[i + 1] = '0'; + + // the resulting string is properly terminated + assert(m_buf[i + 2] == '\0'); + } + } + }; + + + /*! + @brief internal implementation of the serialization function + + This function is called by the public member function dump and organizes + the serialization internally. The indentation level is propagated as + additional parameter. In case of arrays and objects, the function is + called recursively. Note that + + - strings and object keys are escaped using `escape_string()` + - integer numbers are converted implicitly via `operator<<` + - floating-point numbers are converted to a string using `"%g"` format + + @param[out] o stream to write to + @param[in] pretty_print whether the output shall be pretty-printed + @param[in] indent_step the indent level + @param[in] current_indent the current indent level (only used internally) + */ + void dump(std::ostream& o, + const bool pretty_print, + const unsigned int indent_step, + const unsigned int current_indent = 0) const + { + // variable to hold indentation for recursive calls + unsigned int new_indent = current_indent; + + switch (m_type) + { + case value_t::object: + { + if (m_value.object->empty()) + { + o << "{}"; + return; + } + + o << "{"; + + // increase indentation + if (pretty_print) + { + new_indent += indent_step; + o << "\n"; + } + + for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i) + { + if (i != m_value.object->cbegin()) + { + o << (pretty_print ? ",\n" : ","); + } + o << string_t(new_indent, ' ') << "\"" + << escape_string(i->first) << "\":" + << (pretty_print ? " " : ""); + i->second.dump(o, pretty_print, indent_step, new_indent); + } + + // decrease indentation + if (pretty_print) + { + new_indent -= indent_step; + o << "\n"; + } + + o << string_t(new_indent, ' ') + "}"; + return; + } + + case value_t::array: + { + if (m_value.array->empty()) + { + o << "[]"; + return; + } + + o << "["; + + // increase indentation + if (pretty_print) + { + new_indent += indent_step; + o << "\n"; + } + + for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i) + { + if (i != m_value.array->cbegin()) + { + o << (pretty_print ? ",\n" : ","); + } + o << string_t(new_indent, ' '); + i->dump(o, pretty_print, indent_step, new_indent); + } + + // decrease indentation + if (pretty_print) + { + new_indent -= indent_step; + o << "\n"; + } + + o << string_t(new_indent, ' ') << "]"; + return; + } + + case value_t::string: + { + o << string_t("\"") << escape_string(*m_value.string) << "\""; + return; + } + + case value_t::boolean: + { + o << (m_value.boolean ? "true" : "false"); + return; + } + + case value_t::number_integer: + { + o << numtostr(m_value.number_integer).c_str(); + return; + } + + case value_t::number_unsigned: + { + o << numtostr(m_value.number_unsigned).c_str(); + return; + } + + case value_t::number_float: + { + o << numtostr(m_value.number_float).c_str(); + return; + } + + case value_t::discarded: + { + o << ""; + return; + } + + case value_t::null: + { + o << "null"; + return; + } + } + } + + private: + ////////////////////// + // member variables // + ////////////////////// + + /// the type of the current element + value_t m_type = value_t::null; + + /// the value of the current element + json_value m_value = {}; + + + private: + /////////////// + // iterators // + /////////////// + + /*! + @brief an iterator for primitive JSON types + + This class models an iterator for primitive JSON types (boolean, number, + string). It's only purpose is to allow the iterator/const_iterator classes + to "iterate" over primitive values. Internally, the iterator is modeled by + a `difference_type` variable. Value begin_value (`0`) models the begin, + end_value (`1`) models past the end. + */ + class primitive_iterator_t + { + public: + + difference_type get_value() const noexcept + { + return m_it; + } + /// set iterator to a defined beginning + void set_begin() noexcept + { + m_it = begin_value; + } + + /// set iterator to a defined past the end + void set_end() noexcept + { + m_it = end_value; + } + + /// return whether the iterator can be dereferenced + constexpr bool is_begin() const noexcept + { + return (m_it == begin_value); + } + + /// return whether the iterator is at end + constexpr bool is_end() const noexcept + { + return (m_it == end_value); + } + + friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it == rhs.m_it; + } + + friend constexpr bool operator!=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return !(lhs == rhs); + } + + friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it < rhs.m_it; + } + + friend constexpr bool operator<=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it <= rhs.m_it; + } + + friend constexpr bool operator>(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it > rhs.m_it; + } + + friend constexpr bool operator>=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it >= rhs.m_it; + } + + primitive_iterator_t operator+(difference_type i) + { + auto result = *this; + result += i; + return result; + } + + friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it - rhs.m_it; + } + + friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it) + { + return os << it.m_it; + } + + primitive_iterator_t& operator++() + { + ++m_it; + return *this; + } + + primitive_iterator_t operator++(int) + { + auto result = *this; + m_it++; + return result; + } + + primitive_iterator_t& operator--() + { + --m_it; + return *this; + } + + primitive_iterator_t operator--(int) + { + auto result = *this; + m_it--; + return result; + } + + primitive_iterator_t& operator+=(difference_type n) + { + m_it += n; + return *this; + } + + primitive_iterator_t& operator-=(difference_type n) + { + m_it -= n; + return *this; + } + + private: + static constexpr difference_type begin_value = 0; + static constexpr difference_type end_value = begin_value + 1; + + /// iterator as signed integer type + difference_type m_it = std::numeric_limits::denorm_min(); + }; + + /*! + @brief an iterator value + + @note This structure could easily be a union, but MSVC currently does not + allow unions members with complex constructors, see + https://github.com/nlohmann/json/pull/105. + */ + struct internal_iterator + { + /// iterator for JSON objects + typename object_t::iterator object_iterator; + /// iterator for JSON arrays + typename array_t::iterator array_iterator; + /// generic iterator for all other types + primitive_iterator_t primitive_iterator; + + /// create an uninitialized internal_iterator + internal_iterator() noexcept + : object_iterator(), array_iterator(), primitive_iterator() + {} + }; + + /// proxy class for the iterator_wrapper functions + template + class iteration_proxy + { + private: + /// helper class for iteration + class iteration_proxy_internal + { + private: + /// the iterator + IteratorType anchor; + /// an index for arrays (used to create key names) + size_t array_index = 0; + + public: + explicit iteration_proxy_internal(IteratorType it) noexcept + : anchor(it) + {} + + /// dereference operator (needed for range-based for) + iteration_proxy_internal& operator*() + { + return *this; + } + + /// increment operator (needed for range-based for) + iteration_proxy_internal& operator++() + { + ++anchor; + ++array_index; + + return *this; + } + + /// inequality operator (needed for range-based for) + bool operator!= (const iteration_proxy_internal& o) const + { + return anchor != o.anchor; + } + + /// return key of the iterator + typename basic_json::string_t key() const + { + assert(anchor.m_object != nullptr); + + switch (anchor.m_object->type()) + { + // use integer array index as key + case value_t::array: + { + return std::to_string(array_index); + } + + // use key from the object + case value_t::object: + { + return anchor.key(); + } + + // use an empty key for all primitive types + default: + { + return ""; + } + } + } + + /// return value of the iterator + typename IteratorType::reference value() const + { + return anchor.value(); + } + }; + + /// the container to iterate + typename IteratorType::reference container; + + public: + /// construct iteration proxy from a container + explicit iteration_proxy(typename IteratorType::reference cont) + : container(cont) + {} + + /// return iterator begin (needed for range-based for) + iteration_proxy_internal begin() noexcept + { + return iteration_proxy_internal(container.begin()); + } + + /// return iterator end (needed for range-based for) + iteration_proxy_internal end() noexcept + { + return iteration_proxy_internal(container.end()); + } + }; + + public: + /*! + @brief a template for a random access iterator for the @ref basic_json class + + This class implements a both iterators (iterator and const_iterator) for the + @ref basic_json class. + + @note An iterator is called *initialized* when a pointer to a JSON value + has been set (e.g., by a constructor or a copy assignment). If the + iterator is default-constructed, it is *uninitialized* and most + methods are undefined. **The library uses assertions to detect calls + on uninitialized iterators.** + + @requirement The class satisfies the following concept requirements: + - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): + The iterator that can be moved to point (forward and backward) to any + element in constant time. + + @since version 1.0.0, simplified in version 2.0.9 + */ + template + class iter_impl : public std::iterator + { + /// allow basic_json to access private members + friend class basic_json; + + // make sure U is basic_json or const basic_json + static_assert(std::is_same::value + or std::is_same::value, + "iter_impl only accepts (const) basic_json"); + + public: + /// the type of the values when the iterator is dereferenced + using value_type = typename basic_json::value_type; + /// a type to represent differences between iterators + using difference_type = typename basic_json::difference_type; + /// defines a pointer to the type iterated over (value_type) + using pointer = typename std::conditional::value, + typename basic_json::const_pointer, + typename basic_json::pointer>::type; + /// defines a reference to the type iterated over (value_type) + using reference = typename std::conditional::value, + typename basic_json::const_reference, + typename basic_json::reference>::type; + /// the category of the iterator + using iterator_category = std::bidirectional_iterator_tag; + + /// default constructor + iter_impl() = default; + + /*! + @brief constructor for a given JSON instance + @param[in] object pointer to a JSON object for this iterator + @pre object != nullptr + @post The iterator is initialized; i.e. `m_object != nullptr`. + */ + explicit iter_impl(pointer object) noexcept + : m_object(object) + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + m_it.object_iterator = typename object_t::iterator(); + break; + } + + case basic_json::value_t::array: + { + m_it.array_iterator = typename array_t::iterator(); + break; + } + + default: + { + m_it.primitive_iterator = primitive_iterator_t(); + break; + } + } + } + + /* + Use operator `const_iterator` instead of `const_iterator(const iterator& + other) noexcept` to avoid two class definitions for @ref iterator and + @ref const_iterator. + + This function is only called if this class is an @ref iterator. If this + class is a @ref const_iterator this function is not called. + */ + operator const_iterator() const + { + const_iterator ret; + + if (m_object) + { + ret.m_object = m_object; + ret.m_it = m_it; + } + + return ret; + } + + /*! + @brief copy constructor + @param[in] other iterator to copy from + @note It is not checked whether @a other is initialized. + */ + iter_impl(const iter_impl& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief copy assignment + @param[in,out] other iterator to copy from + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(iter_impl other) noexcept( + std::is_nothrow_move_constructible::value and + std::is_nothrow_move_assignable::value and + std::is_nothrow_move_constructible::value and + std::is_nothrow_move_assignable::value + ) + { + std::swap(m_object, other.m_object); + std::swap(m_it, other.m_it); + return *this; + } + + private: + /*! + @brief set the iterator to the first value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_begin() noexcept + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + m_it.object_iterator = m_object->m_value.object->begin(); + break; + } + + case basic_json::value_t::array: + { + m_it.array_iterator = m_object->m_value.array->begin(); + break; + } + + case basic_json::value_t::null: + { + // set to end so begin()==end() is true: null is empty + m_it.primitive_iterator.set_end(); + break; + } + + default: + { + m_it.primitive_iterator.set_begin(); + break; + } + } + } + + /*! + @brief set the iterator past the last value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_end() noexcept + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + m_it.object_iterator = m_object->m_value.object->end(); + break; + } + + case basic_json::value_t::array: + { + m_it.array_iterator = m_object->m_value.array->end(); + break; + } + + default: + { + m_it.primitive_iterator.set_end(); + break; + } + } + } + + public: + /*! + @brief return a reference to the value pointed to by the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator*() const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + assert(m_it.object_iterator != m_object->m_value.object->end()); + return m_it.object_iterator->second; + } + + case basic_json::value_t::array: + { + assert(m_it.array_iterator != m_object->m_value.array->end()); + return *m_it.array_iterator; + } + + case basic_json::value_t::null: + { + JSON_THROW(std::out_of_range("cannot get value")); + } + + default: + { + if (m_it.primitive_iterator.is_begin()) + { + return *m_object; + } + + JSON_THROW(std::out_of_range("cannot get value")); + } + } + } + + /*! + @brief dereference the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + pointer operator->() const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + assert(m_it.object_iterator != m_object->m_value.object->end()); + return &(m_it.object_iterator->second); + } + + case basic_json::value_t::array: + { + assert(m_it.array_iterator != m_object->m_value.array->end()); + return &*m_it.array_iterator; + } + + default: + { + if (m_it.primitive_iterator.is_begin()) + { + return m_object; + } + + JSON_THROW(std::out_of_range("cannot get value")); + } + } + } + + /*! + @brief post-increment (it++) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator++(int) + { + auto result = *this; + ++(*this); + return result; + } + + /*! + @brief pre-increment (++it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator++() + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + std::advance(m_it.object_iterator, 1); + break; + } + + case basic_json::value_t::array: + { + std::advance(m_it.array_iterator, 1); + break; + } + + default: + { + ++m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief post-decrement (it--) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator--(int) + { + auto result = *this; + --(*this); + return result; + } + + /*! + @brief pre-decrement (--it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator--() + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + std::advance(m_it.object_iterator, -1); + break; + } + + case basic_json::value_t::array: + { + std::advance(m_it.array_iterator, -1); + break; + } + + default: + { + --m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief comparison: equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator==(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (m_object != other.m_object) + { + JSON_THROW(std::domain_error("cannot compare iterators of different containers")); + } + + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + return (m_it.object_iterator == other.m_it.object_iterator); + } + + case basic_json::value_t::array: + { + return (m_it.array_iterator == other.m_it.array_iterator); + } + + default: + { + return (m_it.primitive_iterator == other.m_it.primitive_iterator); + } + } + } + + /*! + @brief comparison: not equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator!=(const iter_impl& other) const + { + return not operator==(other); + } + + /*! + @brief comparison: smaller + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (m_object != other.m_object) + { + JSON_THROW(std::domain_error("cannot compare iterators of different containers")); + } + + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + JSON_THROW(std::domain_error("cannot compare order of object iterators")); + } + + case basic_json::value_t::array: + { + return (m_it.array_iterator < other.m_it.array_iterator); + } + + default: + { + return (m_it.primitive_iterator < other.m_it.primitive_iterator); + } + } + } + + /*! + @brief comparison: less than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<=(const iter_impl& other) const + { + return not other.operator < (*this); + } + + /*! + @brief comparison: greater than + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>(const iter_impl& other) const + { + return not operator<=(other); + } + + /*! + @brief comparison: greater than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>=(const iter_impl& other) const + { + return not operator<(other); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator+=(difference_type i) + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + JSON_THROW(std::domain_error("cannot use offsets with object iterators")); + } + + case basic_json::value_t::array: + { + std::advance(m_it.array_iterator, i); + break; + } + + default: + { + m_it.primitive_iterator += i; + break; + } + } + + return *this; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator-=(difference_type i) + { + return operator+=(-i); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator+(difference_type i) + { + auto result = *this; + result += i; + return result; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator-(difference_type i) + { + auto result = *this; + result -= i; + return result; + } + + /*! + @brief return difference + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + difference_type operator-(const iter_impl& other) const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + JSON_THROW(std::domain_error("cannot use offsets with object iterators")); + } + + case basic_json::value_t::array: + { + return m_it.array_iterator - other.m_it.array_iterator; + } + + default: + { + return m_it.primitive_iterator - other.m_it.primitive_iterator; + } + } + } + + /*! + @brief access to successor + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator[](difference_type n) const + { + assert(m_object != nullptr); + + switch (m_object->m_type) + { + case basic_json::value_t::object: + { + JSON_THROW(std::domain_error("cannot use operator[] for object iterators")); + } + + case basic_json::value_t::array: + { + return *std::next(m_it.array_iterator, n); + } + + case basic_json::value_t::null: + { + JSON_THROW(std::out_of_range("cannot get value")); + } + + default: + { + if (m_it.primitive_iterator.get_value() == -n) + { + return *m_object; + } + + JSON_THROW(std::out_of_range("cannot get value")); + } + } + } + + /*! + @brief return the key of an object iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + typename object_t::key_type key() const + { + assert(m_object != nullptr); + + if (m_object->is_object()) + { + return m_it.object_iterator->first; + } + + JSON_THROW(std::domain_error("cannot use key() for non-object iterators")); + } + + /*! + @brief return the value of an iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference value() const + { + return operator*(); + } + + private: + /// associated JSON instance + pointer m_object = nullptr; + /// the actual iterator of the associated instance + internal_iterator m_it = internal_iterator(); + }; + + /*! + @brief a template for a reverse iterator class + + @tparam Base the base iterator type to reverse. Valid types are @ref + iterator (to create @ref reverse_iterator) and @ref const_iterator (to + create @ref const_reverse_iterator). + + @requirement The class satisfies the following concept requirements: + - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): + The iterator that can be moved to point (forward and backward) to any + element in constant time. + - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator): + It is possible to write to the pointed-to element (only if @a Base is + @ref iterator). + + @since version 1.0.0 + */ + template + class json_reverse_iterator : public std::reverse_iterator + { + public: + /// shortcut to the reverse iterator adaptor + using base_iterator = std::reverse_iterator; + /// the reference type for the pointed-to element + using reference = typename Base::reference; + + /// create reverse iterator from iterator + json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept + : base_iterator(it) + {} + + /// create reverse iterator from base class + json_reverse_iterator(const base_iterator& it) noexcept + : base_iterator(it) + {} + + /// post-increment (it++) + json_reverse_iterator operator++(int) + { + return base_iterator::operator++(1); + } + + /// pre-increment (++it) + json_reverse_iterator& operator++() + { + base_iterator::operator++(); + return *this; + } + + /// post-decrement (it--) + json_reverse_iterator operator--(int) + { + return base_iterator::operator--(1); + } + + /// pre-decrement (--it) + json_reverse_iterator& operator--() + { + base_iterator::operator--(); + return *this; + } + + /// add to iterator + json_reverse_iterator& operator+=(difference_type i) + { + base_iterator::operator+=(i); + return *this; + } + + /// add to iterator + json_reverse_iterator operator+(difference_type i) const + { + auto result = *this; + result += i; + return result; + } + + /// subtract from iterator + json_reverse_iterator operator-(difference_type i) const + { + auto result = *this; + result -= i; + return result; + } + + /// return difference + difference_type operator-(const json_reverse_iterator& other) const + { + return this->base() - other.base(); + } + + /// access to successor + reference operator[](difference_type n) const + { + return *(this->operator+(n)); + } + + /// return the key of an object iterator + typename object_t::key_type key() const + { + auto it = --this->base(); + return it.key(); + } + + /// return the value of an iterator + reference value() const + { + auto it = --this->base(); + return it.operator * (); + } + }; + + + private: + ////////////////////// + // lexer and parser // + ////////////////////// + + /*! + @brief lexical analysis + + This class organizes the lexical analysis during JSON deserialization. The + core of it is a scanner generated by [re2c](http://re2c.org) that + processes a buffer and recognizes tokens according to RFC 7159. + */ + class lexer + { + public: + /// token types for the parser + enum class token_type + { + uninitialized, ///< indicating the scanner is uninitialized + literal_true, ///< the `true` literal + literal_false, ///< the `false` literal + literal_null, ///< the `null` literal + value_string, ///< a string -- use get_string() for actual value + value_unsigned, ///< an unsigned integer -- use get_number() for actual value + value_integer, ///< a signed integer -- use get_number() for actual value + value_float, ///< an floating point number -- use get_number() for actual value + begin_array, ///< the character for array begin `[` + begin_object, ///< the character for object begin `{` + end_array, ///< the character for array end `]` + end_object, ///< the character for object end `}` + name_separator, ///< the name separator `:` + value_separator, ///< the value separator `,` + parse_error, ///< indicating a parse error + end_of_input ///< indicating the end of the input buffer + }; + + /// the char type to use in the lexer + using lexer_char_t = unsigned char; + + /// a lexer from a buffer with given length + lexer(const lexer_char_t* buff, const size_t len) noexcept + : m_content(buff) + { + assert(m_content != nullptr); + m_start = m_cursor = m_content; + m_limit = m_content + len; + } + + /// a lexer from an input stream + explicit lexer(std::istream& s) + : m_stream(&s), m_line_buffer() + { + // immediately abort if stream is erroneous + if (s.fail()) + { + JSON_THROW(std::invalid_argument("stream error")); + } + + // fill buffer + fill_line_buffer(); + + // skip UTF-8 byte-order mark + if (m_line_buffer.size() >= 3 and m_line_buffer.substr(0, 3) == "\xEF\xBB\xBF") + { + m_line_buffer[0] = ' '; + m_line_buffer[1] = ' '; + m_line_buffer[2] = ' '; + } + } + + // switch off unwanted functions (due to pointer members) + lexer() = delete; + lexer(const lexer&) = delete; + lexer operator=(const lexer&) = delete; + + /*! + @brief create a string from one or two Unicode code points + + There are two cases: (1) @a codepoint1 is in the Basic Multilingual + Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2) + @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to + represent a code point above U+FFFF. + + @param[in] codepoint1 the code point (can be high surrogate) + @param[in] codepoint2 the code point (can be low surrogate or 0) + + @return string representation of the code point; the length of the + result string is between 1 and 4 characters. + + @throw std::out_of_range if code point is > 0x10ffff; example: `"code + points above 0x10FFFF are invalid"` + @throw std::invalid_argument if the low surrogate is invalid; example: + `""missing or wrong low surrogate""` + + @complexity Constant. + + @see + */ + static string_t to_unicode(const std::size_t codepoint1, + const std::size_t codepoint2 = 0) + { + // calculate the code point from the given code points + std::size_t codepoint = codepoint1; + + // check if codepoint1 is a high surrogate + if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF) + { + // check if codepoint2 is a low surrogate + if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF) + { + codepoint = + // high surrogate occupies the most significant 22 bits + (codepoint1 << 10) + // low surrogate occupies the least significant 15 bits + + codepoint2 + // there is still the 0xD800, 0xDC00 and 0x10000 noise + // in the result so we have to subtract with: + // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 + - 0x35FDC00; + } + else + { + JSON_THROW(std::invalid_argument("missing or wrong low surrogate")); + } + } + + string_t result; + + if (codepoint < 0x80) + { + // 1-byte characters: 0xxxxxxx (ASCII) + result.append(1, static_cast(codepoint)); + } + else if (codepoint <= 0x7ff) + { + // 2-byte characters: 110xxxxx 10xxxxxx + result.append(1, static_cast(0xC0 | ((codepoint >> 6) & 0x1F))); + result.append(1, static_cast(0x80 | (codepoint & 0x3F))); + } + else if (codepoint <= 0xffff) + { + // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx + result.append(1, static_cast(0xE0 | ((codepoint >> 12) & 0x0F))); + result.append(1, static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + result.append(1, static_cast(0x80 | (codepoint & 0x3F))); + } + else if (codepoint <= 0x10ffff) + { + // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + result.append(1, static_cast(0xF0 | ((codepoint >> 18) & 0x07))); + result.append(1, static_cast(0x80 | ((codepoint >> 12) & 0x3F))); + result.append(1, static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + result.append(1, static_cast(0x80 | (codepoint & 0x3F))); + } + else + { + JSON_THROW(std::out_of_range("code points above 0x10FFFF are invalid")); + } + + return result; + } + + /// return name of values of type token_type (only used for errors) + static std::string token_type_name(const token_type t) + { + switch (t) + { + case token_type::uninitialized: + return ""; + case token_type::literal_true: + return "true literal"; + case token_type::literal_false: + return "false literal"; + case token_type::literal_null: + return "null literal"; + case token_type::value_string: + return "string literal"; + case lexer::token_type::value_unsigned: + case lexer::token_type::value_integer: + case lexer::token_type::value_float: + return "number literal"; + case token_type::begin_array: + return "'['"; + case token_type::begin_object: + return "'{'"; + case token_type::end_array: + return "']'"; + case token_type::end_object: + return "'}'"; + case token_type::name_separator: + return "':'"; + case token_type::value_separator: + return "','"; + case token_type::parse_error: + return ""; + case token_type::end_of_input: + return "end of input"; + default: + { + // catch non-enum values + return "unknown token"; // LCOV_EXCL_LINE + } + } + } + + /*! + This function implements a scanner for JSON. It is specified using + regular expressions that try to follow RFC 7159 as close as possible. + These regular expressions are then translated into a minimized + deterministic finite automaton (DFA) by the tool + [re2c](http://re2c.org). As a result, the translated code for this + function consists of a large block of code with `goto` jumps. + + @return the class of the next token read from the buffer + + @complexity Linear in the length of the input.\n + + Proposition: The loop below will always terminate for finite input.\n + + Proof (by contradiction): Assume a finite input. To loop forever, the + loop must never hit code with a `break` statement. The only code + snippets without a `break` statement are the continue statements for + whitespace and byte-order-marks. To loop forever, the input must be an + infinite sequence of whitespace or byte-order-marks. This contradicts + the assumption of finite input, q.e.d. + */ + token_type scan() + { + while (true) + { + // pointer for backtracking information + m_marker = nullptr; + + // remember the begin of the token + m_start = m_cursor; + assert(m_start != nullptr); + + + { + lexer_char_t yych; + unsigned int yyaccept = 0; + static const unsigned char yybm[] = + { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 32, 32, 0, 0, 32, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 160, 128, 0, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 192, 192, 192, 192, 192, 192, 192, 192, + 192, 192, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 0, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 128, 128, 128, 128, 128, 128, 128, 128, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + }; + if ((m_limit - m_cursor) < 5) + { + fill_line_buffer(5); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yybm[0 + yych] & 32) + { + goto basic_json_parser_6; + } + if (yych <= '[') + { + if (yych <= '-') + { + if (yych <= '"') + { + if (yych <= 0x00) + { + goto basic_json_parser_2; + } + if (yych <= '!') + { + goto basic_json_parser_4; + } + goto basic_json_parser_9; + } + else + { + if (yych <= '+') + { + goto basic_json_parser_4; + } + if (yych <= ',') + { + goto basic_json_parser_10; + } + goto basic_json_parser_12; + } + } + else + { + if (yych <= '9') + { + if (yych <= '/') + { + goto basic_json_parser_4; + } + if (yych <= '0') + { + goto basic_json_parser_13; + } + goto basic_json_parser_15; + } + else + { + if (yych <= ':') + { + goto basic_json_parser_17; + } + if (yych <= 'Z') + { + goto basic_json_parser_4; + } + goto basic_json_parser_19; + } + } + } + else + { + if (yych <= 'n') + { + if (yych <= 'e') + { + if (yych == ']') + { + goto basic_json_parser_21; + } + goto basic_json_parser_4; + } + else + { + if (yych <= 'f') + { + goto basic_json_parser_23; + } + if (yych <= 'm') + { + goto basic_json_parser_4; + } + goto basic_json_parser_24; + } + } + else + { + if (yych <= 'z') + { + if (yych == 't') + { + goto basic_json_parser_25; + } + goto basic_json_parser_4; + } + else + { + if (yych <= '{') + { + goto basic_json_parser_26; + } + if (yych == '}') + { + goto basic_json_parser_28; + } + goto basic_json_parser_4; + } + } + } +basic_json_parser_2: + ++m_cursor; + { + last_token_type = token_type::end_of_input; + break; + } +basic_json_parser_4: + ++m_cursor; +basic_json_parser_5: + { + last_token_type = token_type::parse_error; + break; + } +basic_json_parser_6: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yybm[0 + yych] & 32) + { + goto basic_json_parser_6; + } + { + continue; + } +basic_json_parser_9: + yyaccept = 0; + yych = *(m_marker = ++m_cursor); + if (yych <= 0x1F) + { + goto basic_json_parser_5; + } + if (yych <= 0x7F) + { + goto basic_json_parser_31; + } + if (yych <= 0xC1) + { + goto basic_json_parser_5; + } + if (yych <= 0xF4) + { + goto basic_json_parser_31; + } + goto basic_json_parser_5; +basic_json_parser_10: + ++m_cursor; + { + last_token_type = token_type::value_separator; + break; + } +basic_json_parser_12: + yych = *++m_cursor; + if (yych <= '/') + { + goto basic_json_parser_5; + } + if (yych <= '0') + { + goto basic_json_parser_43; + } + if (yych <= '9') + { + goto basic_json_parser_45; + } + goto basic_json_parser_5; +basic_json_parser_13: + yyaccept = 1; + yych = *(m_marker = ++m_cursor); + if (yych <= '9') + { + if (yych == '.') + { + goto basic_json_parser_47; + } + if (yych >= '0') + { + goto basic_json_parser_48; + } + } + else + { + if (yych <= 'E') + { + if (yych >= 'E') + { + goto basic_json_parser_51; + } + } + else + { + if (yych == 'e') + { + goto basic_json_parser_51; + } + } + } +basic_json_parser_14: + { + last_token_type = token_type::value_unsigned; + break; + } +basic_json_parser_15: + yyaccept = 1; + m_marker = ++m_cursor; + if ((m_limit - m_cursor) < 3) + { + fill_line_buffer(3); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yybm[0 + yych] & 64) + { + goto basic_json_parser_15; + } + if (yych <= 'D') + { + if (yych == '.') + { + goto basic_json_parser_47; + } + goto basic_json_parser_14; + } + else + { + if (yych <= 'E') + { + goto basic_json_parser_51; + } + if (yych == 'e') + { + goto basic_json_parser_51; + } + goto basic_json_parser_14; + } +basic_json_parser_17: + ++m_cursor; + { + last_token_type = token_type::name_separator; + break; + } +basic_json_parser_19: + ++m_cursor; + { + last_token_type = token_type::begin_array; + break; + } +basic_json_parser_21: + ++m_cursor; + { + last_token_type = token_type::end_array; + break; + } +basic_json_parser_23: + yyaccept = 0; + yych = *(m_marker = ++m_cursor); + if (yych == 'a') + { + goto basic_json_parser_52; + } + goto basic_json_parser_5; +basic_json_parser_24: + yyaccept = 0; + yych = *(m_marker = ++m_cursor); + if (yych == 'u') + { + goto basic_json_parser_53; + } + goto basic_json_parser_5; +basic_json_parser_25: + yyaccept = 0; + yych = *(m_marker = ++m_cursor); + if (yych == 'r') + { + goto basic_json_parser_54; + } + goto basic_json_parser_5; +basic_json_parser_26: + ++m_cursor; + { + last_token_type = token_type::begin_object; + break; + } +basic_json_parser_28: + ++m_cursor; + { + last_token_type = token_type::end_object; + break; + } +basic_json_parser_30: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; +basic_json_parser_31: + if (yybm[0 + yych] & 128) + { + goto basic_json_parser_30; + } + if (yych <= 0xE0) + { + if (yych <= '\\') + { + if (yych <= 0x1F) + { + goto basic_json_parser_32; + } + if (yych <= '"') + { + goto basic_json_parser_33; + } + goto basic_json_parser_35; + } + else + { + if (yych <= 0xC1) + { + goto basic_json_parser_32; + } + if (yych <= 0xDF) + { + goto basic_json_parser_36; + } + goto basic_json_parser_37; + } + } + else + { + if (yych <= 0xEF) + { + if (yych == 0xED) + { + goto basic_json_parser_39; + } + goto basic_json_parser_38; + } + else + { + if (yych <= 0xF0) + { + goto basic_json_parser_40; + } + if (yych <= 0xF3) + { + goto basic_json_parser_41; + } + if (yych <= 0xF4) + { + goto basic_json_parser_42; + } + } + } +basic_json_parser_32: + m_cursor = m_marker; + if (yyaccept <= 1) + { + if (yyaccept == 0) + { + goto basic_json_parser_5; + } + else + { + goto basic_json_parser_14; + } + } + else + { + if (yyaccept == 2) + { + goto basic_json_parser_44; + } + else + { + goto basic_json_parser_58; + } + } +basic_json_parser_33: + ++m_cursor; + { + last_token_type = token_type::value_string; + break; + } +basic_json_parser_35: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 'e') + { + if (yych <= '/') + { + if (yych == '"') + { + goto basic_json_parser_30; + } + if (yych <= '.') + { + goto basic_json_parser_32; + } + goto basic_json_parser_30; + } + else + { + if (yych <= '\\') + { + if (yych <= '[') + { + goto basic_json_parser_32; + } + goto basic_json_parser_30; + } + else + { + if (yych == 'b') + { + goto basic_json_parser_30; + } + goto basic_json_parser_32; + } + } + } + else + { + if (yych <= 'q') + { + if (yych <= 'f') + { + goto basic_json_parser_30; + } + if (yych == 'n') + { + goto basic_json_parser_30; + } + goto basic_json_parser_32; + } + else + { + if (yych <= 's') + { + if (yych <= 'r') + { + goto basic_json_parser_30; + } + goto basic_json_parser_32; + } + else + { + if (yych <= 't') + { + goto basic_json_parser_30; + } + if (yych <= 'u') + { + goto basic_json_parser_55; + } + goto basic_json_parser_32; + } + } + } +basic_json_parser_36: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 0x7F) + { + goto basic_json_parser_32; + } + if (yych <= 0xBF) + { + goto basic_json_parser_30; + } + goto basic_json_parser_32; +basic_json_parser_37: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 0x9F) + { + goto basic_json_parser_32; + } + if (yych <= 0xBF) + { + goto basic_json_parser_36; + } + goto basic_json_parser_32; +basic_json_parser_38: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 0x7F) + { + goto basic_json_parser_32; + } + if (yych <= 0xBF) + { + goto basic_json_parser_36; + } + goto basic_json_parser_32; +basic_json_parser_39: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 0x7F) + { + goto basic_json_parser_32; + } + if (yych <= 0x9F) + { + goto basic_json_parser_36; + } + goto basic_json_parser_32; +basic_json_parser_40: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 0x8F) + { + goto basic_json_parser_32; + } + if (yych <= 0xBF) + { + goto basic_json_parser_38; + } + goto basic_json_parser_32; +basic_json_parser_41: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 0x7F) + { + goto basic_json_parser_32; + } + if (yych <= 0xBF) + { + goto basic_json_parser_38; + } + goto basic_json_parser_32; +basic_json_parser_42: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 0x7F) + { + goto basic_json_parser_32; + } + if (yych <= 0x8F) + { + goto basic_json_parser_38; + } + goto basic_json_parser_32; +basic_json_parser_43: + yyaccept = 2; + yych = *(m_marker = ++m_cursor); + if (yych <= '9') + { + if (yych == '.') + { + goto basic_json_parser_47; + } + if (yych >= '0') + { + goto basic_json_parser_48; + } + } + else + { + if (yych <= 'E') + { + if (yych >= 'E') + { + goto basic_json_parser_51; + } + } + else + { + if (yych == 'e') + { + goto basic_json_parser_51; + } + } + } +basic_json_parser_44: + { + last_token_type = token_type::value_integer; + break; + } +basic_json_parser_45: + yyaccept = 2; + m_marker = ++m_cursor; + if ((m_limit - m_cursor) < 3) + { + fill_line_buffer(3); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= '9') + { + if (yych == '.') + { + goto basic_json_parser_47; + } + if (yych <= '/') + { + goto basic_json_parser_44; + } + goto basic_json_parser_45; + } + else + { + if (yych <= 'E') + { + if (yych <= 'D') + { + goto basic_json_parser_44; + } + goto basic_json_parser_51; + } + else + { + if (yych == 'e') + { + goto basic_json_parser_51; + } + goto basic_json_parser_44; + } + } +basic_json_parser_47: + yych = *++m_cursor; + if (yych <= '/') + { + goto basic_json_parser_32; + } + if (yych <= '9') + { + goto basic_json_parser_56; + } + goto basic_json_parser_32; +basic_json_parser_48: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= '/') + { + goto basic_json_parser_50; + } + if (yych <= '9') + { + goto basic_json_parser_48; + } +basic_json_parser_50: + { + last_token_type = token_type::parse_error; + break; + } +basic_json_parser_51: + yych = *++m_cursor; + if (yych <= ',') + { + if (yych == '+') + { + goto basic_json_parser_59; + } + goto basic_json_parser_32; + } + else + { + if (yych <= '-') + { + goto basic_json_parser_59; + } + if (yych <= '/') + { + goto basic_json_parser_32; + } + if (yych <= '9') + { + goto basic_json_parser_60; + } + goto basic_json_parser_32; + } +basic_json_parser_52: + yych = *++m_cursor; + if (yych == 'l') + { + goto basic_json_parser_62; + } + goto basic_json_parser_32; +basic_json_parser_53: + yych = *++m_cursor; + if (yych == 'l') + { + goto basic_json_parser_63; + } + goto basic_json_parser_32; +basic_json_parser_54: + yych = *++m_cursor; + if (yych == 'u') + { + goto basic_json_parser_64; + } + goto basic_json_parser_32; +basic_json_parser_55: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= '@') + { + if (yych <= '/') + { + goto basic_json_parser_32; + } + if (yych <= '9') + { + goto basic_json_parser_65; + } + goto basic_json_parser_32; + } + else + { + if (yych <= 'F') + { + goto basic_json_parser_65; + } + if (yych <= '`') + { + goto basic_json_parser_32; + } + if (yych <= 'f') + { + goto basic_json_parser_65; + } + goto basic_json_parser_32; + } +basic_json_parser_56: + yyaccept = 3; + m_marker = ++m_cursor; + if ((m_limit - m_cursor) < 3) + { + fill_line_buffer(3); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= 'D') + { + if (yych <= '/') + { + goto basic_json_parser_58; + } + if (yych <= '9') + { + goto basic_json_parser_56; + } + } + else + { + if (yych <= 'E') + { + goto basic_json_parser_51; + } + if (yych == 'e') + { + goto basic_json_parser_51; + } + } +basic_json_parser_58: + { + last_token_type = token_type::value_float; + break; + } +basic_json_parser_59: + yych = *++m_cursor; + if (yych <= '/') + { + goto basic_json_parser_32; + } + if (yych >= ':') + { + goto basic_json_parser_32; + } +basic_json_parser_60: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= '/') + { + goto basic_json_parser_58; + } + if (yych <= '9') + { + goto basic_json_parser_60; + } + goto basic_json_parser_58; +basic_json_parser_62: + yych = *++m_cursor; + if (yych == 's') + { + goto basic_json_parser_66; + } + goto basic_json_parser_32; +basic_json_parser_63: + yych = *++m_cursor; + if (yych == 'l') + { + goto basic_json_parser_67; + } + goto basic_json_parser_32; +basic_json_parser_64: + yych = *++m_cursor; + if (yych == 'e') + { + goto basic_json_parser_69; + } + goto basic_json_parser_32; +basic_json_parser_65: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= '@') + { + if (yych <= '/') + { + goto basic_json_parser_32; + } + if (yych <= '9') + { + goto basic_json_parser_71; + } + goto basic_json_parser_32; + } + else + { + if (yych <= 'F') + { + goto basic_json_parser_71; + } + if (yych <= '`') + { + goto basic_json_parser_32; + } + if (yych <= 'f') + { + goto basic_json_parser_71; + } + goto basic_json_parser_32; + } +basic_json_parser_66: + yych = *++m_cursor; + if (yych == 'e') + { + goto basic_json_parser_72; + } + goto basic_json_parser_32; +basic_json_parser_67: + ++m_cursor; + { + last_token_type = token_type::literal_null; + break; + } +basic_json_parser_69: + ++m_cursor; + { + last_token_type = token_type::literal_true; + break; + } +basic_json_parser_71: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= '@') + { + if (yych <= '/') + { + goto basic_json_parser_32; + } + if (yych <= '9') + { + goto basic_json_parser_74; + } + goto basic_json_parser_32; + } + else + { + if (yych <= 'F') + { + goto basic_json_parser_74; + } + if (yych <= '`') + { + goto basic_json_parser_32; + } + if (yych <= 'f') + { + goto basic_json_parser_74; + } + goto basic_json_parser_32; + } +basic_json_parser_72: + ++m_cursor; + { + last_token_type = token_type::literal_false; + break; + } +basic_json_parser_74: + ++m_cursor; + if (m_limit <= m_cursor) + { + fill_line_buffer(1); // LCOV_EXCL_LINE + } + yych = *m_cursor; + if (yych <= '@') + { + if (yych <= '/') + { + goto basic_json_parser_32; + } + if (yych <= '9') + { + goto basic_json_parser_30; + } + goto basic_json_parser_32; + } + else + { + if (yych <= 'F') + { + goto basic_json_parser_30; + } + if (yych <= '`') + { + goto basic_json_parser_32; + } + if (yych <= 'f') + { + goto basic_json_parser_30; + } + goto basic_json_parser_32; + } + } + + } + + return last_token_type; + } + + /*! + @brief append data from the stream to the line buffer + + This function is called by the scan() function when the end of the + buffer (`m_limit`) is reached and the `m_cursor` pointer cannot be + incremented without leaving the limits of the line buffer. Note re2c + decides when to call this function. + + If the lexer reads from contiguous storage, there is no trailing null + byte. Therefore, this function must make sure to add these padding + null bytes. + + If the lexer reads from an input stream, this function reads the next + line of the input. + + @pre + p p p p p p u u u u u x . . . . . . + ^ ^ ^ ^ + m_content m_start | m_limit + m_cursor + + @post + u u u u u x x x x x x x . . . . . . + ^ ^ ^ + | m_cursor m_limit + m_start + m_content + */ + void fill_line_buffer(size_t n = 0) + { + // if line buffer is used, m_content points to its data + assert(m_line_buffer.empty() + or m_content == reinterpret_cast(m_line_buffer.data())); + + // if line buffer is used, m_limit is set past the end of its data + assert(m_line_buffer.empty() + or m_limit == m_content + m_line_buffer.size()); + + // pointer relationships + assert(m_content <= m_start); + assert(m_start <= m_cursor); + assert(m_cursor <= m_limit); + assert(m_marker == nullptr or m_marker <= m_limit); + + // number of processed characters (p) + const auto num_processed_chars = static_cast(m_start - m_content); + // offset for m_marker wrt. to m_start + const auto offset_marker = (m_marker == nullptr) ? 0 : m_marker - m_start; + // number of unprocessed characters (u) + const auto offset_cursor = m_cursor - m_start; + + // no stream is used or end of file is reached + if (m_stream == nullptr or m_stream->eof()) + { + // m_start may or may not be pointing into m_line_buffer at + // this point. We trust the standard library to do the right + // thing. See http://stackoverflow.com/q/28142011/266378 + m_line_buffer.assign(m_start, m_limit); + + // append n characters to make sure that there is sufficient + // space between m_cursor and m_limit + m_line_buffer.append(1, '\x00'); + if (n > 0) + { + m_line_buffer.append(n - 1, '\x01'); + } + } + else + { + // delete processed characters from line buffer + m_line_buffer.erase(0, num_processed_chars); + // read next line from input stream + m_line_buffer_tmp.clear(); + std::getline(*m_stream, m_line_buffer_tmp, '\n'); + + // add line with newline symbol to the line buffer + m_line_buffer += m_line_buffer_tmp; + m_line_buffer.push_back('\n'); + } + + // set pointers + m_content = reinterpret_cast(m_line_buffer.data()); + assert(m_content != nullptr); + m_start = m_content; + m_marker = m_start + offset_marker; + m_cursor = m_start + offset_cursor; + m_limit = m_start + m_line_buffer.size(); + } + + /// return string representation of last read token + string_t get_token_string() const + { + assert(m_start != nullptr); + return string_t(reinterpret_cast(m_start), + static_cast(m_cursor - m_start)); + } + + /*! + @brief return string value for string tokens + + The function iterates the characters between the opening and closing + quotes of the string value. The complete string is the range + [m_start,m_cursor). Consequently, we iterate from m_start+1 to + m_cursor-1. + + We differentiate two cases: + + 1. Escaped characters. In this case, a new character is constructed + according to the nature of the escape. Some escapes create new + characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied + as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape + `"\\uxxxx"` need special care. In this case, to_unicode takes care + of the construction of the values. + 2. Unescaped characters are copied as is. + + @pre `m_cursor - m_start >= 2`, meaning the length of the last token + is at least 2 bytes which is trivially true for any string (which + consists of at least two quotes). + + " c1 c2 c3 ... " + ^ ^ + m_start m_cursor + + @complexity Linear in the length of the string.\n + + Lemma: The loop body will always terminate.\n + + Proof (by contradiction): Assume the loop body does not terminate. As + the loop body does not contain another loop, one of the called + functions must never return. The called functions are `std::strtoul` + and to_unicode. Neither function can loop forever, so the loop body + will never loop forever which contradicts the assumption that the loop + body does not terminate, q.e.d.\n + + Lemma: The loop condition for the for loop is eventually false.\n + + Proof (by contradiction): Assume the loop does not terminate. Due to + the above lemma, this can only be due to a tautological loop + condition; that is, the loop condition i < m_cursor - 1 must always be + true. Let x be the change of i for any loop iteration. Then + m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This + can be rephrased to m_cursor - m_start - 2 > x. With the + precondition, we x <= 0, meaning that the loop condition holds + indefinitely if i is always decreased. However, observe that the value + of i is strictly increasing with each iteration, as it is incremented + by 1 in the iteration expression and never decremented inside the loop + body. Hence, the loop condition will eventually be false which + contradicts the assumption that the loop condition is a tautology, + q.e.d. + + @return string value of current token without opening and closing + quotes + @throw std::out_of_range if to_unicode fails + */ + string_t get_string() const + { + assert(m_cursor - m_start >= 2); + + string_t result; + result.reserve(static_cast(m_cursor - m_start - 2)); + + // iterate the result between the quotes + for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i) + { + // find next escape character + auto e = std::find(i, m_cursor - 1, '\\'); + if (e != i) + { + // see https://github.com/nlohmann/json/issues/365#issuecomment-262874705 + for (auto k = i; k < e; k++) + { + result.push_back(static_cast(*k)); + } + i = e - 1; // -1 because of ++i + } + else + { + // processing escaped character + // read next character + ++i; + + switch (*i) + { + // the default escapes + case 't': + { + result += "\t"; + break; + } + case 'b': + { + result += "\b"; + break; + } + case 'f': + { + result += "\f"; + break; + } + case 'n': + { + result += "\n"; + break; + } + case 'r': + { + result += "\r"; + break; + } + case '\\': + { + result += "\\"; + break; + } + case '/': + { + result += "/"; + break; + } + case '"': + { + result += "\""; + break; + } + + // unicode + case 'u': + { + // get code xxxx from uxxxx + auto codepoint = std::strtoul(std::string(reinterpret_cast(i + 1), + 4).c_str(), nullptr, 16); + + // check if codepoint is a high surrogate + if (codepoint >= 0xD800 and codepoint <= 0xDBFF) + { + // make sure there is a subsequent unicode + if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u') + { + JSON_THROW(std::invalid_argument("missing low surrogate")); + } + + // get code yyyy from uxxxx\uyyyy + auto codepoint2 = std::strtoul(std::string(reinterpret_cast + (i + 7), 4).c_str(), nullptr, 16); + result += to_unicode(codepoint, codepoint2); + // skip the next 10 characters (xxxx\uyyyy) + i += 10; + } + else if (codepoint >= 0xDC00 and codepoint <= 0xDFFF) + { + // we found a lone low surrogate + JSON_THROW(std::invalid_argument("missing high surrogate")); + } + else + { + // add unicode character(s) + result += to_unicode(codepoint); + // skip the next four characters (xxxx) + i += 4; + } + break; + } + } + } + } + + return result; + } + + + /*! + @brief parse string into a built-in arithmetic type as if the current + locale is POSIX. + + @note in floating-point case strtod may parse past the token's end - + this is not an error + + @note any leading blanks are not handled + */ + struct strtonum + { + public: + strtonum(const char* start, const char* end) + : m_start(start), m_end(end) + {} + + /*! + @return true iff parsed successfully as number of type T + + @param[in,out] val shall contain parsed value, or undefined value + if could not parse + */ + template::value>::type> + bool to(T& val) const + { + return parse(val, std::is_integral()); + } + + private: + const char* const m_start = nullptr; + const char* const m_end = nullptr; + + // floating-point conversion + + // overloaded wrappers for strtod/strtof/strtold + // that will be called from parse + static void strtof(float& f, const char* str, char** endptr) + { + f = std::strtof(str, endptr); + } + + static void strtof(double& f, const char* str, char** endptr) + { + f = std::strtod(str, endptr); + } + + static void strtof(long double& f, const char* str, char** endptr) + { + f = std::strtold(str, endptr); + } + + template + bool parse(T& value, /*is_integral=*/std::false_type) const + { + // replace decimal separator with locale-specific version, + // when necessary; data will point to either the original + // string, or buf, or tempstr containing the fixed string. + std::string tempstr; + std::array buf; + const size_t len = static_cast(m_end - m_start); + + // lexer will reject empty numbers + assert(len > 0); + + // since dealing with strtod family of functions, we're + // getting the decimal point char from the C locale facilities + // instead of C++'s numpunct facet of the current std::locale + const auto loc = localeconv(); + assert(loc != nullptr); + const char decimal_point_char = (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0]; + + const char* data = m_start; + + if (decimal_point_char != '.') + { + const size_t ds_pos = static_cast(std::find(m_start, m_end, '.') - m_start); + + if (ds_pos != len) + { + // copy the data into the local buffer or tempstr, if + // buffer is too small; replace decimal separator, and + // update data to point to the modified bytes + if ((len + 1) < buf.size()) + { + std::copy(m_start, m_end, buf.begin()); + buf[len] = 0; + buf[ds_pos] = decimal_point_char; + data = buf.data(); + } + else + { + tempstr.assign(m_start, m_end); + tempstr[ds_pos] = decimal_point_char; + data = tempstr.c_str(); + } + } + } + + char* endptr = nullptr; + value = 0; + // this calls appropriate overload depending on T + strtof(value, data, &endptr); + + // parsing was successful iff strtof parsed exactly the number + // of characters determined by the lexer (len) + const bool ok = (endptr == (data + len)); + + if (ok and (value == static_cast(0.0)) and (*data == '-')) + { + // some implementations forget to negate the zero + value = -0.0; + } + + return ok; + } + + // integral conversion + + signed long long parse_integral(char** endptr, /*is_signed*/std::true_type) const + { + return std::strtoll(m_start, endptr, 10); + } + + unsigned long long parse_integral(char** endptr, /*is_signed*/std::false_type) const + { + return std::strtoull(m_start, endptr, 10); + } + + template + bool parse(T& value, /*is_integral=*/std::true_type) const + { + char* endptr = nullptr; + errno = 0; // these are thread-local + const auto x = parse_integral(&endptr, std::is_signed()); + + // called right overload? + static_assert(std::is_signed() == std::is_signed(), ""); + + value = static_cast(x); + + return (x == static_cast(value)) // x fits into destination T + and (x < 0) == (value < 0) // preserved sign + //and ((x != 0) or is_integral()) // strto[u]ll did nto fail + and (errno == 0) // strto[u]ll did not overflow + and (m_start < m_end) // token was not empty + and (endptr == m_end); // parsed entire token exactly + } + }; + + /*! + @brief return number value for number tokens + + This function translates the last token into the most appropriate + number type (either integer, unsigned integer or floating point), + which is passed back to the caller via the result parameter. + + integral numbers that don't fit into the the range of the respective + type are parsed as number_float_t + + floating-point values do not satisfy std::isfinite predicate + are converted to value_t::null + + throws if the entire string [m_start .. m_cursor) cannot be + interpreted as a number + + @param[out] result @ref basic_json object to receive the number. + @param[in] token the type of the number token + */ + bool get_number(basic_json& result, const token_type token) const + { + assert(m_start != nullptr); + assert(m_start < m_cursor); + assert((token == token_type::value_unsigned) or + (token == token_type::value_integer) or + (token == token_type::value_float)); + + strtonum num_converter(reinterpret_cast(m_start), + reinterpret_cast(m_cursor)); + + switch (token) + { + case lexer::token_type::value_unsigned: + { + number_unsigned_t val; + if (num_converter.to(val)) + { + // parsing successful + result.m_type = value_t::number_unsigned; + result.m_value = val; + return true; + } + break; + } + + case lexer::token_type::value_integer: + { + number_integer_t val; + if (num_converter.to(val)) + { + // parsing successful + result.m_type = value_t::number_integer; + result.m_value = val; + return true; + } + break; + } + + default: + { + break; + } + } + + // parse float (either explicitly or because a previous conversion + // failed) + number_float_t val; + if (num_converter.to(val)) + { + // parsing successful + result.m_type = value_t::number_float; + result.m_value = val; + + // replace infinity and NAN by null + if (not std::isfinite(result.m_value.number_float)) + { + result.m_type = value_t::null; + result.m_value = basic_json::json_value(); + } + + return true; + } + + // couldn't parse number in any format + return false; + } + + private: + /// optional input stream + std::istream* m_stream = nullptr; + /// line buffer buffer for m_stream + string_t m_line_buffer {}; + /// used for filling m_line_buffer + string_t m_line_buffer_tmp {}; + /// the buffer pointer + const lexer_char_t* m_content = nullptr; + /// pointer to the beginning of the current symbol + const lexer_char_t* m_start = nullptr; + /// pointer for backtracking information + const lexer_char_t* m_marker = nullptr; + /// pointer to the current symbol + const lexer_char_t* m_cursor = nullptr; + /// pointer to the end of the buffer + const lexer_char_t* m_limit = nullptr; + /// the last token type + token_type last_token_type = token_type::end_of_input; + }; + + /*! + @brief syntax analysis + + This class implements a recursive decent parser. + */ + class parser + { + public: + /// a parser reading from a string literal + parser(const char* buff, const parser_callback_t cb = nullptr) + : callback(cb), + m_lexer(reinterpret_cast(buff), std::strlen(buff)) + {} + + /// a parser reading from an input stream + parser(std::istream& is, const parser_callback_t cb = nullptr) + : callback(cb), m_lexer(is) + {} + + /// a parser reading from an iterator range with contiguous storage + template::iterator_category, std::random_access_iterator_tag>::value + , int>::type + = 0> + parser(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr) + : callback(cb), + m_lexer(reinterpret_cast(&(*first)), + static_cast(std::distance(first, last))) + {} + + /// public parser interface + basic_json parse() + { + // read first token + get_token(); + + basic_json result = parse_internal(true); + result.assert_invariant(); + + expect(lexer::token_type::end_of_input); + + // return parser result and replace it with null in case the + // top-level value was discarded by the callback function + return result.is_discarded() ? basic_json() : std::move(result); + } + + private: + /// the actual parser + basic_json parse_internal(bool keep) + { + auto result = basic_json(value_t::discarded); + + switch (last_token) + { + case lexer::token_type::begin_object: + { + if (keep and (not callback + or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0))) + { + // explicitly set result to object to cope with {} + result.m_type = value_t::object; + result.m_value = value_t::object; + } + + // read next token + get_token(); + + // closing } -> we are done + if (last_token == lexer::token_type::end_object) + { + get_token(); + if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) + { + result = basic_json(value_t::discarded); + } + return result; + } + + // no comma is expected here + unexpect(lexer::token_type::value_separator); + + // otherwise: parse key-value pairs + do + { + // ugly, but could be fixed with loop reorganization + if (last_token == lexer::token_type::value_separator) + { + get_token(); + } + + // store key + expect(lexer::token_type::value_string); + const auto key = m_lexer.get_string(); + + bool keep_tag = false; + if (keep) + { + if (callback) + { + basic_json k(key); + keep_tag = callback(depth, parse_event_t::key, k); + } + else + { + keep_tag = true; + } + } + + // parse separator (:) + get_token(); + expect(lexer::token_type::name_separator); + + // parse and add value + get_token(); + auto value = parse_internal(keep); + if (keep and keep_tag and not value.is_discarded()) + { + result[key] = std::move(value); + } + } + while (last_token == lexer::token_type::value_separator); + + // closing } + expect(lexer::token_type::end_object); + get_token(); + if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) + { + result = basic_json(value_t::discarded); + } + + return result; + } + + case lexer::token_type::begin_array: + { + if (keep and (not callback + or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0))) + { + // explicitly set result to object to cope with [] + result.m_type = value_t::array; + result.m_value = value_t::array; + } + + // read next token + get_token(); + + // closing ] -> we are done + if (last_token == lexer::token_type::end_array) + { + get_token(); + if (callback and not callback(--depth, parse_event_t::array_end, result)) + { + result = basic_json(value_t::discarded); + } + return result; + } + + // no comma is expected here + unexpect(lexer::token_type::value_separator); + + // otherwise: parse values + do + { + // ugly, but could be fixed with loop reorganization + if (last_token == lexer::token_type::value_separator) + { + get_token(); + } + + // parse value + auto value = parse_internal(keep); + if (keep and not value.is_discarded()) + { + result.push_back(std::move(value)); + } + } + while (last_token == lexer::token_type::value_separator); + + // closing ] + expect(lexer::token_type::end_array); + get_token(); + if (keep and callback and not callback(--depth, parse_event_t::array_end, result)) + { + result = basic_json(value_t::discarded); + } + + return result; + } + + case lexer::token_type::literal_null: + { + get_token(); + result.m_type = value_t::null; + break; + } + + case lexer::token_type::value_string: + { + const auto s = m_lexer.get_string(); + get_token(); + result = basic_json(s); + break; + } + + case lexer::token_type::literal_true: + { + get_token(); + result.m_type = value_t::boolean; + result.m_value = true; + break; + } + + case lexer::token_type::literal_false: + { + get_token(); + result.m_type = value_t::boolean; + result.m_value = false; + break; + } + + case lexer::token_type::value_unsigned: + case lexer::token_type::value_integer: + case lexer::token_type::value_float: + { + m_lexer.get_number(result, last_token); + get_token(); + break; + } + + default: + { + // the last token was unexpected + unexpect(last_token); + } + } + + if (keep and callback and not callback(depth, parse_event_t::value, result)) + { + result = basic_json(value_t::discarded); + } + return result; + } + + /// get next token from lexer + typename lexer::token_type get_token() + { + last_token = m_lexer.scan(); + return last_token; + } + + void expect(typename lexer::token_type t) const + { + if (t != last_token) + { + std::string error_msg = "parse error - unexpected "; + error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() + + "'") : + lexer::token_type_name(last_token)); + error_msg += "; expected " + lexer::token_type_name(t); + JSON_THROW(std::invalid_argument(error_msg)); + } + } + + void unexpect(typename lexer::token_type t) const + { + if (t == last_token) + { + std::string error_msg = "parse error - unexpected "; + error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() + + "'") : + lexer::token_type_name(last_token)); + JSON_THROW(std::invalid_argument(error_msg)); + } + } + + private: + /// current level of recursion + int depth = 0; + /// callback function + const parser_callback_t callback = nullptr; + /// the type of the last read token + typename lexer::token_type last_token = lexer::token_type::uninitialized; + /// the lexer + lexer m_lexer; + }; + + public: + /*! + @brief JSON Pointer + + A JSON pointer defines a string syntax for identifying a specific value + within a JSON document. It can be used with functions `at` and + `operator[]`. Furthermore, JSON pointers are the base for JSON patches. + + @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) + + @since version 2.0.0 + */ + class json_pointer + { + /// allow basic_json to access private members + friend class basic_json; + + public: + /*! + @brief create JSON pointer + + Create a JSON pointer according to the syntax described in + [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). + + @param[in] s string representing the JSON pointer; if omitted, the + empty string is assumed which references the whole JSON + value + + @throw std::domain_error if reference token is nonempty and does not + begin with a slash (`/`); example: `"JSON pointer must be empty or + begin with /"` + @throw std::domain_error if a tilde (`~`) is not followed by `0` + (representing `~`) or `1` (representing `/`); example: `"escape error: + ~ must be followed with 0 or 1"` + + @liveexample{The example shows the construction several valid JSON + pointers as well as the exceptional behavior.,json_pointer} + + @since version 2.0.0 + */ + explicit json_pointer(const std::string& s = "") + : reference_tokens(split(s)) + {} + + /*! + @brief return a string representation of the JSON pointer + + @invariant For each JSON pointer `ptr`, it holds: + @code {.cpp} + ptr == json_pointer(ptr.to_string()); + @endcode + + @return a string representation of the JSON pointer + + @liveexample{The example shows the result of `to_string`., + json_pointer__to_string} + + @since version 2.0.0 + */ + std::string to_string() const noexcept + { + return std::accumulate(reference_tokens.begin(), + reference_tokens.end(), std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + escape(b); + }); + } + + /// @copydoc to_string() + operator std::string() const + { + return to_string(); + } + + private: + /// remove and return last reference pointer + std::string pop_back() + { + if (is_root()) + { + JSON_THROW(std::domain_error("JSON pointer has no parent")); + } + + auto last = reference_tokens.back(); + reference_tokens.pop_back(); + return last; + } + + /// return whether pointer points to the root document + bool is_root() const + { + return reference_tokens.empty(); + } + + json_pointer top() const + { + if (is_root()) + { + JSON_THROW(std::domain_error("JSON pointer has no parent")); + } + + json_pointer result = *this; + result.reference_tokens = {reference_tokens[0]}; + return result; + } + + /*! + @brief create and return a reference to the pointed to value + + @complexity Linear in the number of reference tokens. + */ + reference get_and_create(reference j) const + { + pointer result = &j; + + // in case no reference tokens exist, return a reference to the + // JSON value j which will be overwritten by a primitive value + for (const auto& reference_token : reference_tokens) + { + switch (result->m_type) + { + case value_t::null: + { + if (reference_token == "0") + { + // start a new array if reference token is 0 + result = &result->operator[](0); + } + else + { + // start a new object otherwise + result = &result->operator[](reference_token); + } + break; + } + + case value_t::object: + { + // create an entry in the object + result = &result->operator[](reference_token); + break; + } + + case value_t::array: + { + // create an entry in the array + result = &result->operator[](static_cast(std::stoi(reference_token))); + break; + } + + /* + The following code is only reached if there exists a + reference token _and_ the current value is primitive. In + this case, we have an error situation, because primitive + values may only occur as single value; that is, with an + empty list of reference tokens. + */ + default: + { + JSON_THROW(std::domain_error("invalid value to unflatten")); + } + } + } + + return *result; + } + + /*! + @brief return a reference to the pointed to value + + @note This version does not throw if a value is not present, but tries + to create nested values instead. For instance, calling this function + with pointer `"/this/that"` on a null value is equivalent to calling + `operator[]("this").operator[]("that")` on that value, effectively + changing the null value to an object. + + @param[in] ptr a JSON value + + @return reference to the JSON value pointed to by the JSON pointer + + @complexity Linear in the length of the JSON pointer. + + @throw std::out_of_range if the JSON pointer can not be resolved + @throw std::domain_error if an array index begins with '0' + @throw std::invalid_argument if an array index was not a number + */ + reference get_unchecked(pointer ptr) const + { + for (const auto& reference_token : reference_tokens) + { + // convert null values to arrays or objects before continuing + if (ptr->m_type == value_t::null) + { + // check if reference token is a number + const bool nums = std::all_of(reference_token.begin(), + reference_token.end(), + [](const char x) + { + return std::isdigit(x); + }); + + // change value to array for numbers or "-" or to object + // otherwise + if (nums or reference_token == "-") + { + *ptr = value_t::array; + } + else + { + *ptr = value_t::object; + } + } + + switch (ptr->m_type) + { + case value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case value_t::array: + { + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 and reference_token[0] == '0') + { + JSON_THROW(std::domain_error("array index must not begin with '0'")); + } + + if (reference_token == "-") + { + // explicitly treat "-" as index beyond the end + ptr = &ptr->operator[](ptr->m_value.array->size()); + } + else + { + // convert array index to number; unchecked access + ptr = &ptr->operator[](static_cast(std::stoi(reference_token))); + } + break; + } + + default: + { + JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; + } + + reference get_checked(pointer ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->m_type) + { + case value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case value_t::array: + { + if (reference_token == "-") + { + // "-" always fails the range check + JSON_THROW(std::out_of_range("array index '-' (" + + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 and reference_token[0] == '0') + { + JSON_THROW(std::domain_error("array index must not begin with '0'")); + } + + // note: at performs range check + ptr = &ptr->at(static_cast(std::stoi(reference_token))); + break; + } + + default: + { + JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; + } + + /*! + @brief return a const reference to the pointed to value + + @param[in] ptr a JSON value + + @return const reference to the JSON value pointed to by the JSON + pointer + */ + const_reference get_unchecked(const_pointer ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->m_type) + { + case value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case value_t::array: + { + if (reference_token == "-") + { + // "-" cannot be used for const access + JSON_THROW(std::out_of_range("array index '-' (" + + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 and reference_token[0] == '0') + { + JSON_THROW(std::domain_error("array index must not begin with '0'")); + } + + // use unchecked array access + ptr = &ptr->operator[](static_cast(std::stoi(reference_token))); + break; + } + + default: + { + JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; + } + + const_reference get_checked(const_pointer ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->m_type) + { + case value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case value_t::array: + { + if (reference_token == "-") + { + // "-" always fails the range check + JSON_THROW(std::out_of_range("array index '-' (" + + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (reference_token.size() > 1 and reference_token[0] == '0') + { + JSON_THROW(std::domain_error("array index must not begin with '0'")); + } + + // note: at performs range check + ptr = &ptr->at(static_cast(std::stoi(reference_token))); + break; + } + + default: + { + JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'")); + } + } + } + + return *ptr; + } + + /// split the string input to reference tokens + static std::vector split(const std::string& reference_string) + { + std::vector result; + + // special case: empty reference string -> no reference tokens + if (reference_string.empty()) + { + return result; + } + + // check if nonempty reference string begins with slash + if (reference_string[0] != '/') + { + JSON_THROW(std::domain_error("JSON pointer must be empty or begin with '/'")); + } + + // extract the reference tokens: + // - slash: position of the last read slash (or end of string) + // - start: position after the previous slash + for ( + // search for the first slash after the first character + size_t slash = reference_string.find_first_of('/', 1), + // set the beginning of the first reference token + start = 1; + // we can stop if start == string::npos+1 = 0 + start != 0; + // set the beginning of the next reference token + // (will eventually be 0 if slash == std::string::npos) + start = slash + 1, + // find next slash + slash = reference_string.find_first_of('/', start)) + { + // use the text between the beginning of the reference token + // (start) and the last slash (slash). + auto reference_token = reference_string.substr(start, slash - start); + + // check reference tokens are properly escaped + for (size_t pos = reference_token.find_first_of('~'); + pos != std::string::npos; + pos = reference_token.find_first_of('~', pos + 1)) + { + assert(reference_token[pos] == '~'); + + // ~ must be followed by 0 or 1 + if (pos == reference_token.size() - 1 or + (reference_token[pos + 1] != '0' and + reference_token[pos + 1] != '1')) + { + JSON_THROW(std::domain_error("escape error: '~' must be followed with '0' or '1'")); + } + } + + // finally, store the reference token + unescape(reference_token); + result.push_back(reference_token); + } + + return result; + } + + private: + /*! + @brief replace all occurrences of a substring by another string + + @param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t + @param[in] f the substring to replace with @a t + @param[in] t the string to replace @a f + + @pre The search string @a f must not be empty. + + @since version 2.0.0 + */ + static void replace_substring(std::string& s, + const std::string& f, + const std::string& t) + { + assert(not f.empty()); + + for ( + size_t pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t + pos = s.find(f, pos + t.size()) // find next occurrence of f + ); + } + + /// escape tilde and slash + static std::string escape(std::string s) + { + // escape "~"" to "~0" and "/" to "~1" + replace_substring(s, "~", "~0"); + replace_substring(s, "/", "~1"); + return s; + } + + /// unescape tilde and slash + static void unescape(std::string& s) + { + // first transform any occurrence of the sequence '~1' to '/' + replace_substring(s, "~1", "/"); + // then transform any occurrence of the sequence '~0' to '~' + replace_substring(s, "~0", "~"); + } + + /*! + @param[in] reference_string the reference string to the current value + @param[in] value the value to consider + @param[in,out] result the result object to insert values to + + @note Empty objects or arrays are flattened to `null`. + */ + static void flatten(const std::string& reference_string, + const basic_json& value, + basic_json& result) + { + switch (value.m_type) + { + case value_t::array: + { + if (value.m_value.array->empty()) + { + // flatten empty array as null + result[reference_string] = nullptr; + } + else + { + // iterate array and use index as reference string + for (size_t i = 0; i < value.m_value.array->size(); ++i) + { + flatten(reference_string + "/" + std::to_string(i), + value.m_value.array->operator[](i), result); + } + } + break; + } + + case value_t::object: + { + if (value.m_value.object->empty()) + { + // flatten empty object as null + result[reference_string] = nullptr; + } + else + { + // iterate object and use keys as reference string + for (const auto& element : *value.m_value.object) + { + flatten(reference_string + "/" + escape(element.first), + element.second, result); + } + } + break; + } + + default: + { + // add primitive value with its reference string + result[reference_string] = value; + break; + } + } + } + + /*! + @param[in] value flattened JSON + + @return unflattened JSON + */ + static basic_json unflatten(const basic_json& value) + { + if (not value.is_object()) + { + JSON_THROW(std::domain_error("only objects can be unflattened")); + } + + basic_json result; + + // iterate the JSON object values + for (const auto& element : *value.m_value.object) + { + if (not element.second.is_primitive()) + { + JSON_THROW(std::domain_error("values in object must be primitive")); + } + + // assign value to reference pointed to by JSON pointer; Note + // that if the JSON pointer is "" (i.e., points to the whole + // value), function get_and_create returns a reference to + // result itself. An assignment will then create a primitive + // value. + json_pointer(element.first).get_and_create(result) = element.second; + } + + return result; + } + + private: + friend bool operator==(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return lhs.reference_tokens == rhs.reference_tokens; + } + + friend bool operator!=(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return !(lhs == rhs); + } + + /// the reference tokens + std::vector reference_tokens {}; + }; + + ////////////////////////// + // JSON Pointer support // + ////////////////////////// + + /// @name JSON Pointer functions + /// @{ + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. Similar to @ref operator[](const typename + object_t::key_type&), `null` values are created in arrays and objects if + necessary. + + In particular: + - If the JSON pointer points to an object key that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. + - If the JSON pointer points to an array index that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. All indices between the current maximum and the given + index are also filled with `null`. + - The special value `-` is treated as a synonym for the index past the + end. + + @param[in] ptr a JSON pointer + + @return reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw std::out_of_range if the JSON pointer can not be resolved + @throw std::domain_error if an array index begins with '0' + @throw std::invalid_argument if an array index was not a number + + @liveexample{The behavior is shown in the example.,operatorjson_pointer} + + @since version 2.0.0 + */ + reference operator[](const json_pointer& ptr) + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. The function does not change the JSON + value; no `null` values are created. In particular, the the special value + `-` yields an exception. + + @param[in] ptr JSON pointer to the desired element + + @return const reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw std::out_of_range if the JSON pointer can not be resolved + @throw std::domain_error if an array index begins with '0' + @throw std::invalid_argument if an array index was not a number + + @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} + + @since version 2.0.0 + */ + const_reference operator[](const json_pointer& ptr) const + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a reference to the element at with specified JSON pointer @a ptr, + with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw std::out_of_range if the JSON pointer can not be resolved + @throw std::domain_error if an array index begins with '0' + @throw std::invalid_argument if an array index was not a number + + @liveexample{The behavior is shown in the example.,at_json_pointer} + + @since version 2.0.0 + */ + reference at(const json_pointer& ptr) + { + return ptr.get_checked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a const reference to the element at with specified JSON pointer @a + ptr, with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw std::out_of_range if the JSON pointer can not be resolved + @throw std::domain_error if an array index begins with '0' + @throw std::invalid_argument if an array index was not a number + + @liveexample{The behavior is shown in the example.,at_json_pointer_const} + + @since version 2.0.0 + */ + const_reference at(const json_pointer& ptr) const + { + return ptr.get_checked(this); + } + + /*! + @brief return flattened JSON value + + The function creates a JSON object whose keys are JSON pointers (see [RFC + 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all + primitive. The original JSON value can be restored using the @ref + unflatten() function. + + @return an object that maps JSON pointers to primitive values + + @note Empty objects and arrays are flattened to `null` and will not be + reconstructed correctly by the @ref unflatten() function. + + @complexity Linear in the size the JSON value. + + @liveexample{The following code shows how a JSON object is flattened to an + object whose keys consist of JSON pointers.,flatten} + + @sa @ref unflatten() for the reverse function + + @since version 2.0.0 + */ + basic_json flatten() const + { + basic_json result(value_t::object); + json_pointer::flatten("", *this, result); + return result; + } + + /*! + @brief unflatten a previously flattened JSON value + + The function restores the arbitrary nesting of a JSON value that has been + flattened before using the @ref flatten() function. The JSON value must + meet certain constraints: + 1. The value must be an object. + 2. The keys must be JSON pointers (see + [RFC 6901](https://tools.ietf.org/html/rfc6901)) + 3. The mapped values must be primitive JSON types. + + @return the original JSON from a flattened version + + @note Empty objects and arrays are flattened by @ref flatten() to `null` + values and can not unflattened to their original type. Apart from + this example, for a JSON value `j`, the following is always true: + `j == j.flatten().unflatten()`. + + @complexity Linear in the size the JSON value. + + @liveexample{The following code shows how a flattened JSON object is + unflattened into the original nested JSON object.,unflatten} + + @sa @ref flatten() for the reverse function + + @since version 2.0.0 + */ + basic_json unflatten() const + { + return json_pointer::unflatten(*this); + } + + /// @} + + ////////////////////////// + // JSON Patch functions // + ////////////////////////// + + /// @name JSON Patch functions + /// @{ + + /*! + @brief applies a JSON patch + + [JSON Patch](http://jsonpatch.com) defines a JSON document structure for + expressing a sequence of operations to apply to a JSON) document. With + this function, a JSON Patch is applied to the current JSON value by + executing all operations from the patch. + + @param[in] json_patch JSON patch document + @return patched document + + @note The application of a patch is atomic: Either all operations succeed + and the patched document is returned or an exception is thrown. In + any case, the original value is not changed: the patch is applied + to a copy of the value. + + @throw std::out_of_range if a JSON pointer inside the patch could not + be resolved successfully in the current JSON value; example: `"key baz + not found"` + @throw invalid_argument if the JSON patch is malformed (e.g., mandatory + attributes are missing); example: `"operation add must have member path"` + + @complexity Linear in the size of the JSON value and the length of the + JSON patch. As usually only a fraction of the JSON value is affected by + the patch, the complexity can usually be neglected. + + @liveexample{The following code shows how a JSON patch is applied to a + value.,patch} + + @sa @ref diff -- create a JSON patch by comparing two JSON values + + @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) + @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) + + @since version 2.0.0 + */ + basic_json patch(const basic_json& json_patch) const + { + // make a working copy to apply the patch to + basic_json result = *this; + + // the valid JSON Patch operations + enum class patch_operations {add, remove, replace, move, copy, test, invalid}; + + const auto get_op = [](const std::string op) + { + if (op == "add") + { + return patch_operations::add; + } + if (op == "remove") + { + return patch_operations::remove; + } + if (op == "replace") + { + return patch_operations::replace; + } + if (op == "move") + { + return patch_operations::move; + } + if (op == "copy") + { + return patch_operations::copy; + } + if (op == "test") + { + return patch_operations::test; + } + + return patch_operations::invalid; + }; + + // wrapper for "add" operation; add value at ptr + const auto operation_add = [&result](json_pointer & ptr, basic_json val) + { + // adding to the root of the target document means replacing it + if (ptr.is_root()) + { + result = val; + } + else + { + // make sure the top element of the pointer exists + json_pointer top_pointer = ptr.top(); + if (top_pointer != ptr) + { + result.at(top_pointer); + } + + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.pop_back(); + basic_json& parent = result[ptr]; + + switch (parent.m_type) + { + case value_t::null: + case value_t::object: + { + // use operator[] to add value + parent[last_path] = val; + break; + } + + case value_t::array: + { + if (last_path == "-") + { + // special case: append to back + parent.push_back(val); + } + else + { + const auto idx = std::stoi(last_path); + if (static_cast(idx) > parent.size()) + { + // avoid undefined behavior + JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range")); + } + else + { + // default case: insert add offset + parent.insert(parent.begin() + static_cast(idx), val); + } + } + break; + } + + default: + { + // if there exists a parent it cannot be primitive + assert(false); // LCOV_EXCL_LINE + } + } + } + }; + + // wrapper for "remove" operation; remove value at ptr + const auto operation_remove = [&result](json_pointer & ptr) + { + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.pop_back(); + basic_json& parent = result.at(ptr); + + // remove child + if (parent.is_object()) + { + // perform range check + auto it = parent.find(last_path); + if (it != parent.end()) + { + parent.erase(it); + } + else + { + JSON_THROW(std::out_of_range("key '" + last_path + "' not found")); + } + } + else if (parent.is_array()) + { + // note erase performs range check + parent.erase(static_cast(std::stoi(last_path))); + } + }; + + // type check + if (not json_patch.is_array()) + { + // a JSON patch must be an array of objects + JSON_THROW(std::invalid_argument("JSON patch must be an array of objects")); + } + + // iterate and apply the operations + for (const auto& val : json_patch) + { + // wrapper to get a value for an operation + const auto get_value = [&val](const std::string & op, + const std::string & member, + bool string_type) -> basic_json& + { + // find value + auto it = val.m_value.object->find(member); + + // context-sensitive error message + const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; + + // check if desired value is present + if (it == val.m_value.object->end()) + { + JSON_THROW(std::invalid_argument(error_msg + " must have member '" + member + "'")); + } + + // check if result is of type string + if (string_type and not it->second.is_string()) + { + JSON_THROW(std::invalid_argument(error_msg + " must have string member '" + member + "'")); + } + + // no error: return value + return it->second; + }; + + // type check + if (not val.is_object()) + { + JSON_THROW(std::invalid_argument("JSON patch must be an array of objects")); + } + + // collect mandatory members + const std::string op = get_value("op", "op", true); + const std::string path = get_value(op, "path", true); + json_pointer ptr(path); + + switch (get_op(op)) + { + case patch_operations::add: + { + operation_add(ptr, get_value("add", "value", false)); + break; + } + + case patch_operations::remove: + { + operation_remove(ptr); + break; + } + + case patch_operations::replace: + { + // the "path" location must exist - use at() + result.at(ptr) = get_value("replace", "value", false); + break; + } + + case patch_operations::move: + { + const std::string from_path = get_value("move", "from", true); + json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The move operation is functionally identical to a + // "remove" operation on the "from" location, followed + // immediately by an "add" operation at the target + // location with the value that was just removed. + operation_remove(from_ptr); + operation_add(ptr, v); + break; + } + + case patch_operations::copy: + { + const std::string from_path = get_value("copy", "from", true);; + const json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + result[ptr] = result.at(from_ptr); + break; + } + + case patch_operations::test: + { + bool success = false; + JSON_TRY + { + // check if "value" matches the one at "path" + // the "path" location must exist - use at() + success = (result.at(ptr) == get_value("test", "value", false)); + } + JSON_CATCH (std::out_of_range&) + { + // ignore out of range errors: success remains false + } + + // throw an exception if test fails + if (not success) + { + JSON_THROW(std::domain_error("unsuccessful: " + val.dump())); + } + + break; + } + + case patch_operations::invalid: + { + // op must be "add", "remove", "replace", "move", "copy", or + // "test" + JSON_THROW(std::invalid_argument("operation value '" + op + "' is invalid")); + } + } + } + + return result; + } + + /*! + @brief creates a diff as a JSON patch + + Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can + be changed into the value @a target by calling @ref patch function. + + @invariant For two JSON values @a source and @a target, the following code + yields always `true`: + @code {.cpp} + source.patch(diff(source, target)) == target; + @endcode + + @note Currently, only `remove`, `add`, and `replace` operations are + generated. + + @param[in] source JSON value to compare from + @param[in] target JSON value to compare against + @param[in] path helper value to create JSON pointers + + @return a JSON patch to convert the @a source to @a target + + @complexity Linear in the lengths of @a source and @a target. + + @liveexample{The following code shows how a JSON patch is created as a + diff for two JSON values.,diff} + + @sa @ref patch -- apply a JSON patch + + @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) + + @since version 2.0.0 + */ + static basic_json diff(const basic_json& source, + const basic_json& target, + const std::string& path = "") + { + // the patch + basic_json result(value_t::array); + + // if the values are the same, return empty patch + if (source == target) + { + return result; + } + + if (source.type() != target.type()) + { + // different types: replace value + result.push_back( + { + {"op", "replace"}, + {"path", path}, + {"value", target} + }); + } + else + { + switch (source.type()) + { + case value_t::array: + { + // first pass: traverse common elements + size_t i = 0; + while (i < source.size() and i < target.size()) + { + // recursive call to compare array values at index i + auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + ++i; + } + + // i now reached the end of at least one array + // in a second pass, traverse the remaining elements + + // remove my remaining elements + const auto end_index = static_cast(result.size()); + while (i < source.size()) + { + // add operations in reverse order to avoid invalid + // indices + result.insert(result.begin() + end_index, object( + { + {"op", "remove"}, + {"path", path + "/" + std::to_string(i)} + })); + ++i; + } + + // add other remaining elements + while (i < target.size()) + { + result.push_back( + { + {"op", "add"}, + {"path", path + "/" + std::to_string(i)}, + {"value", target[i]} + }); + ++i; + } + + break; + } + + case value_t::object: + { + // first pass: traverse this object's elements + for (auto it = source.begin(); it != source.end(); ++it) + { + // escape the key name to be used in a JSON patch + const auto key = json_pointer::escape(it.key()); + + if (target.find(it.key()) != target.end()) + { + // recursive call to compare object values at key it + auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + } + else + { + // found a key that is not in o -> remove it + result.push_back(object( + { + {"op", "remove"}, + {"path", path + "/" + key} + })); + } + } + + // second pass: traverse other object's elements + for (auto it = target.begin(); it != target.end(); ++it) + { + if (source.find(it.key()) == source.end()) + { + // found a key that is not in this -> add it + const auto key = json_pointer::escape(it.key()); + result.push_back( + { + {"op", "add"}, + {"path", path + "/" + key}, + {"value", it.value()} + }); + } + } + + break; + } + + default: + { + // both primitive type: replace value + result.push_back( + { + {"op", "replace"}, + {"path", path}, + {"value", target} + }); + break; + } + } + } + + return result; + } + + /// @} +}; + +///////////// +// presets // +///////////// + +/*! +@brief default JSON class + +This type is the default specialization of the @ref basic_json class which +uses the standard template types. + +@since version 1.0.0 +*/ +using json = basic_json<>; +} // namespace nlohmann + + +/////////////////////// +// nonmember support // +/////////////////////// + +// specialization of std::swap, and std::hash +namespace std +{ +/*! +@brief exchanges the values of two JSON objects + +@since version 1.0.0 +*/ +template<> +inline void swap(nlohmann::json& j1, + nlohmann::json& j2) noexcept( + is_nothrow_move_constructible::value and + is_nothrow_move_assignable::value + ) +{ + j1.swap(j2); +} + +/// hash value for JSON objects +template<> +struct hash +{ + /*! + @brief return a hash value for a JSON object + + @since version 1.0.0 + */ + std::size_t operator()(const nlohmann::json& j) const + { + // a naive hashing via the string representation + const auto& h = hash(); + return h(j.dump()); + } +}; +} // namespace std + +/*! +@brief user-defined string literal for JSON values + +This operator implements a user-defined string literal for JSON objects. It +can be used by adding `"_json"` to a string literal and returns a JSON object +if no parse error occurred. + +@param[in] s a string representation of a JSON object +@param[in] n the length of string @a s +@return a JSON object + +@since version 1.0.0 +*/ +inline nlohmann::json operator "" _json(const char* s, std::size_t n) +{ + return nlohmann::json::parse(s, s + n); +} + +/*! +@brief user-defined string literal for JSON pointer + +This operator implements a user-defined string literal for JSON Pointers. It +can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer +object if no parse error occurred. + +@param[in] s a string representation of a JSON Pointer +@param[in] n the length of string @a s +@return a JSON pointer object + +@since version 2.0.0 +*/ +inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) +{ + return nlohmann::json::json_pointer(std::string(s, n)); +} + +// restore GCC/clang diagnostic settings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic pop +#endif + +// clean up +#undef JSON_CATCH +#undef JSON_DEPRECATED +#undef JSON_THROW +#undef JSON_TRY + +#endif diff --git a/src/localplayer.cpp b/src/localplayer.cpp index 7bbd733b..16f16449 100644 --- a/src/localplayer.cpp +++ b/src/localplayer.cpp @@ -20,6 +20,7 @@ void LocalPlayer::Update() { holding_sniper_rifle = false; wep = weapon(); if (CE_GOOD(wep)) { + weapon_mode = GetWeaponMode(); if (wep->m_iClassID == CL_CLASS(CTFSniperRifle) || wep->m_iClassID == CL_CLASS(CTFSniperRifleDecap)) holding_sniper_rifle = true; } team = CE_INT(entity, netvar.iTeamNum); diff --git a/src/localplayer.h b/src/localplayer.h index 56b50709..240a7533 100644 --- a/src/localplayer.h +++ b/src/localplayer.h @@ -24,6 +24,7 @@ public: bool bZoomed; float flZoomBegin; bool holding_sniper_rifle; + weaponmode weapon_mode; bool using_action_slot_item { false }; Vector v_ViewOffset; diff --git a/src/logging.cpp b/src/logging.cpp index f4b00f21..de101f70 100644 --- a/src/logging.cpp +++ b/src/logging.cpp @@ -7,6 +7,7 @@ #include #include + #include #include "common.h" @@ -15,9 +16,9 @@ FILE* logging::handle = 0; void logging::Initialize() { + // FIXME other method of naming the file? passwd* pwd = getpwuid(getuid()); - char* user = pwd->pw_name; - logging::handle = fopen(strfmt("/tmp/cathook-%s.log", user), "w"); + logging::handle = fopen(strfmt("/tmp/cathook-%s.log", pwd->pw_name), "w"); } void logging::Info(const char* fmt, ...) { @@ -28,14 +29,24 @@ void logging::Info(const char* fmt, ...) { vsprintf(buffer, fmt, list); va_end(list); size_t length = strlen(buffer); - char* result = new char[length + 9]; - sprintf(result, "[CAT] %s\n", buffer); + char* result = new char[length + 24]; + time_t current_time; + struct tm * time_info = nullptr; + char timeString[10]; + time(¤t_time); + time_info = localtime(¤t_time); + strftime(timeString, sizeof(timeString), "%H:%M:%S", time_info); + sprintf(result, "%% [%s] %s\n", timeString, buffer); fprintf(logging::handle, "%s", result); fflush(logging::handle); +#ifndef TEXTMODE if (g_ICvar) { if (console_logging.convar_parent && console_logging) g_ICvar->ConsolePrintf("%s", result); } +#else + printf("%s", result); +#endif delete [] buffer; delete [] result; } diff --git a/src/logging.h b/src/logging.h index 9d69c363..24126c25 100644 --- a/src/logging.h +++ b/src/logging.h @@ -12,7 +12,9 @@ typedef void(fn_Msg_t)(const char* msg, va_list); +#ifdef __cplusplus namespace logging { +#endif extern FILE* handle; @@ -20,6 +22,8 @@ void Initialize(); void Shutdown(); void Info(const char* fmt, ...); +#ifdef __cplusplus } +#endif #endif /* LOGGING_H_ */ diff --git a/src/macros.hpp b/src/macros.hpp new file mode 100644 index 00000000..6e98c48a --- /dev/null +++ b/src/macros.hpp @@ -0,0 +1,17 @@ +/* + * macros.hpp + * + * Created on: May 25, 2017 + * Author: nullifiedcat + */ + +#ifndef MACROS_HPP_ +#define MACROS_HPP_ + +#if defined(NOGUI) and NOGUI == 1 or defined(TEXTMODE) +#define ENABLE_GUI false +#else +#define ENABLE_GUI true +#endif + +#endif /* MACROS_HPP_ */ diff --git a/src/netvars.cpp b/src/netvars.cpp index 53f10659..8fdbe59f 100644 --- a/src/netvars.cpp +++ b/src/netvars.cpp @@ -21,12 +21,14 @@ void NetVars::Init() { this->iHitboxSet = gNetvars.get_offset("DT_BaseAnimating", "m_nHitboxSet"); this->vVelocity = gNetvars.get_offset("DT_BasePlayer", "localdata", "m_vecVelocity[0]"); this->movetype = gNetvars.get_offset("DT_BaseEntity", "movetype"); + this->m_iAmmo = gNetvars.get_offset("DT_BasePlayer", "localdata", "m_iAmmo"); this->m_Collision = gNetvars.get_offset("DT_BaseEntity", "m_Collision"); m_flSimulationTime = gNetvars.get_offset("DT_BaseEntity", "m_flSimulationTime"); IF_GAME (IsTF2()) { res_iTeam = gNetvars.get_offset("DT_TFPlayerResource", "baseclass", "m_iTeam"); this->res_iMaxBuffedHealth = gNetvars.get_offset("DT_TFPlayerResource", "m_iMaxBuffedHealth"); m_angEyeAngles = gNetvars.get_offset("DT_TFPlayer", "tfnonlocaldata", "m_angEyeAngles[0]"); + m_angEyeAnglesLocal = gNetvars.get_offset("DT_TFPlayer", "tflocaldata", "m_angEyeAngles[0]"); this->bGlowEnabled = gNetvars.get_offset("DT_TFPlayer", "m_bGlowEnabled"); //this->iDecapitations = gNetvars.get_offset("DT_TFPlayer", "m_Shared", "m_iDecapitations"); //this->flReloadPriorNextFire = gNetvars.get_offset("DT_TFWeaponBase", "LocalActiveTFWeaponData", "m_flReloadPriorNextFire"); @@ -46,6 +48,7 @@ void NetVars::Init() { m_iTauntIndex = gNetvars.get_offset("DT_TFPlayer", "m_Shared", "m_iTauntIndex"); m_iTauntConcept = gNetvars.get_offset("DT_TFPlayer", "m_Shared", "m_iTauntConcept"); } + this->res_iScore = gNetvars.get_offset("DT_TFPlayerResource", "baseclass", "m_iScore"); IF_GAME (IsTF()) { this->res_iMaxHealth = gNetvars.get_offset("DT_TFPlayerResource", "m_iMaxHealth"); this->res_iPlayerClass = gNetvars.get_offset("DT_TFPlayerResource", "m_iPlayerClass"); diff --git a/src/netvars.h b/src/netvars.h index 0a8eb8f2..c6684afc 100644 --- a/src/netvars.h +++ b/src/netvars.h @@ -13,7 +13,7 @@ class IClientEntity; #define NET_VAR(entity, offset, type) \ - (*(reinterpret_cast(reinterpret_cast(entity) + offset))) + (*(reinterpret_cast(reinterpret_cast(entity) + (offset)))) #define NET_INT(entity, offset) \ NET_VAR(entity, offset, int) @@ -63,6 +63,7 @@ public: offset_t iPipeType; offset_t iBuildingHealth; offset_t iBuildingMaxHealth; + offset_t m_iAmmo; offset_t iHitboxSet; offset_t vVelocity; offset_t bGlowEnabled; @@ -124,6 +125,7 @@ public: offset_t m_bReadyToBackstab; offset_t m_Collision; offset_t res_iTeam; + offset_t res_iScore; offset_t m_nChargeResistType; offset_t m_flChargeLevel; @@ -133,6 +135,7 @@ public: offset_t m_iTauntConcept; offset_t m_iTauntIndex; + offset_t m_angEyeAnglesLocal; offset_t m_nSequence; offset_t m_flSimulationTime; }; diff --git a/src/offsets.hpp b/src/offsets.hpp index 6c03bb34..de927c2d 100644 --- a/src/offsets.hpp +++ b/src/offsets.hpp @@ -59,6 +59,7 @@ struct offsets { static constexpr uint32_t LevelInit() { return PlatformOffset(23, -1, -1); } static constexpr uint32_t LevelShutdown() { return PlatformOffset(24, -1, -1); } static constexpr uint32_t BeginFrame() { return PlatformOffset(5, -1, -1); } + static constexpr uint32_t FireGameEvent() { return PlatformOffset(2, -1, -1); } static constexpr uint32_t lastoutgoingcommand() { return PlatformOffset(19228, -1, -1); } static constexpr uint32_t m_nOutSequenceNr() { return PlatformOffset(8, -1, -1); } diff --git a/src/playerlist.cpp b/src/playerlist.cpp index 1fefff9d..c7683eec 100644 --- a/src/playerlist.cpp +++ b/src/playerlist.cpp @@ -16,27 +16,27 @@ namespace playerlist { std::unordered_map data {}; -constexpr userdata null_data {}; +const userdata null_data {}; + +rgba_t k_Colors[] = { + colors::empty, + colors::FromRGBA8(99, 226, 161, 255), + colors::FromRGBA8(226, 204, 99, 255), + colors::FromRGBA8(232, 134, 6, 255), + colors::empty }; bool ShouldSave(const userdata& data) { return data.color || (data.state != k_EState::DEFAULT); } void Save() { - uid_t uid = geteuid(); - passwd* pw = getpwuid(uid); - if (!pw) { - logging::Info("Couldn't get username!"); - return; - } - std::string name(pw->pw_name); - DIR* cathook_directory = opendir(strfmt("/home/%s/.cathook", pw->pw_name)); + DIR* cathook_directory = opendir("cathook"); if (!cathook_directory) { - logging::Info(".cathook directory doesn't exist, creating one!"); - mkdir(strfmt("/home/%s/.cathook", pw->pw_name), S_IRWXU | S_IRWXG); + logging::Info("[WARNING] cathook data directory doesn't exist! How did the cheat even get injected?"); + mkdir("cathook", S_IRWXU | S_IRWXG); } else closedir(cathook_directory); try { - std::ofstream file("/home/" + name + "/.cathook/plist", std::ios::out | std::ios::binary); + std::ofstream file("cathook/plist", std::ios::out | std::ios::binary); file.write(reinterpret_cast(&SERIALIZE_VERSION), sizeof(SERIALIZE_VERSION)); int size = 0; for (const auto& item : data) { @@ -57,20 +57,13 @@ void Save() { void Load() { data.clear(); - uid_t uid = geteuid(); - passwd* pw = getpwuid(uid); - if (!pw) { - logging::Info("Couldn't get username!"); - return; - } - std::string name(pw->pw_name); - DIR* cathook_directory = opendir(strfmt("/home/%s/.cathook", pw->pw_name)); + DIR* cathook_directory = opendir("cathook"); if (!cathook_directory) { - logging::Info(".cathook directory doesn't exist, creating one!"); - mkdir(strfmt("/home/%s/.cathook", pw->pw_name), S_IRWXU | S_IRWXG); + logging::Info("[WARNING] cathook data directory doesn't exist! How did the cheat even get injected?"); + mkdir("cathook", S_IRWXU | S_IRWXG); } else closedir(cathook_directory); try { - std::ifstream file("/home/" + name + "/.cathook/plist", std::ios::in | std::ios::binary); + std::ifstream file("cathook/plist", std::ios::in | std::ios::binary); int file_serialize = 0; file.read(reinterpret_cast(&file_serialize), sizeof(file_serialize)); if (file_serialize != SERIALIZE_VERSION) { @@ -95,24 +88,19 @@ void Load() { } } -void DoNotKillMe() { - constexpr unsigned developer_alts[] = { 306902159, 347272825, 401679596, 416491033, 289921064, 175278337 }; - for (int i = 0; i < sizeof(developer_alts) / sizeof(int); i++) AccessData(developer_alts[i]).state = k_EState::DEVELOPER; -} - -int Color(unsigned steamid) { +rgba_t Color(unsigned steamid) { if (AccessData(steamid).state == k_EState::DEVELOPER) return colors::RainbowCurrent(); - if (AccessData(steamid).color) { + if (AccessData(steamid).color.a) { return AccessData(steamid).color; } else { return k_Colors[static_cast(AccessData(steamid).state)]; } } -int Color(CachedEntity* player) { +rgba_t Color(CachedEntity* player) { if (CE_GOOD(player)) return Color(player->player_info.friendsID); - return 0; + return colors::empty; } userdata& AccessData(unsigned steamid) { @@ -133,7 +121,7 @@ userdata& AccessData(CachedEntity* player) { bool IsDefault(unsigned steamid) { const userdata& data = AccessData(steamid); - return data.state == k_EState::DEFAULT && !data.color; + return data.state == k_EState::DEFAULT && !data.color.a; } bool IsDefault(CachedEntity* entity) { @@ -166,9 +154,9 @@ CatCommand pl_set_color("pl_set_color", "pl_set_color uniqueid r g b", [](const int r = strtol(args.Arg(2), nullptr, 10); int g = strtol(args.Arg(3), nullptr, 10); int b = strtol(args.Arg(4), nullptr, 10); - int color = colors::Create(r, g, b, 255); + rgba_t color = colors::FromRGBA8(r, g, b, 255); AccessData(steamid).color = color; - logging::Info("Set %d's color to 0x%08x", steamid, (unsigned int)color); + logging::Info("Changed %d's color", steamid); }); CatCommand pl_info("pl_info", "pl_info uniqueid", [](const CCommand& args) { @@ -179,10 +167,10 @@ CatCommand pl_info("pl_info", "pl_info uniqueid", [](const CCommand& args) { unsigned steamid = strtoul(args.Arg(1), nullptr, 10); logging::Info("Data for %i: ", steamid); logging::Info(" State: %i", AccessData(steamid).state); - int clr = AccessData(steamid).color; + /*int clr = AccessData(steamid).color; if (clr) { ConColorMsg(*reinterpret_cast<::Color*>(&clr), "[CUSTOM COLOR]\n"); - } + }*/ }); } diff --git a/src/playerlist.hpp b/src/playerlist.hpp index c792723f..992b76c1 100644 --- a/src/playerlist.hpp +++ b/src/playerlist.hpp @@ -12,7 +12,7 @@ namespace playerlist { -constexpr int SERIALIZE_VERSION = 2; +constexpr int SERIALIZE_VERSION = 3; enum class k_EState { DEFAULT, @@ -24,12 +24,16 @@ enum class k_EState { }; -constexpr int k_Colors[] = { 0, colors::Create(99, 226, 161, 255), colors::Create(226, 204, 99, 255), colors::Create(232, 134, 6, 255), 0 }; +extern rgba_t k_Colors[]; const std::string k_Names[] = { "DEFAULT", "FRIEND", "RAGE", "IPC", "DEVELOPER" }; +const char* const k_pszNames[] = { "DEFAULT", "FRIEND", "RAGE", "IPC", "DEVELOPER" }; struct userdata { k_EState state { k_EState::DEFAULT }; - int color { 0 }; + rgba_t color { 0, 0, 0, 0 }; + float inventory_value { 0 }; + unsigned deaths_to { 0 }; + unsigned kills { 0 }; }; extern std::unordered_map data; @@ -37,14 +41,12 @@ extern std::unordered_map data; void Save(); void Load(); -void DoNotKillMe(); - constexpr bool IsFriendly(k_EState state) { return state == k_EState::DEVELOPER || state == k_EState::FRIEND || state == k_EState::IPC; } -int Color(unsigned steamid); -int Color(CachedEntity* player); +rgba_t Color(unsigned steamid); +rgba_t Color(CachedEntity* player); userdata& AccessData(unsigned steamid); userdata& AccessData(CachedEntity* player); bool IsDefault(unsigned steamid); diff --git a/src/playerresource.cpp b/src/playerresource.cpp index 0017f68f..77430dd5 100644 --- a/src/playerresource.cpp +++ b/src/playerresource.cpp @@ -53,6 +53,15 @@ int TFPlayerResource::GetTeam(int idx) { return *(int*)((unsigned)ent + netvar.res_iTeam + 4 * idx); } +int TFPlayerResource::GetScore(int idx) { + IClientEntity *ent; + + if (idx >= 32 || idx < 1) return 0; + ent = g_IEntityList->GetClientEntity(entity); + if (!ent || ent->GetClientClass()->m_ClassID != RCC_PLAYERRESOURCE) return 0; + return *(int*)((unsigned)ent + netvar.res_iScore + 4 * idx); +} + int TFPlayerResource::GetClass(CachedEntity* player) { IClientEntity *ent; int idx; diff --git a/src/playerresource.h b/src/playerresource.h index 3d814fb8..5e7f7007 100644 --- a/src/playerresource.h +++ b/src/playerresource.h @@ -17,6 +17,7 @@ public: int GetMaxBuffedHealth(CachedEntity* player); int GetClass(CachedEntity* player); int GetTeam(int idx); + int GetScore(int idx); int entity; }; diff --git a/src/prediction.cpp b/src/prediction.cpp index 2add7539..21d03410 100644 --- a/src/prediction.cpp +++ b/src/prediction.cpp @@ -37,8 +37,8 @@ Vector SimpleLatencyPrediction(CachedEntity* ent, int hb) { } float PlayerGravityMod(CachedEntity* player) { - int movetype = CE_INT(player, netvar.movetype); - if (movetype == MOVETYPE_FLY || movetype == MOVETYPE_NOCLIP) return 0.0f; +// int movetype = CE_INT(player, netvar.movetype); +// if (movetype == MOVETYPE_FLY || movetype == MOVETYPE_NOCLIP) return 0.0f; if (HasCondition(player)) return 0.448f; return 1.0f; } @@ -50,12 +50,196 @@ bool PerformProjectilePrediction(CachedEntity* target, int hitbox) { return true; } + +std::vector> predicted_players {}; + +int predicted_player_count = 0; + +static CatVar debug_enginepred(CV_SWITCH, "debug_engine_pred_others", "0", "DO NOT USE - MOVEMENT"); + +void Prediction_CreateMove() { + static bool setup = false; + if (!setup) { + setup = true; + predicted_players.resize(32); + } + if (!debug_enginepred) return; + for (int i = 1; i < g_GlobalVars->maxClients; i++) { + CachedEntity* ent = ENTITY(i); + if (CE_GOOD(ent)) { + Vector o = ent->m_vecOrigin; + predicted_players[i].clear(); + for (int j = 0; j < 20; j++) { + Vector r = EnginePrediction(ent, 0.05f); + ent->m_vecOrigin = r; + predicted_players[i].push_back(std::move(r)); + } + ent->m_vecOrigin = o; + CE_VECTOR(ent, 0x354) = o; + //logging::Info("Predicted %d to be at [%.2f, %.2f, %.2f] vs [%.2f, %.2f, %.2f]", i, r.x,r.y,r.z, o.x, o.y, o.z); + predicted_player_count = i; + } + } +} +#ifndef TEXTMODE +void Prediction_PaintTraverse() { + if (!debug_enginepred) return; + for (int i = 1; i < predicted_player_count; i++) { + CachedEntity* ent = ENTITY(i); + if (CE_GOOD(ent)) { + Vector previous_screen; + if (!draw::WorldToScreen(ent->m_vecOrigin, previous_screen)) continue; + rgba_t color = colors::FromRGBA8(255, 0, 0, 255); + for (int j = 0; j < predicted_players[i].size(); j++) { + Vector screen; + if (draw::WorldToScreen(predicted_players[i][j], screen)) { + drawgl::Line(screen.x, screen.y, previous_screen.x - screen.x, previous_screen.y - screen.y, color); + previous_screen = screen; + } else { + break; + } + color.r -= 1.0f / 20.0f; + } + + } + } +} +#endif +Vector EnginePrediction(CachedEntity* entity, float time) { + Vector result = entity->m_vecOrigin; + IClientEntity* ent = RAW_ENT(entity); + + typedef void(*SetupMoveFn)(IPrediction*, IClientEntity *, CUserCmd *, class IMoveHelper *, CMoveData *); + typedef void(*FinishMoveFn)(IPrediction*, IClientEntity *, CUserCmd*, CMoveData*); + + void **predictionVtable = *((void ***)g_IPrediction); + SetupMoveFn oSetupMove = (SetupMoveFn)(*(unsigned*)(predictionVtable + 19)); + FinishMoveFn oFinishMove = (FinishMoveFn)(*(unsigned*)(predictionVtable + 20)); + + //CMoveData *pMoveData = (CMoveData*)(sharedobj::client->lmap->l_addr + 0x1F69C0C); + //CMoveData movedata {}; + char* object = new char[165]; + CMoveData *pMoveData = (CMoveData*)object; + + float frameTime = g_GlobalVars->frametime; + float curTime = g_GlobalVars->curtime; + + CUserCmd fakecmd {}; + + memset(&fakecmd, 0, sizeof(CUserCmd)); + + Vector vel; + if (velocity::EstimateAbsVelocity) + velocity::EstimateAbsVelocity(RAW_ENT(entity), vel); + else + vel = CE_VECTOR(entity, netvar.vVelocity); + fakecmd.command_number = last_cmd_number; + fakecmd.forwardmove = vel.x; + fakecmd.sidemove = -vel.y; + Vector oldangles = CE_VECTOR(entity, netvar.m_angEyeAngles); + static Vector zerov {0,0,0}; + CE_VECTOR(entity, netvar.m_angEyeAngles) = zerov; + + CUserCmd* original_cmd = NET_VAR(ent, 4188, CUserCmd*); + + NET_VAR(ent, 4188, CUserCmd*) = &fakecmd; + + g_GlobalVars->curtime = g_GlobalVars->interval_per_tick * NET_INT(ent, netvar.nTickBase); + g_GlobalVars->frametime = time; + + Vector old_origin = entity->m_vecOrigin; + NET_VECTOR(ent, 0x354) = entity->m_vecOrigin; + + //*g_PredictionRandomSeed = MD5_PseudoRandom(g_pUserCmd->command_number) & 0x7FFFFFFF; + g_IGameMovement->StartTrackPredictionErrors(reinterpret_cast(ent)); + oSetupMove(g_IPrediction, ent, &fakecmd, NULL, pMoveData); + g_IGameMovement->ProcessMovement(reinterpret_cast(ent), pMoveData); + oFinishMove(g_IPrediction, ent, &fakecmd, pMoveData); + g_IGameMovement->FinishTrackPredictionErrors(reinterpret_cast(ent)); + + delete[] object; + + NET_VAR(entity, 4188, CUserCmd*) = original_cmd; + + g_GlobalVars->frametime = frameTime; + g_GlobalVars->curtime = curTime; + + result = ent->GetAbsOrigin(); + NET_VECTOR(ent, 0x354) = old_origin; + CE_VECTOR(entity, netvar.m_angEyeAngles) = oldangles; + return result; +} + +Vector ProjectilePrediction_Engine(CachedEntity* ent, int hb, float speed, float gravitymod, float entgmod /* ignored */) { + Vector origin = ent->m_vecOrigin; + Vector hitbox; + GetHitbox(ent, hb, hitbox); + Vector hitbox_offset = hitbox - origin; + + if (speed == 0.0f) return Vector(); + Vector velocity; + if (velocity::EstimateAbsVelocity) + velocity::EstimateAbsVelocity(RAW_ENT(ent), velocity); + else + velocity = CE_VECTOR(ent, netvar.vVelocity); + // TODO ProjAim + float medianTime = g_pLocalPlayer->v_Eye.DistTo(hitbox) / speed; + float range = 1.5f; + float currenttime = medianTime - range; + if (currenttime <= 0.0f) currenttime = 0.01f; + float besttime = currenttime; + float mindelta = 65536.0f; + Vector bestpos = origin; + Vector current = origin; + int maxsteps = 40; + bool onground = false; + if (ent->m_Type == ENTITY_PLAYER) { + if (CE_INT(ent, netvar.iFlags) & FL_ONGROUND) onground = true; + } + float steplength = ((float)(2 * range) / (float)maxsteps); + for (int steps = 0; steps < maxsteps; steps++, currenttime += steplength) { + ent->m_vecOrigin = current; + current = EnginePrediction(ent, steplength); + + if (onground) { + float toground = DistanceToGround(current); + current.z -= toground; + } + + float rockettime = g_pLocalPlayer->v_Eye.DistTo(current) / speed; + if (fabs(rockettime - currenttime) < mindelta) { + besttime = currenttime; + bestpos = current; + mindelta = fabs(rockettime - currenttime); + } + } + ent->m_vecOrigin = origin; + CE_VECTOR(ent, 0x354) = origin; + bestpos.z += (400 * besttime * besttime * gravitymod); + // S = at^2/2 ; t = sqrt(2S/a)*/ + Vector result = bestpos + hitbox_offset; + logging::Info("[Pred][%d] delta: %.2f %.2f %.2f", result.x - origin.x, result.y - origin.y, result.z - origin.z ); + return result; +} + +CatVar debug_pp_extrapolate(CV_SWITCH, "debug_pp_extrapolate", "0", "Extrapolate entity position when predicting projectiles"); +CatVar debug_pp_rockettimeping(CV_SWITCH, "debug_pp_rocket_time_ping", "0", "Compensate for ping in pp"); + Vector ProjectilePrediction(CachedEntity* ent, int hb, float speed, float gravitymod, float entgmod) { if (!ent) return Vector(); - Vector result = SimpleLatencyPrediction(ent, hb); + Vector result; + if (not debug_pp_extrapolate) { + GetHitbox(ent, hb, result); + } else { + result = SimpleLatencyPrediction(ent, hb); + } if (speed == 0.0f) return Vector(); float dtg = DistanceToGround(ent); - Vector vel = CE_VECTOR(ent, netvar.vVelocity); + Vector vel; + if (velocity::EstimateAbsVelocity) + velocity::EstimateAbsVelocity(RAW_ENT(ent), vel); + else + vel = CE_VECTOR(ent, netvar.vVelocity); // TODO ProjAim float medianTime = g_pLocalPlayer->v_Eye.DistTo(result) / speed; float range = 1.5f; @@ -73,6 +257,7 @@ Vector ProjectilePrediction(CachedEntity* ent, int hb, float speed, float gravit if (curpos.z < result.z - dtg) curpos.z = result.z - dtg; } float rockettime = g_pLocalPlayer->v_Eye.DistTo(curpos) / speed; + if (debug_pp_rockettimeping) rockettime += g_IEngine->GetNetChannelInfo()->GetLatency(FLOW_OUTGOING); if (fabs(rockettime - currenttime) < mindelta) { besttime = currenttime; bestpos = curpos; @@ -105,3 +290,94 @@ float DistanceToGround(Vector origin) { g_ITrace->TraceRay(ray, MASK_PLAYERSOLID, &trace::filter_no_player, &ground_trace); return 8192.0f * ground_trace.fraction; } + +/* +// Set of to be fuctions for preciting players, similear to ncc prediction. + +// The way air prediction works is that we use getabsvel to get a baseline position of where the player could be +// next tick. Then we save that into the array for our math next tick. +// After the first tick passed, we check to see how the GetAbsVel function actually performed and we can correct for its +// mistakes by comparing the result from GetAbsVel last tick and where the player currently is this tick and applying an +// offset for predictions. +// With the new offset, you can use GetAbsVel and apply the offset to get 1 tick but for every other time you would need +// to apply the offset due to the way airstrafing works. +// GetAbsVel only works in a strait fassion of what the players current velocity and doesnt factor in what the players +// next velocity could be due to the player having the ability to airstrafe and change that by quite a bit. + +// Ground prediction works in the way of it using GetAbsVel to get a baseline direction of where the player is going and +// attempting to predict the players movement from that. The prediction should check its surroundings for corners, walls, +// and the like to determine a path of where the player could potentially go. We would also want to check if players +// collision box would intercept a wall or floor and interpolate even more with that in mind. +// If a player is moving too steeply onto a wall, the prediction should stop there and count that as a place for where the +// player would be for any time after it. + +// we can change between the two prediction types based on the ground flag netvar. + +// For using the predictions to work as projectile aimbot, we can determine the distance from the player kind of like how +// the current projectile aimbot currently does but we will follow the predicted path instead of just placing a vector in +// a really simple fassion. + +// This is based on the estimation that GetAbsVelocity predicts players next position for the next createmove tick + +// A set of vectors for every potential player +static Vector last_predicted_vector[32]; +// An array to store predictions +static Vector last_predictions[32]; +// Vectors to determine whether the player was in the air last tick +static bool last_predicted_inair[32]; + +// Should be run every createmove to predict playermovement +void RunPredictPlayers() { + + // Create a cached ent for use in the for loop + CachedEntity* ent; + + // Loop through players + for (int i = 0; i < 32; i++) { + + // Get an ent from current loop and check for dormancy/null + ent = ENTITY(i); + if (CE_BAD(ent)) continue; + + // Grab netvar for ground to control type of prediction + int flags = CE_INT(g_pLocalPlayer->entity, netvar.iFlags); + bool ground = (flags & (1 << 0)); + + // For ground prediction, we would just use the old method for now + if (ground) { + + // Set our last "in air" state to false + last_predicted_vector_inair[i] = false; + + + // For air prediction, attempts to exerpolate strafing speed + } else { + + // If we were not in the air last tick, we need to create our first prediction + if (!last_predicted_inair[i]) { + + // Set "in air" to true to allow air prediction to work next tick + last_predicted_inair[i] = true; + // Get our abs velocity and set it into the array + velocity::EstimateAbsVelocity(RAW_ENT(ent), last_predicted_vector[i]); + + + // Since we have been in the air last tick, we can create an offset off of prediction errors + } else { + + // Create a storage vector and get abs velocity of + Vector current_prediction; + velocity::EstimateAbsVelocity(RAW_ENT(ent), current_prediction); + last_predictions[32]; + } + } + } +} + + + +// Draws our predicted player pathing for debug or visual use +void DrawPredictPlayers() { + // TODO +} +*/ diff --git a/src/prediction.h b/src/prediction.h index e0df3052..bd4bab32 100644 --- a/src/prediction.h +++ b/src/prediction.h @@ -18,9 +18,16 @@ Vector SimpleLatencyPrediction(CachedEntity* ent, int hb); bool PerformProjectilePrediction(CachedEntity* target, int hitbox); Vector ProjectilePrediction(CachedEntity* ent, int hb, float speed, float gravitymod, float entgmod); +Vector ProjectilePrediction_Engine(CachedEntity* ent, int hb, float speed, float gravitymod, float entgmod /* ignored */); float PlayerGravityMod(CachedEntity* player); +Vector EnginePrediction(CachedEntity* player, float time); +void Prediction_CreateMove(); +#ifndef TEXTMODE +void Prediction_PaintTraverse(); +#endif + float DistanceToGround(CachedEntity* ent); float DistanceToGround(Vector origin); diff --git a/src/profiler.h b/src/profiler.h index 9835fc2a..a5c1661b 100644 --- a/src/profiler.h +++ b/src/profiler.h @@ -40,7 +40,7 @@ public: ProfilerSection& m_section; }; -#define ENABLE_PROFILER false +#define ENABLE_PROFILER true #if ENABLE_PROFILER #define PROF_SECTION(id) \ static ProfilerSection __PROFILER__##id(#id); \ diff --git a/src/projlogging.cpp b/src/projlogging.cpp new file mode 100644 index 00000000..31d42771 --- /dev/null +++ b/src/projlogging.cpp @@ -0,0 +1,33 @@ +/* + * projlogging.cpp + * + * Created on: May 26, 2017 + * Author: nullifiedcat + */ + +#include "projlogging.hpp" +#include "common.h" + +namespace projectile_logging { + +void Update() { + for (int i = 1; i < HIGHEST_ENTITY; i++) { + CachedEntity* ent = ENTITY(i); + if (CE_BAD(ent)) continue; + if (ent->m_Type == ENTITY_PROJECTILE) { + int owner = CE_INT(ent, 0x894) & 0xFFF; + if (owner != LOCAL_W->m_IDX) continue; + if (tickcount % 20 == 0) { + const Vector& v = ent->m_vecVelocity; + const Vector& a = ent->m_vecAcceleration; + Vector eav; + velocity::EstimateAbsVelocity(RAW_ENT(ent), eav); +// logging::Info("%d [%s]: CatVelocity: %.2f %.2f %.2f (%.2f) | EAV: %.2f %.2f %.2f (%.2f)", i, RAW_ENT(ent)->GetClientClass()->GetName(), v.x, v.y, v.z, v.Length(), a.x, a.y, a.z); + logging::Info("%d [%s]: CatVelocity: %.2f %.2f %.2f (%.2f) | EAV: %.2f %.2f %.2f (%.2f)", i, RAW_ENT(ent)->GetClientClass()->GetName(), v.x, v.y, v.z, v.Length(), eav.x, eav.y, eav.z, eav.Length()); + } + } + } +} + +} + diff --git a/src/projlogging.hpp b/src/projlogging.hpp new file mode 100644 index 00000000..507f3e76 --- /dev/null +++ b/src/projlogging.hpp @@ -0,0 +1,17 @@ +/* + * projlogging.hpp + * + * Created on: May 26, 2017 + * Author: nullifiedcat + */ + +#ifndef PROJLOGGING_HPP_ +#define PROJLOGGING_HPP_ + +namespace projectile_logging { + +void Update(); + +} + +#endif /* PROJLOGGING_HPP_ */ diff --git a/src/resource.cpp b/src/resource.cpp deleted file mode 100644 index 16d23fe5..00000000 --- a/src/resource.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * resource.cpp - * - * Created on: Mar 28, 2017 - * Author: nullifiedcat - */ - -#include "resource.hpp" -#include "common.h" - -Texture::Texture(unsigned char* start, unsigned w, unsigned h) - : start_addr(start), w(w), h(h) {} - -Texture::~Texture() { - if (id) { - g_ISurface->DeleteTextureByID(id); - } -} - -void Texture::Load() { - id = g_ISurface->CreateNewTextureID(true); - logging::Info("Loading %ix%i texture from 0x%08x: got id %i", w, h, start_addr, id); - //g_ISurface->DrawSetTextureRGBA(id, start_addr, w, h, 0, 0); - g_ISurface->DrawSetTextureRGBAEx(id, start_addr, w, h, ImageFormat::IMAGE_FORMAT_RGBA8888); -} - -void Texture::Draw(int x, int y, int sw, int sh, int color) { - if (!g_ISurface->IsTextureIDValid(id)) throw std::runtime_error("Invalid texture ID!"); - g_ISurface->DrawSetColor(*reinterpret_cast(&color)); - g_ISurface->DrawSetTexture(id); - g_ISurface->DrawTexturedRect(x, y, x + sw, y + sh); -} diff --git a/src/resource.hpp b/src/resource.hpp deleted file mode 100644 index e60e09a2..00000000 --- a/src/resource.hpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * resource.hpp - * - * Created on: Mar 28, 2017 - * Author: nullifiedcat - */ - -#ifndef RESOURCE_HPP_ -#define RESOURCE_HPP_ - -#include "drawing.h" - -class Texture { -public: - Texture(unsigned char* start, unsigned w, unsigned h); - ~Texture(); - void Load(); - void Draw(int x, int y, int w, int h, int color = colors::Create(255, 255, 255, 255)); -public: - int id { 0 }; - const unsigned char* const start_addr; - const unsigned w; - const unsigned h; -}; - -#endif /* RESOURCE_HPP_ */ diff --git a/src/sdk.h b/src/sdk.h index a2c1bcf2..b66be2a8 100644 --- a/src/sdk.h +++ b/src/sdk.h @@ -54,10 +54,12 @@ #include #include +#include "sdk/TFGCClientSystem.hpp" #include "sdk/in_buttons.h" #include "sdk/imaterialsystemfixed.h" #include "sdk/ScreenSpaceEffects.h" #include "sdk/iinput.h" #include "sdk/igamemovement.h" +#include "sdk/HUD.h" #endif /* SDK_H_ */ diff --git a/src/sdk/HUD.cpp b/src/sdk/HUD.cpp new file mode 100644 index 00000000..93032b33 --- /dev/null +++ b/src/sdk/HUD.cpp @@ -0,0 +1,18 @@ +/* + * HUD.cpp + * + * Created on: Jun 4, 2017 + * Author: nullifiedcat + */ + +#include "HUD.h" +#include "../logging.h" +#include "../copypasted/CSignature.h" + +#include + +CHudElement* CHud::FindElement(const char* name) { + static uintptr_t findel_sig = gSignatures.GetClientSignature("55 89 E5 57 56 53 31 DB 83 EC 1C 8B 75 08 8B 7E 28 85 FF 7F 13 EB 49 89 F6 8D BC 27 00 00 00 00 83 C3 01 39 5E 28 7E 38 8B 46 1C 8D 3C 9D 00 00 00 00 8B 04 98 8B 08 89 04 24 FF 51 24 8B 55 0C 89 04 24"); + typedef CHudElement*(*FindElement)(CHud*, const char*); + ((FindElement)(findel_sig))(this, name); +} diff --git a/src/sdk/HUD.h b/src/sdk/HUD.h new file mode 100644 index 00000000..6610689a --- /dev/null +++ b/src/sdk/HUD.h @@ -0,0 +1,35 @@ +/* + * HUD.h + * + * Created on: Jun 4, 2017 + * Author: nullifiedcat + */ + +#pragma once + +#include "../logging.h" + +#include +#include "../vfunc.h" + +class CHudBaseChat { +public: + void* vtable; + inline void Printf(const char* string) { + typedef void(*original_t)(CHudBaseChat*, int, const char*, ...); + original_t function = vfunc(this, 0x15); + function(this, 0, "%s", string); + } +}; + +class CHudElement { +public: + void* vtable; +}; + +class CHud { +public: + void* vtable; + + CHudElement* FindElement(const char* name); +}; diff --git a/src/sdk/TFGCClientSystem.cpp b/src/sdk/TFGCClientSystem.cpp new file mode 100644 index 00000000..c28221bf --- /dev/null +++ b/src/sdk/TFGCClientSystem.cpp @@ -0,0 +1,39 @@ +/* + * TFGCClientSystem.cpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#include "../copypasted/CSignature.h" +#include "TFGCClientSystem.hpp" +#include "../logging.h" + + +int TFGCClientSystem::RequestSelectWizardStep(int type) { + static uintptr_t RequestSelectWizardStep_loc = gSignatures.GetClientSignature("55 89 E5 57 56 53 83 EC 1C 8B 5D 08 8B 75 0C 89 1C 24 E8 ? ? ? ? 84 C0 75 0D 83 C4 1C 5B 5E 5F 5D C3 90 8D 74 26 00 89 1C 24 E8 ? ? ? ? 85 C0"); + typedef int(*RequestSelectWizardStep_t)(TFGCClientSystem*, int); + static RequestSelectWizardStep_t RequestSelectWizardStep_fn = (RequestSelectWizardStep_t)RequestSelectWizardStep_loc; + return RequestSelectWizardStep_fn(this, 4); +} + +int TFGCClientSystem::GetState() { + return *(int*)((uintptr_t)this + 1136); +} + +/* 55 89 E5 57 56 8D 75 C8 53 81 EC 8C 00 00 00 8B 45 0C C7 04 24 ? ? ? ? 8B 5D 08 89 45 A4 0F B6 C0 89 44 24 04 E8 ? ? ? ? C7 44 24 04 91 18 00 00 89 34 24 E8 ? ? ? ? A1 ? ? ? ? */ +int TFGCClientSystem::SendExitMatchmaking(bool abandon) { + static uintptr_t SendExitMatchmaking_loc = gSignatures.GetClientSignature("55 89 E5 57 56 8D 75 C8 53 81 EC 8C 00 00 00 8B 45 0C C7 04 24 ? ? ? ? 8B 5D 08 89 45 A4 0F B6 C0 89 44"); + typedef int(*SendExitMatchmaking_t)(TFGCClientSystem*, char); + static SendExitMatchmaking_t SendExitMatchmaking_fn = (SendExitMatchmaking_t)SendExitMatchmaking_loc; + logging::Info("Calling 0x%08x", SendExitMatchmaking_fn); + return SendExitMatchmaking_fn(this, abandon); +} + +int TFGCClientSystem::LoadSearchCriteria() { + static uintptr_t LoadSearchCriteria_loc = gSignatures.GetClientSignature("55 89 E5 57 56 53 8D 5D A8 81 EC DC 00 00 00 C7 44 24 0C 00 00 00 00 C7 44 24 08 00 00 00 00 C7 44 24 04 00 00 00 00 89 1C 24 E8 ? ? ? ? C7 44 24 08 01 00 00 00 C7 44 24 04 01 00 00 00 89 1C 24 E8 ? ? ? ? A1 ? ? ? ? 8D 50 04"); + typedef int(*LoadSearchCriteria_t)(TFGCClientSystem*); + static LoadSearchCriteria_t LoadSearchCriteria_fn = (LoadSearchCriteria_t)LoadSearchCriteria_loc; + logging::Info("Calling 0x%08x", LoadSearchCriteria_fn); + return LoadSearchCriteria_fn(this); +} diff --git a/src/sdk/TFGCClientSystem.hpp b/src/sdk/TFGCClientSystem.hpp new file mode 100644 index 00000000..6280b809 --- /dev/null +++ b/src/sdk/TFGCClientSystem.hpp @@ -0,0 +1,18 @@ +/* + * TFGCClientSystem.hpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class TFGCClientSystem { +public: + int RequestSelectWizardStep(int type); + int GetState(); + /* 55 89 E5 57 56 8D 75 C8 53 81 EC 8C 00 00 00 8B 45 0C C7 04 24 ? ? ? ? 8B 5D 08 89 45 A4 0F B6 C0 89 44 24 04 E8 ? ? ? ? C7 44 24 04 91 18 00 00 89 34 24 E8 ? ? ? ? A1 ? ? ? ? */ + int SendExitMatchmaking(bool abandon); + int LoadSearchCriteria(); +}; + diff --git a/src/sharedobj.cpp b/src/sharedobj.cpp index 2a5d11fe..3f12bb14 100644 --- a/src/sharedobj.cpp +++ b/src/sharedobj.cpp @@ -14,79 +14,40 @@ #include #include -// TODO rewrite! -const char* path_from_proc_maps(const std::string& name) { +namespace sharedobj { + +bool LocateSharedObject(std::string& name, std::string& out_full_path) { FILE* proc_maps = fopen(strfmt("/proc/%i/maps", getpid()), "r"); - if (!proc_maps) return (const char*)0; - char* buffer = new char[512]; - while (fgets(buffer, 512, proc_maps)) { - size_t length = strlen(buffer); - size_t path_begin = 0; - size_t filename_begin = 0; - for (size_t i = 0; i < length; i++) { - if (*(char*)((size_t)buffer + i) == '/' && !path_begin) path_begin = i; - if (*(char*)((size_t)buffer + i) == '/') filename_begin = i + 1; - } - if (!path_begin || !filename_begin) continue; - char* filename = buffer + filename_begin; - filename[strlen(filename) - 1] = '\0'; - if (!strcmp(name.c_str(), filename)) { - return buffer + path_begin; + if (proc_maps == nullptr) { + return false; + } + char buffer[512]; + while (fgets(buffer, 511, proc_maps)) { + char* path = strchr(buffer, '/'); + char* filename = strrchr(buffer, '/') + 1; + if (not path or not filename) continue; + if (!strncmp(name.c_str(), filename, name.length())) { + out_full_path.assign(path); + out_full_path.resize(out_full_path.size() - 1); + return true; } } - delete [] buffer; - return (const char*)0; + return false; } -const char* tf_path_from_maps() { - FILE* proc_maps = fopen(strfmt("/proc/%i/maps", getpid()), "r"); - if (!proc_maps) return (const char*)0; - char* buffer = new char[512]; - char* path = new char[256]; - while (fgets(buffer, 512, proc_maps)) { - size_t length = strlen(buffer); - size_t path_begin = 0; - size_t filename_begin = 0; - for (size_t i = 0; i < length; i++) { - if (*(char*)((size_t)buffer + i) == '/' && !path_begin) path_begin = i; - if (*(char*)((size_t)buffer + i) == '/') filename_begin = i + 1; - } - if (!path_begin || !filename_begin) continue; - char* filename = buffer + filename_begin; - filename[strlen(filename) - 1] = '\0'; - if (!strcmp("client.so", filename)) { - strcpy(path, buffer + path_begin); - path[filename_begin - path_begin - 4] = '\0'; - return path; - } - } - delete [] buffer; - return (const char*)0; +SharedObject::SharedObject(const char* _file, bool _factory) : file(_file), path("unassigned"), factory(_factory) { + constructed = true; } -namespace logging { -void Info(const char* fmt, ...); -} - -sharedobj::SharedObject* sharedobj::steamclient = 0; -sharedobj::SharedObject* sharedobj::client = 0; -sharedobj::SharedObject* sharedobj::engine = 0; -sharedobj::SharedObject* sharedobj::vguimatsurface = 0; -sharedobj::SharedObject* sharedobj::vgui2 = 0; -sharedobj::SharedObject* sharedobj::vstdlib = 0; -sharedobj::SharedObject* sharedobj::tier0 = 0; -sharedobj::SharedObject* sharedobj::inputsystem = 0; -sharedobj::SharedObject* sharedobj::studiorender = 0; -sharedobj::SharedObject* sharedobj::materialsystem = 0; - -sharedobj::SharedObject::SharedObject(const std::string& name, bool factory) { - while (!(this->path = path_from_proc_maps(name))) { +void SharedObject::Load() { + while (not LocateSharedObject(file, path)) { sleep(1); } - while (!(lmap = (link_map*)dlopen(path, RTLD_NOLOAD))) { + while (!(lmap = (link_map*)dlopen(path.c_str(), RTLD_NOLOAD))) { sleep(1); - if (0 != dlerror()) { - logging::Info("DLERROR: %s", dlerror()); + char* error = dlerror(); + if (error) { + logging::Info("DLERROR: %s", error); } } logging::Info("Shared object %s loaded at 0x%08x", basename(lmap->l_name), lmap->l_addr); @@ -98,41 +59,83 @@ sharedobj::SharedObject::SharedObject(const std::string& name, bool factory) { } } -int* sharedobj::SharedObject::Pointer(int offset) { - if (this->lmap) { - return (int*)((int) this->lmap->l_addr + offset); +char* SharedObject::Pointer(uintptr_t offset) const { + if (this->lmap != nullptr) { + return reinterpret_cast(uintptr_t(lmap->l_addr) + offset); } else { - return 0; + return nullptr; } } -void* sharedobj::SharedObject::CreateInterface(const std::string& name) { - return (void*)(fptr(name.c_str(), nullptr));; +void* SharedObject::CreateInterface(const std::string& interface) { + return (void*)(fptr(interface.c_str(), nullptr)); } -void sharedobj::LoadAllSharedObjects() { - sharedobj::client = new SharedObject("client.so", true); - /*uintptr_t itemschemapatch = (gSignatures.GetClientSignature("8B 85 78 FF FF FF 89 44 24 0C 8B 85 68 FF FF FF 89 44 24 08 8B 85 38 FF FF FF 89 44 24 04 8B 85 28 FF FF FF 89 04 24 E8 F4 D0 FF FF 84 C0 0F 84 FC 00 00 00") + 44); - logging::Info("Patching @ 0x%08x", itemschemapatch); - if (itemschemapatch) { - unsigned char patch1[] = { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 }; - Patch((void*)itemschemapatch, (void*)patch1, 8); +void LoadAllSharedObjects() { + try { + steamclient().Load(); + client().Load(); + engine().Load(); + vstdlib().Load(); + tier0().Load(); + inputsystem().Load(); + materialsystem().Load(); +#ifndef TEXTMODE + vguimatsurface().Load(); + vgui2().Load(); + studiorender().Load(); + libsdl().Load(); +#endif + } catch (std::exception& ex) { + logging::Info("Exception: %s", ex.what()); } - - uintptr_t itemschemapatch2 = (gSignatures.GetClientSignature("8B 45 10 89 44 24 08 8B 45 0C 89 44 24 04 8B 45 08 89 04 24 E8 CA 35 A8 00 A2 B4 A9 F8 01 C9 C3") + 22); - logging::Info("Patching @ 0x%08x", itemschemapatch2); - if (itemschemapatch2) { - unsigned char patch1[] = { 0xb0, 0x01, 0x90, 0x90, 0x90 }; - Patch((void*)itemschemapatch2, (void*)patch1, 5); - }*/ - sharedobj::engine = new SharedObject("engine.so", true); - sharedobj::steamclient = new SharedObject("steamclient.so", true); - sharedobj::tier0 = new SharedObject("libtier0.so", false); - sharedobj::vgui2 = new SharedObject("vgui2.so", true); - sharedobj::vguimatsurface = new SharedObject("vguimatsurface.so", true); - sharedobj::vstdlib = new SharedObject("libvstdlib.so", true); - sharedobj::inputsystem = new SharedObject("inputsystem.so", true); - sharedobj::studiorender = new SharedObject("studiorender.so", true); - sharedobj::materialsystem = new SharedObject("materialsystem.so", true); } +SharedObject& steamclient() { + static SharedObject obj("steamclient.so", true); + return obj; +} +SharedObject& client() { + static SharedObject obj("client.so", true); + return obj; +} +SharedObject& engine() { + static SharedObject obj("engine.so", true); + return obj; +} +SharedObject& vstdlib() { + static SharedObject obj("libvstdlib.so", true); + return obj; +} +SharedObject& tier0() { + static SharedObject obj("libtier0.so", false); + return obj; +} +SharedObject& inputsystem() { + static SharedObject obj("inputsystem.so", true); + return obj; +} +SharedObject& materialsystem() { + static SharedObject obj("materialsystem.so", true); + return obj; +} +#ifndef TEXTMODE +SharedObject& vguimatsurface() { + static SharedObject obj("vguimatsurface.so", true); + return obj; +} +SharedObject& vgui2() { + static SharedObject obj("vgui2.so", true); + return obj; +} +SharedObject& studiorender() { + static SharedObject obj("studiorender.so", true); + return obj; +} +SharedObject& libsdl() { + static SharedObject obj("libSDL2-2.0.so.0", false); + return obj; +} +#endif + +} diff --git a/src/sharedobj.h b/src/sharedobj.h index 1681f96d..57356101 100644 --- a/src/sharedobj.h +++ b/src/sharedobj.h @@ -10,36 +10,45 @@ #include "beforecheaders.h" #include +#include #include "aftercheaders.h" struct link_map; typedef void *(*fn_CreateInterface_t)(const char*, int*); -const char* path_from_proc_maps(const std::string& path); -const char* tf_path_from_maps(); - namespace sharedobj { +bool LocateSharedObject(std::string& name, std::string& out_full_path); + class SharedObject { public: - SharedObject(const std::string& name, bool factory); - int* Pointer(int offset); - void* CreateInterface(const std::string& name); - fn_CreateInterface_t fptr; - const char* path; - link_map* lmap; + SharedObject(const char* _file, bool _factory); + void Load(); + char* Pointer(uintptr_t offset) const; + void* CreateInterface(const std::string& interface); +public: + std::string file; + std::string path; + bool factory { false }; + bool constructed { false }; + + fn_CreateInterface_t fptr { nullptr }; + link_map* lmap { nullptr }; }; -extern SharedObject* steamclient; -extern SharedObject* client; -extern SharedObject* engine; -extern SharedObject* vguimatsurface; -extern SharedObject* vgui2; -extern SharedObject* vstdlib; -extern SharedObject* tier0; -extern SharedObject* inputsystem; -extern SharedObject* studiorender; -extern SharedObject* materialsystem; +SharedObject& steamclient(); +SharedObject& client(); +SharedObject& engine(); +SharedObject& vstdlib(); +SharedObject& tier0(); +SharedObject& inputsystem(); +SharedObject& materialsystem(); +#ifndef TEXTMODE +SharedObject& vguimatsurface(); +SharedObject& vgui2(); +SharedObject& studiorender(); +SharedObject& libsdl(); +#endif void LoadAllSharedObjects(); diff --git a/src/textfile.cpp b/src/textfile.cpp index 24cb75c5..28c1b7d2 100644 --- a/src/textfile.cpp +++ b/src/textfile.cpp @@ -13,27 +13,36 @@ #include #include "aftercheaders.h" -#include #include -TextFile::TextFile() : lines {} {}; +TextFile::TextFile() + : lines {} {} + +bool TextFile::TryLoad(std::string name) { + if (name.length() == 0) return false; + std::string filename = format("cathook/", name); + std::ifstream file(filename, std::ios::in); + if (!file) { + return false; + } + lines.clear(); + for (std::string line; std::getline(file, line);) { + if (*line.rbegin() == '\r') line.erase(line.length() - 1, 1); + lines.push_back(line); + } + return true; +} void TextFile::Load(std::string name) { - uid_t uid = geteuid(); - passwd* pw = getpwuid(uid); - if (!pw) { - logging::Info("can't get the username!"); - return; - } - std::string test_format = format(123); - std::string filename = format("/home/", pw->pw_name, "/.cathook/", name); + std::string filename = format("cathook/", name); std::ifstream file(filename, std::ios::in); if (file.bad()) { - logging::Info("Could not open the file: %s", filename); + logging::Info("Could not open the file: %s", filename.c_str()); return; } lines.clear(); for (std::string line; std::getline(file, line);) { + if (*line.rbegin() == '\r') line.erase(line.length() - 1, 1); lines.push_back(line); } } diff --git a/src/textfile.h b/src/textfile.h index 2587cd2b..e9df7356 100644 --- a/src/textfile.h +++ b/src/textfile.h @@ -17,9 +17,10 @@ class TextFile { public: TextFile(); void Load(std::string filename); + bool TryLoad(std::string filename); size_t LineCount() const; const std::string& Line(size_t id) const; - +public: std::vector lines; }; diff --git a/src/textmode.cpp b/src/textmode.cpp new file mode 100644 index 00000000..8c689c53 --- /dev/null +++ b/src/textmode.cpp @@ -0,0 +1,55 @@ +/* + * textmode.cpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#include "common.h" +#include "init.hpp" +#include "copypasted/CSignature.h" +#include "cvwrapper.h" + +#include +#include + +bool *allowSecureServers { nullptr }; + +void EXPOSED_Epic_VACBypass_1337_DoNotSteal_xXx_$1_xXx_MLG() { + static unsigned char patch[] = { 0x55, 0x89, 0xE5, 0x83, 0xEC, 0x18, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC9, 0xC3 }; + uintptr_t Host_IsSecureServerAllowed_addr = gSignatures.GetEngineSignature("55 89 E5 83 EC 18 E8 ? ? ? ? 8B 10 C7 44 24 04 ? ? ? ? 89 04 24 FF 52 2C 85 C0 74 11 C6 05 90 43 88 00 00"); + // +0x21 = allowSecureServers + logging::Info("1337 VAC bypass: 0x%08x", Host_IsSecureServerAllowed_addr); + Patch((void*)Host_IsSecureServerAllowed_addr, (void*)patch, sizeof(patch)); + uintptr_t allowSecureServers_addr = Host_IsSecureServerAllowed_addr + 0x21; + allowSecureServers = *(bool**)(allowSecureServers_addr); + logging::Info("Allow Secure Servers: 0x%08x", allowSecureServers); + *allowSecureServers = true; + logging::Info("Done..?"); +} + +CatCommand fixvac("fixvac", "Lemme in to secure servers", []() { + *allowSecureServers = true; +}); + +#ifdef TEXTMODE +InitRoutine init([]() { +#ifdef TEXTMODE_STDIN + logging::Info("[TEXTMODE] Setting up input handling"); + int flags = fcntl(0, F_GETFL, 0); + flags |= O_NONBLOCK; + fcntl(0, F_SETFL, flags); + logging::Info("[TEXTMODE] stdin is now non-blocking"); +#endif + EXPOSED_Epic_VACBypass_1337_DoNotSteal_xXx_$1_xXx_MLG(); +}); +#endif + +void UpdateInput() { + char buffer[256]; + int bytes = read(0, buffer, 255); + if (bytes > 0) { + buffer[bytes] = '\0'; + g_IEngine->ExecuteClientCmd(buffer); + } +} diff --git a/src/textmode.hpp b/src/textmode.hpp new file mode 100644 index 00000000..353819b0 --- /dev/null +++ b/src/textmode.hpp @@ -0,0 +1,10 @@ +/* + * textmode.hpp + * + * Created on: Jul 28, 2017 + * Author: nullifiedcat + */ + +#pragma once + +void UpdateInput(); diff --git a/src/timer.hpp b/src/timer.hpp new file mode 100644 index 00000000..e995da60 --- /dev/null +++ b/src/timer.hpp @@ -0,0 +1,36 @@ +/* + * timer.hpp + * + * Created on: Jul 29, 2017 + * Author: nullifiedcat + */ + +#pragma once + +#include + +class Timer { +public: + typedef std::chrono::system_clock clock; + + inline Timer() {}; + + inline bool check(unsigned ms) const { + return std::chrono::duration_cast(clock::now() - last).count() >= ms; + } + inline bool test_and_set(unsigned ms) { + if (check(ms)) { + update(); + return true; + } + return false; + } + inline void update() { + last = clock::now(); + } + +public: + std::chrono::time_point last {}; +}; + + diff --git a/src/trace.cpp b/src/trace.cpp index 1f041cdf..de2b287f 100644 --- a/src/trace.cpp +++ b/src/trace.cpp @@ -20,7 +20,7 @@ trace::FilterDefault::FilterDefault() { m_pSelf = nullptr; } -trace::FilterDefault::~FilterDefault() {}; +trace::FilterDefault::~FilterDefault() {} void trace::FilterDefault::SetSelf(IClientEntity* self) { if (self == nullptr) { diff --git a/src/ucccccp_cmds.cpp b/src/ucccccp_cmds.cpp new file mode 100644 index 00000000..b791fbbe --- /dev/null +++ b/src/ucccccp_cmds.cpp @@ -0,0 +1,22 @@ +/* + * utfccp_commands.cpp + * + * Created on: Jul 1, 2017 + * Author: nullifiedcat + */ + +#include "ucccccp.hpp" +#include "common.h" +#include "ucccccp_cmds.hpp" + +CatCommand utfccp_encrypt("ucccccp_encrypt", "Encrypt a message", [](const CCommand& args) { + logging::Info("%s", ucccccp::encrypt(std::string(args.ArgS())).c_str()); +}); + +CatCommand utfccp_decrypt("ucccccp_decrypt", "Decrypt a message", [](const CCommand& args) { + if (ucccccp::validate(std::string(args.ArgS()))) { + logging::Info("%s", ucccccp::decrypt(std::string(args.ArgS())).c_str()); + } else { + logging::Info("Invalid input data!"); + } +}); diff --git a/src/ucccccp_cmds.hpp b/src/ucccccp_cmds.hpp new file mode 100644 index 00000000..eacc6491 --- /dev/null +++ b/src/ucccccp_cmds.hpp @@ -0,0 +1,13 @@ +/* + * utfccp_commands.hpp + * + * Created on: Jul 1, 2017 + * Author: nullifiedcat + */ + +#pragma once + +class CatCommand; + +extern CatCommand ucccccp_encrypt; +extern CatCommand ucccccp_decrypt; diff --git a/src/velocity.cpp b/src/velocity.cpp new file mode 100644 index 00000000..3ecb8c9a --- /dev/null +++ b/src/velocity.cpp @@ -0,0 +1,20 @@ +/* + * velocity.cpp + * + * Created on: May 27, 2017 + * Author: nullifiedcat + */ + +#include "velocity.hpp" +#include "common.h" +#include "copypasted/CSignature.h" + +namespace velocity { + +EstimateAbsVelocity_t EstimateAbsVelocity {}; + +void Init() { + EstimateAbsVelocity = (void(*)(IClientEntity*, Vector&))gSignatures.GetClientSignature("55 89 E5 56 53 83 EC 20 8B 5D 08 8B 75 0C E8 ? ? ? ? 39 D8 74 79 0F B6 05 ? ? ? ? 81 C3 B8 02 00 00 C6 05 ? ? ? ? 01 F3 0F 10 05 ? ? ? ? F3 0F 11 45 F0 88 45 EC A1 ? ? ? ? 89 45 E8 8D 45 E8 A3 ? ? ? ? A1 ? ? ? ? F3 0F 10 40 0C 89 74 24 04 89 1C 24 F3 0F 11 44 24 08 E8 ? ? ? ? 0F B6 45 EC F3 0F 10 45 F0 F3 0F 11 05 ? ? ? ? A2 ? ? ? ? 8B 45 E8 A3 ? ? ? ? 83 C4 20 5B 5E 5D C3"); +} + +} diff --git a/src/velocity.hpp b/src/velocity.hpp new file mode 100644 index 00000000..e3524a78 --- /dev/null +++ b/src/velocity.hpp @@ -0,0 +1,23 @@ +/* + * velocity.hpp + * + * Created on: May 27, 2017 + * Author: nullifiedcat + */ + +#ifndef VELOCITY_HPP_ +#define VELOCITY_HPP_ + +#include "common.h" + +namespace velocity { + +typedef std::function EstimateAbsVelocity_t; +extern EstimateAbsVelocity_t EstimateAbsVelocity; + +void Init(); + + +} + +#endif /* VELOCITY_HPP_ */ diff --git a/src/vfunc.h b/src/vfunc.h index 5f9878d3..0c1137f5 100644 --- a/src/vfunc.h +++ b/src/vfunc.h @@ -10,7 +10,7 @@ template inline F vfunc(void* thisptr, uintptr_t idx, uintptr_t offset = 0) { - void** vmt = *reinterpret_cast((uintptr_t)thisptr + offset); + void** vmt = *reinterpret_cast(uintptr_t(thisptr) + offset); return reinterpret_cast((vmt)[idx]); } diff --git a/src/xorstring.hpp b/src/xorstring.hpp new file mode 100644 index 00000000..0fa6c8a3 --- /dev/null +++ b/src/xorstring.hpp @@ -0,0 +1,11 @@ +/* + * xorstring.hpp + * + * Created on: Jun 5, 2017 + * Author: nullifiedcat + */ + +#pragma once + +// TODO stub +#define XS(s) s diff --git a/tf-settings/fonts/opensans-bold.ttf b/tf-settings/fonts/opensans-bold.ttf new file mode 100644 index 00000000..fd79d43b Binary files /dev/null and b/tf-settings/fonts/opensans-bold.ttf differ diff --git a/tf-settings/menu.json b/tf-settings/menu.json new file mode 100644 index 00000000..3544ef01 --- /dev/null +++ b/tf-settings/menu.json @@ -0,0 +1,514 @@ +[ + { + "type": "list", + "name": "Aim Bot", + "list": [ + "aimbot_enabled", + "aimbot_aimkey", + "aimbot_aimkey_mode", + "aimbot_autoshoot", + "aimbot_hitboxmode", + "aimbot_fov", + "aimbot_fov_draw", + "aimbot_prioritymode", + "aimbot_charge", + { + "type": "list", + "name": "Ignore", + "list": [ + "aimbot_ignore_cloak", + "aimbot_ignore_deadringer", + "aimbot_ignore_vaccinator", + "ignore_taunting", + "aimbot_ignore_hoovy", + "aimbot_teammates", + "aimbot_buildings_sentry", + "aimbot_buildings_other", + "aimbot_stickys" + ] + }, + { + "type": "list", + "name": "Auto Heal", + "list": [ + "autoheal_enabled", + "autoheal_uber", + "autoheal_uber_health", + "autoheal_silent", + "autoheal_share_uber" + ] + }, + { + "type": "list", + "name": "Preferences", + "list": [ + "aimbot_silent", + "aimbot_target_lock", + "aimbot_hitbox", + "aimbot_zoomed", + "aimbot_only_when_can_shoot", + "aimbot_enable_attack_only", + "aimbot_maxrange", + "aimbot_slow", + "aimbot_slow_smooth", + "aimbot_slow_autoshoot", + { + "type": "list", + "name": "Projectile Aimbot Tweaks", + "list": [ + "aimbot_projectile", + "aimbot_proj_fovpred", + "aimbot_proj_vispred", + "aimbot_proj_gravity", + "aimbot_proj_speed", + "aimbot_huntsman_charge", + "aimbot_full_auto_huntsman" + ] + } + ] + } + ] + }, + { + "type": "list", + "name": "Trigger Bot", + "list": [ + "trigger_enabled", + "autobackstab", + { + "type": "list", + "name": "Auto Vaccinator", + "list": [ + "auto_vacc", + "auto_vacc_reset_timer", + "auto_vacc_default_resist", + "auto_vacc_bullets", + "auto_vacc_blast", + "auto_vacc_fire", + "auto_vacc_sniper_pop", + "auto_vacc_blast_pop_health", + "auto_vacc_blast_pop_crit", + "auto_vacc_rocket_range", + "auto_vacc_fire_pop_pyro", + "auto_vacc_afterburn", + "auto_vacc_pyro_range", + "auto_vacc_bullet_pop_ubers", + "auto_vacc_blast_pop_ubers", + "auto_vacc_fire_pop_ubers" + ] + }, + { + "type": "list", + "name": "Auto Sticky", + "list": [ + "sticky_enabled", + "sticky_buildings", + "sticky_legit" + ] + }, + { + "type": "list", + "name": "Auto Reflect", + "list": [ + "reflect_enabled", + "reflect_key", + "reflect_legit", + "reflect_only_idle", + "reflect_stickybombs", + "reflect_dodgeball" + ] + }, + { + "type": "list", + "name": "Triggerbot Ignores", + "list": [ + "trigger_ignore_cloak", + "trigger_ignore_hoovy", + "trigger_ignore_vaccinator", + "trigger_buildings_sentry", + "trigger_buildings_other", + "trigger_stickys", + "trigger_teammates" + ] + }, + { + "type": "list", + "name": "Triggerbot Preferences", + "list": [ + "trigger_delay", + "trigger_accuracy", + "trigger_zoomed", + "trigger_maxrange", + "trigger_charge", + "trigger_hitboxmode", + "trigger_key_mode", + "trigger_key" + ] + } + ] + }, + { + "type": "list", + "name": "Visuals", + "list": [ + { + "type": "list", + "name": "ESP", + "list": [ + "esp_enabled", + "esp_bones", + "esp_conds", + "esp_class", + "esp_name", + "esp_distance", + "esp_ubercharge", + "esp_box", + "esp_box_text_position", + "esp_box_nodraw", + "esp_box_expand", + "esp_box_healthbar", + "esp_box_corners", + "esp_box_corner_size", + "esp_legit", + "esp_health_num", + "esp_weapon_spawners", + "esp_model_name", + "esp_weapon", + "esp_vischeck", + "esp_show_tank", + "esp_entity_id", + "esp_followbot_id", + "esp_teammates", + "esp_entity", + "esp_buildings", + "esp_local", + "esp_powerups", + "esp_tracers", + { + "type": "list", + "name": "Emoji ESP", + "list": [ + "esp_emoji", + "esp_emoji_size", + "esp_emoji_scaling", + "esp_emoji_min_size" + ] + }, + { + "type": "list", + "name": "Item ESP", + "list": [ + "esp_item", + "esp_item_adrenaline", + "esp_item_powerups", + "esp_item_health", + "esp_item_ammo", + "esp_item_weapons", + "esp_money_red", + "esp_money" + ] + }, + { + "type": "list", + "name": "Projectile ESP", + "list": [ + "esp_proj", + "esp_proj_enemy", + "esp_proj_stickies", + "esp_proj_pipes", + "esp_proj_arrows", + "esp_proj_rockets" + ] + } + ] + }, + { + "type": "list", + "name": "Radar", + "list": [ + "radar", + "radar_size", + "radar_zoom", + "radar_health", + "radar_enemies_top", + "radar_icon_size", + "radar_x", + "radar_y", + "radar_healthpacks", + "radar_ammopacks", + "radar_teammates", + "radar_icons" + ] + }, + { + "type": "list", + "name": "Chams", + "list": [ + "chams_enable", + "chams_legit", + "chams_singlepass", + "chams_health", + "chams_players", + "chams_teammates", + "chams_buildings", + "chams_teammate_buildings", + "chams_flat", + "chams_recursive", + "chams_weapons_white", + "chams_medkits", + "chams_ammo", + "chams_stickies" + ] + }, + { + "type": "list", + "name": "Glow", + "list": [ + "glow_enable", + "glow_solid_when", + "glow_blur_scale", + "glow_health", + "glow_players", + "glow_teammates", + "glow_buildings", + "glow_teammate_buildings", + "glow_medkits", + "glow_ammo", + "glow_stickies", + "glow_powerups" + ] + }, + { + "type": "list", + "name": "GUI Settings", + "list": [ + "gui_color_b", + "gui_color_g", + "gui_color_r", + "gui_rainbow" + ] + }, + { + "type": "list", + "name": "Miscellaneous Settings", + "list": [ + "pure_bypass", + "antidisguise", + "no_arms", + "no_hats", + "thirdperson", + "thirdperson_angles", + "render_zoomed", + "fov", + "fov_zoomed", + "no_zoom", + "clean_screenshots", + "info", + "font_ftgl_esp" + ] + } + ] + }, + { + "type": "list", + "name": "Anti-/Anti-Aim", + "list": [ + "aa_enabled", + "aa_pitch", + "aa_pitch_mode", + "aa_yaw", + "aa_yaw_mode", + "aa_spin", + "aa_roll", + "aa_no_clamp", + "resolver", + { + "type": "list", + "name": "Anti-Anti-Anti-Aim", + "list": [ + "aa_aaaa_enabled", + "aa_aaaa_interval", + "aa_aaaa_interval_low", + "aa_aaaa_interval_high", + "aa_aaaa_mode", + "aa_aaaa_flip_key" + ] + } + ] + }, + { + "type": "list", + "name": "Crit Hack", + "list": [ + "crit_info", + "crit_hack_next", + "crit_hack", + "crit_suppress", + "crit_melee", + "crit_hack_experimental" + ] + }, + { + "type": "list", + "name": "Chat Settings", + "list": [ + "spam", + "killsay", + "uberspam", + "spam_file", + "killsay_file", + "spam_random", + "chat_newlines", + "clean_chat", + "chat_crypto", + "uberspam_ready", + "uberspam_used", + "uberspam_ended", + "uberspam_team", + "uberspam_build", + "uberspam_file", + "spam_voicecommand", + "spam_teamname" + ] + }, + { + "type": "list", + "name": "Anti-Cheat", + "list": [ + "ac_enabled", + "ac_ignore_local", + "ac_chat", + "ac_aimbot", + "ac_aimbot_detections", + "ac_aimbot_angle", + "ac_removecond", + "ac_removecond_timer", + "ac_bhop_count" + ] + }, + { + "type": "list", + "name": "Followbot", + "list": [ + "fb_bot", + "fb_distance", + "fb_activation", + "fb_roaming", + "fb_mimic_slot", + "fb_always_medigun", + "fb_sync_taunt", + "fb_crumb_draw" + ] + }, + { + "type": "list", + "name": "Miscellaneous", + "list": [ + "events", + "chat_crypto", + "airstuck", + "instant_weapon_switch", + "name", + "fakelag", + "disconnect_reason", + "name_stealer", + "minigun_jump", + "spycrab", + "skinchanger", + "bhop_enabled", + "noisemaker", + "nopush_enabled", + "fast_vischeck", + "anti_afk", + "rollspeedhack", + "info", + "tauntslide_tf2", + "tauntslide", + "flashlight", + { + "type": "list", + "name": "Remove Conditions", + "list": [ + "removecond_master", + "removecond_value", + "removecond_key", + "removecond_fire", + "removecond_taunt", + "removecond_bleeding", + "removecond_stun", + "instant_decloak", + "instant_rezoom", + "infinite_packs", + "lagexploit_mini" + ] + }, + { + "type": "list", + "name": "Fidget Spinner", + "list": [ + "fidgetspinner", + "fidgetspinner_scale", + "fidgetspinner_decay_speed", + "fidgetspinner_speed_scale", + "fidgetspinner_speed_cap", + "fidgetspinner_min_speed" + ] + }, + { + "type": "list", + "name": "Heal Arrows", + "list": [ + "healarrow", + "healarrow_charge", + "healarrow_timeout", + "healarrow_callout", + "healarrow_callout_text" + ] + }, + { + "type": "list", + "name": "Spy Alert", + "list": [ + "spyalert_enabled", + "spyalert_warning", + "spyalert_backstab", + "spyalert_sound", + "spyalert_interval" + ] + }, + { + "type": "list", + "name": "Anti Backstab", + "list": [ + "antibackstab", + "antibackstab_nope", + "antibackstab_angle", + "antibackstab_distance", + "antibackstab_silent" + ] + }, + { + "type": "list", + "name": "Debug Settings", + "list": [ + "enabled", + "debug_projectiles", + "debug_aimbot_engine_pp", + "debug_ve_window", + "debug_ve_smooth", + "debug_ve_averaging", + "no_visuals", + "aimbot_debug", + "debug_info", + "log", + "setupbones_time", + "nolerp", + "skinchanger_debug", + "software_cursor_mode", + "experimental_cursor_fix", + "engine_prediction" + ] + } + ] + } +] diff --git a/tf-settings/shaders/v2f-c4f.frag b/tf-settings/shaders/v2f-c4f.frag new file mode 100644 index 00000000..89946792 --- /dev/null +++ b/tf-settings/shaders/v2f-c4f.frag @@ -0,0 +1,4 @@ +// 2D drawing shader +void main() { + gl_FragColor = gl_Color; +} diff --git a/tf-settings/shaders/v2f-c4f.vert b/tf-settings/shaders/v2f-c4f.vert new file mode 100644 index 00000000..dda5f179 --- /dev/null +++ b/tf-settings/shaders/v2f-c4f.vert @@ -0,0 +1,13 @@ +// 2D drawing shader +uniform mat4 model; +uniform mat4 view; +uniform mat4 projection; + +attribute vec2 vertex; +attribute vec4 color; + +void main() +{ + gl_FrontColor = color; + gl_Position = projection*(view*(model*vec4(vertex,0.0,1.0))); +} diff --git a/tf-settings/shaders/v2f-t2f-c4f.frag b/tf-settings/shaders/v2f-t2f-c4f.frag new file mode 100644 index 00000000..3cdf9801 --- /dev/null +++ b/tf-settings/shaders/v2f-t2f-c4f.frag @@ -0,0 +1,6 @@ +// 2D drawing shader +uniform sampler2D texture; +void main() +{ + gl_FragColor = texture2D(texture, gl_TexCoord[0].xy) * gl_Color; +} diff --git a/tf-settings/shaders/v2f-t2f-c4f.vert b/tf-settings/shaders/v2f-t2f-c4f.vert new file mode 100644 index 00000000..1927b815 --- /dev/null +++ b/tf-settings/shaders/v2f-t2f-c4f.vert @@ -0,0 +1,15 @@ +// 2D drawing shader - modified freetype-gl shader +uniform mat4 model; +uniform mat4 view; +uniform mat4 projection; + +attribute vec2 vertex; +attribute vec2 tex_coord; +attribute vec4 color; + +void main() +{ + gl_TexCoord[0].xy = tex_coord.xy; + gl_FrontColor = color; + gl_Position = projection*(view*(model*vec4(vertex,0.0,1.0))); +} diff --git a/tf-settings/shaders/v3f-t2f-c4f.frag b/tf-settings/shaders/v3f-t2f-c4f.frag new file mode 100644 index 00000000..4b37f859 --- /dev/null +++ b/tf-settings/shaders/v3f-t2f-c4f.frag @@ -0,0 +1,11 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +uniform sampler2D texture; +void main() +{ + float a = texture2D(texture, gl_TexCoord[0].xy).r; + gl_FragColor = vec4(gl_Color.rgb, gl_Color.a*a); +} diff --git a/tf-settings/shaders/v3f-t2f-c4f.vert b/tf-settings/shaders/v3f-t2f-c4f.vert new file mode 100644 index 00000000..5d0232c3 --- /dev/null +++ b/tf-settings/shaders/v3f-t2f-c4f.vert @@ -0,0 +1,18 @@ +/* Freetype GL - A C OpenGL Freetype engine + * + * Distributed under the OSI-approved BSD 2-Clause License. See accompanying + * file `LICENSE` for more details. + */ +uniform mat4 model; +uniform mat4 view; +uniform mat4 projection; + +attribute vec3 vertex; +attribute vec2 tex_coord; +attribute vec4 color; +void main() +{ + gl_TexCoord[0].xy = tex_coord.xy; + gl_FrontColor = color; + gl_Position = projection*(view*(model*vec4(vertex,1.0))); +} diff --git a/ucccccp b/ucccccp new file mode 160000 index 00000000..5b577a66 --- /dev/null +++ b/ucccccp @@ -0,0 +1 @@ +Subproject commit 5b577a66da2e64726385cd28150123896cc1badf diff --git a/update b/update index 9f2f95e3..fa8be8c2 100755 --- a/update +++ b/update @@ -1,6 +1,2 @@ -#!/usr/bin/env bash - -git pull origin master && \ -git submodule update --remote --recursive && \ -make clean && \ -make -j4 +bash ./update-nobuild +./build-tf2 \ No newline at end of file diff --git a/update-data b/update-data new file mode 100755 index 00000000..3d594f93 --- /dev/null +++ b/update-data @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +echo "Searching for Team Fortress 2" +echo "Please wait..." + +find / -type d -name "Team Fortress 2" 2>/dev/null | while read path; do + if [ -e "$path/tf/gameinfo.txt" ]; then + if grep -q 440 "$path/tf/gameinfo.txt"; then + echo "Found Team Fortress 2 installation at $path" + mkdir -p "$path/cathook" + ln -s "$path/cathook" "Data Folder" + rsync -avh --progress tf-settings/ "$path/cathook" + echo "Symbolic link created (Data Folder)" + echo "You can close this window" + read -p "Press ENTER to continue" + fi + fi +done \ No newline at end of file diff --git a/update-nobuild b/update-nobuild new file mode 100755 index 00000000..9407fc0d --- /dev/null +++ b/update-nobuild @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +git pull origin master +git submodule update --remote --recursive +make clean + +./update-data + + +## Ask user if they would like to update the menu +#read -r -p "Update menu? (Y/n) " key +## If the user chose yes, then we run the script here +#if [ $key == "y"* ] || [ $key == "Y"* ]; then +# bash update-menu +#fi \ No newline at end of file