├── .gitignore ├── README.md ├── features ├── aim.cpp ├── aim.hpp ├── entry.cpp ├── entry.hpp ├── esp.cpp ├── esp.hpp ├── include.hpp ├── misc.cpp └── misc.hpp ├── gui ├── menu.cpp ├── menu.hpp ├── overlay.cpp └── overlay.hpp ├── imgui ├── imconfig.h ├── imgui.cpp ├── imgui.h ├── imgui_demo.cpp ├── imgui_draw.cpp ├── imgui_impl_dx11.cpp ├── imgui_impl_dx11.h ├── imgui_impl_win32.cpp ├── imgui_impl_win32.h ├── imgui_internal.h ├── imgui_tables.cpp ├── imgui_widgets.cpp ├── imstb_rectpack.h ├── imstb_textedit.h └── imstb_truetype.h ├── json ├── json.hpp ├── jsonOps.cpp └── jsonOps.hpp ├── offset_download.ps1 ├── screenshots └── preview.png ├── tim_apple.sln ├── tim_apple.vcxproj ├── tim_apple.vcxproj.filters ├── tim_apple.vcxproj.user ├── timapple.cpp └── util ├── MemMan.hpp ├── Vectors.h ├── attributes.cpp ├── attributes.hpp ├── config.hpp ├── utilFunctions.hpp └── weaponInfo.hpp /.gitignore: -------------------------------------------------------------------------------- 1 | External*Dependecies\ 2 | Debug/ 3 | x64/ 4 | .vs/ 5 | .git/ 6 | 7 | imgui.ini -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # :apple: Tim Apple 2 | Simple CS2 external cheat 3 | 4 | ![Preview](screenshots/preview.png) 5 | 6 | ## Features 7 | - Customizable ESP 8 | - Health bar (optional HP counter with numbers) 9 | - Player name 10 | - Weapon name 11 | - Skeleton 12 | - Snap lines 13 | - Distance 14 | - Aimbot 15 | - Recoil control system 16 | - Trigger bot 17 | - Bunny hop 18 | - Anti flash 19 | 20 | ## Compiling from source 21 | Open `tim_apple.sln` in Visual Studio 2022, set build configuration to `Release | x64`. 22 | Press Build solution and you should receive `tim_apple.exe` file. 23 | 24 | Press the `INSERT` key to toggle the menu. 25 | 26 | ## Offsets 27 | ### Script 28 | Run the `offset_download.ps1` in the same folder as you're executable is 29 | ### Manual 30 | 1. Download [client.dll.json](https://github.com/a2x/cs2-dumper/blob/main/generated/client.dll.json) and [offsets.json](https://github.com/a2x/cs2-dumper/blob/main/generated/offsets.json) 31 | 2. Place these files in the same folder as the executable file `tim_apple.exe` is 32 | 33 | 34 | ## Known bugs 35 | - Bone ESP lines go through the screen sometimes 36 | - RCS doesn't always work with aimbot 37 | 38 | ## Credits 39 | - [ocornut/imgui](https://github.com/ocornut/imgui) 40 | - [nlohmann/json](https://github.com/nlohmann/json) 41 | - [a2x/cs2-dumper](https://github.com/a2x/cs2-dumper) 42 | -------------------------------------------------------------------------------- /features/aim.cpp: -------------------------------------------------------------------------------- 1 | #include "aim.hpp" 2 | 3 | void aim::aimBot(LocalPlayer localPlayer, Vector3 baseViewAngles, DWORD_PTR baseViewAnglesAddy, uintptr_t boneArray) { 4 | Vector3 aimPos; 5 | Vector3 newAngle; 6 | 7 | aimPos = MemMan.ReadMem(boneArray + aimConf.boneMap[aimConf.bones[aimConf.boneSelect]] * 32); 8 | Vector3 angle = CalculateAngle(localPlayer.cameraPos, aimPos, localPlayer.viewAngles); 9 | newAngle = calculateBestAngle(angle, aimConf.fov); 10 | newAngle = clampAngles(newAngle); 11 | 12 | newAngle.x = newAngle.x / aimConf.smoothing; 13 | newAngle.y = newAngle.y / aimConf.smoothing; 14 | 15 | if (newAngle.IsZero()) { 16 | return; 17 | } 18 | 19 | if (aimConf.isHot) { 20 | if (GetAsyncKeyState(aimConf.hotKeyMap[aimConf.hotKey[aimConf.hotSelect]])) { 21 | MemMan.WriteMem(baseViewAnglesAddy, baseViewAngles + newAngle); 22 | } 23 | } 24 | else { 25 | MemMan.WriteMem(baseViewAnglesAddy, baseViewAngles + newAngle); 26 | } 27 | } 28 | 29 | void aim::recoilControl(LocalPlayer localPlayer, DWORD_PTR baseViewAnglesAddy) { 30 | localPlayer.getAimPunchCache(); 31 | localPlayer.getViewAngles(); 32 | 33 | static Vector3 oldPunch; 34 | Vector3 aimPunchAngle = MemMan.ReadMem(localPlayer.aimPunchCache.data + (localPlayer.aimPunchCache.count - 1) * sizeof(Vector3)); 35 | 36 | if (localPlayer.getShotsFired() > 1) { 37 | 38 | Vector3 recoilVector = { 39 | localPlayer.viewAngles.x + oldPunch.x - aimPunchAngle.x * 2.f, 40 | localPlayer.viewAngles.y + oldPunch.y - aimPunchAngle.y * 2.f 41 | }; 42 | recoilVector = clampAngles(recoilVector); 43 | 44 | MemMan.WriteMem(baseViewAnglesAddy, recoilVector); 45 | } 46 | oldPunch.x = aimPunchAngle.x * 2.f; 47 | oldPunch.y = aimPunchAngle.y * 2.f; 48 | } -------------------------------------------------------------------------------- /features/aim.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "include.hpp" 4 | 5 | #include "../util/config.hpp" 6 | #include "../gui/overlay.hpp" 7 | 8 | 9 | namespace aim { 10 | void aimBot(LocalPlayer localPlayer, Vector3 baseViewAngles,DWORD_PTR baseViewAnglesAddy,uintptr_t boneArray); 11 | void recoilControl(LocalPlayer localPlayer, DWORD_PTR baseViewAnglesAddy); 12 | } 13 | -------------------------------------------------------------------------------- /features/entry.cpp: -------------------------------------------------------------------------------- 1 | #include "esp.hpp" 2 | #include "aim.hpp" 3 | #include "misc.hpp" 4 | 5 | #include "../util/utilFunctions.hpp" 6 | 7 | void mainLoop(bool state, MemoryManagement::moduleData client) { 8 | 9 | // Classes 10 | Classes Classes(client); 11 | CCSPlayerController CCSPlayerController(client.base); 12 | C_CSPlayerPawn C_CSPlayerPawn(client.base); 13 | CGameSceneNode CGameSceneNode; 14 | LocalPlayer localPlayer(client); 15 | 16 | 17 | // Shared variables (between features) 18 | view_matrix_t viewMatrix = MemMan.ReadMem(client.base + offsets::clientDLL["dwViewMatrix"]["value"]); 19 | Vector3 baseViewAngles = MemMan.ReadMem(client.base + offsets::clientDLL["dwViewAngles"]["value"]); 20 | DWORD_PTR baseViewAnglesAddy = client.base + offsets::clientDLL["dwViewAngles"]["value"]; 21 | 22 | 23 | // NOTE: Cheats that only need local player / visuals that don't relate to gameplay 24 | localPlayer.getPlayerPawn(); 25 | // Aimbot FOV circle 26 | if (aimConf.fovCircle) { 27 | ImVec2 p = ImGui::GetWindowPos(); 28 | float screenMidX = GetSystemMetrics(SM_CXSCREEN) / 2; 29 | float screenMidY = GetSystemMetrics(SM_CYSCREEN) / 2; 30 | 31 | ImGui::GetBackgroundDrawList()->AddCircle({ screenMidX ,screenMidY }, (aimConf.fov * 10), ImColor(1.f, 1.f, 1.f, 1.f), 0, 1.f); 32 | } 33 | // Recoil control 34 | if (aimConf.rcs) { 35 | aim::recoilControl(localPlayer, baseViewAnglesAddy); 36 | } 37 | 38 | // Bunny hop 39 | if (miscConf.bunnyHop) { 40 | misc::bunnyHop(client.base, localPlayer.getFlags()); 41 | } 42 | 43 | // Flash 44 | if (miscConf.flash){ 45 | localPlayer.noFlash(); 46 | } 47 | 48 | // Tigger 49 | if (miscConf.trigger) { 50 | misc::triggerBot(localPlayer, client.base); 51 | } 52 | 53 | 54 | // Main loop 55 | for (int i = 0; i < 64; i++) { 56 | 57 | // Class and value initialisations 58 | Classes.getListEntry(i); 59 | 60 | CCSPlayerController.value = Classes.getCCSPlayerControllerBase(i); 61 | if (CCSPlayerController.value == 0) continue; 62 | 63 | C_CSPlayerPawn.value = CCSPlayerController.getC_CSPlayerPawn(); 64 | 65 | // Player pawn 66 | C_CSPlayerPawn.getPlayerPawn(); 67 | C_CSPlayerPawn.getPawnHealth(); 68 | 69 | CGameSceneNode.value = C_CSPlayerPawn.getCGameSceneNode(); 70 | 71 | 72 | // Checks 73 | if ((C_CSPlayerPawn.getPawnHealth() <= 0 || C_CSPlayerPawn.getPawnHealth() > 100) || localPlayer.getTeam() == CCSPlayerController.getPawnTeam()) { 74 | continue; 75 | } 76 | 77 | 78 | // ESP 79 | if (espConf.state) { 80 | esp::sharedData::weaponID = C_CSPlayerPawn.getWeaponID(); 81 | esp::sharedData::localOrigin = localPlayer.getOrigin(); 82 | esp::sharedData::entityOrigin = C_CSPlayerPawn.getOrigin(); 83 | esp::sharedData::distance = (int)(utils::getDistance(esp::sharedData::localOrigin, esp::sharedData::entityOrigin)) / 100; 84 | 85 | if (espConf.checkSpotted) { 86 | if (SharedFunctions::spottedCheck(C_CSPlayerPawn, localPlayer)) { 87 | esp::boundingBox(C_CSPlayerPawn.getOrigin(), viewMatrix, CCSPlayerController.getPawnName(), C_CSPlayerPawn.pawnHealth, CGameSceneNode.getBoneArray()); 88 | } 89 | } 90 | else { 91 | esp::boundingBox(C_CSPlayerPawn.getOrigin(), viewMatrix, CCSPlayerController.getPawnName(), C_CSPlayerPawn.pawnHealth, CGameSceneNode.getBoneArray()); 92 | } 93 | } 94 | 95 | // Aim 96 | if (aimConf.state) { 97 | localPlayer.getCameraPos(); 98 | localPlayer.getViewAngles(); 99 | 100 | if (aimConf.checkSpotted) { 101 | if (SharedFunctions::spottedCheck(C_CSPlayerPawn, localPlayer)) { 102 | aim::aimBot(localPlayer, baseViewAngles, baseViewAnglesAddy, CGameSceneNode.getBoneArray()); 103 | } 104 | } 105 | else { 106 | aim::aimBot(localPlayer, baseViewAngles, baseViewAnglesAddy, CGameSceneNode.getBoneArray()); 107 | } 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /features/entry.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "include.hpp" 4 | 5 | void mainLoop(bool state, MemoryManagement::moduleData client); -------------------------------------------------------------------------------- /features/esp.cpp: -------------------------------------------------------------------------------- 1 | #include "esp.hpp" 2 | 3 | #include "../util/utilFunctions.hpp" 4 | #include "../util/weaponInfo.hpp" 5 | 6 | void esp::makeHealthBar(float health) { 7 | int healthBarYOffset = ((int)(sharedData::height * health * 0.01f)); 8 | 9 | float red = (255 - (health * 2.55f)) - 100; 10 | float green = (health * 2.55f) / 100; 11 | 12 | ImGui::GetBackgroundDrawList()->AddRectFilled({ sharedData::headPosToScreen.x - (sharedData::width + 2), sharedData::originalPosToScreen.y - sharedData::height}, { sharedData::headPosToScreen.x - (sharedData::width + 5.5f), sharedData::originalPosToScreen.y }, ImColor(0.f, 0.f, 0.f, 0.3f)); 13 | ImGui::GetBackgroundDrawList()->AddRectFilled({ sharedData::headPosToScreen.x - (sharedData::width + 2), sharedData::originalPosToScreen.y - healthBarYOffset }, { sharedData::headPosToScreen.x - (sharedData::width + 5.5f), sharedData::originalPosToScreen.y }, ImColor(red, green, 0.f, 1.f)); 14 | if (espConf.hpCounter) { 15 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - (sharedData::width + 25) + 1, sharedData::originalPosToScreen.y - healthBarYOffset - 5 + 1 }, ImColor(1.0f, 1.0f, 1.0f, 1.0f) & IM_COL32_A_MASK, std::to_string((int)health).c_str()); 16 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - (sharedData::width + 25), sharedData::originalPosToScreen.y - healthBarYOffset - 5 }, ImColor(1.0f, 1.0f, 1.0f, 1.0f), std::to_string((int)health).c_str()); 17 | } 18 | } 19 | 20 | 21 | void esp::makeSkeleton(view_matrix_t viewMatrix, uintptr_t boneArray) { 22 | ImColor skeletonColour = ImColor(espConf.skeletonColours[0], espConf.skeletonColours[1], espConf.skeletonColours[2]); 23 | Vector3 previous, current; 24 | 25 | for (std::vector currentGroup : boneGroups::allGroups) { 26 | previous = { 0,0,0 }; 27 | 28 | for (int currentBone : currentGroup) { 29 | current = MemMan.ReadMem(boneArray + currentBone * 32); 30 | 31 | if (previous.IsZero()) { 32 | previous = current; 33 | continue; 34 | } 35 | 36 | Vector3 currentScreenPos = current.worldToScreen(viewMatrix); 37 | Vector3 previousScreenPos = previous.worldToScreen(viewMatrix); 38 | 39 | ImGui::GetBackgroundDrawList()->AddLine({ previousScreenPos.x,previousScreenPos.y }, { currentScreenPos.x,currentScreenPos.y }, skeletonColour,1.f); 40 | 41 | previous = current; 42 | } 43 | } 44 | } 45 | 46 | 47 | void esp::makeName(std::string name) { 48 | ImVec2 textSize = ImGui::CalcTextSize(name.c_str()); 49 | 50 | float horizontalOffset = textSize.x / 2.f; 51 | float verticalOffset = textSize.y; 52 | 53 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - horizontalOffset + 1, sharedData::headPosToScreen.y - verticalOffset + 1 }, ImColor(1.0f, 1.0f, 1.0f, 1.0f) & IM_COL32_A_MASK, name.c_str()); 54 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - horizontalOffset, sharedData::headPosToScreen.y - verticalOffset }, ImColor(1.0f, 1.0f, 1.0f, 1.0f), name.c_str()); 55 | } 56 | 57 | 58 | void esp::makeWeaponname() { 59 | std::string name = getWeaponFromID(weaponID); 60 | 61 | ImVec2 textSize = ImGui::CalcTextSize(name.c_str()); 62 | 63 | float horizontalOffset = textSize.x / 2.f; 64 | float verticalOffset = textSize.y - (sharedData::height + 15); 65 | 66 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - horizontalOffset + 1, sharedData::headPosToScreen.y - verticalOffset + 1 }, ImColor(1.0f, 1.0f, 1.0f, 1.0f) & IM_COL32_A_MASK, name.c_str()); 67 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - horizontalOffset, sharedData::headPosToScreen.y - verticalOffset }, ImColor(1.0f, 1.0f, 1.0f, 1.0f), name.c_str()); 68 | } 69 | 70 | void esp::makeDistance() { 71 | ImVec2 textSize = ImGui::CalcTextSize(std::to_string(sharedData::distance).c_str()); 72 | 73 | float horizontalOffset = textSize.x / 2.f; 74 | float verticalOffset = textSize.y; 75 | 76 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - horizontalOffset + 1, sharedData::headPosToScreen.y - verticalOffset - 12 + 1}, ImColor(1.0f, 1.0f, 1.0f, 1.0f) & IM_COL32_A_MASK, std::to_string(sharedData::distance).c_str()); 77 | ImGui::GetBackgroundDrawList()->AddText({ sharedData::headPosToScreen.x - horizontalOffset, sharedData::headPosToScreen.y - verticalOffset - 12}, ImColor(1.0f, 1.0f, 1.0f, 1.0f), std::to_string(sharedData::distance).c_str()); 78 | } 79 | 80 | 81 | void esp::boundingBox(Vector3 origin, view_matrix_t viewMatrix, std::string name, int health, uintptr_t boneArray) { 82 | if (origin.IsZero()) return; 83 | 84 | Vector3 originalPosToScreen = origin.worldToScreen(viewMatrix); 85 | sharedData::originalPosToScreen = originalPosToScreen; 86 | sharedData::origin = origin; 87 | 88 | Vector3 headPos; 89 | headPos.x = origin.x; 90 | headPos.y = origin.y; 91 | headPos.z = origin.z + 75.f; 92 | sharedData::headPos = headPos; 93 | 94 | Vector3 headPosToScreen = headPos.worldToScreen(viewMatrix); 95 | sharedData::headPosToScreen = headPosToScreen; 96 | 97 | float height = originalPosToScreen.y - headPosToScreen.y; 98 | float width = height * espConf.width; 99 | width = width / 10; 100 | sharedData::height = height; 101 | sharedData::width = width; 102 | 103 | if (originalPosToScreen.z >= 0.01f) { 104 | if (espConf.boundBox) { 105 | ImGui::GetBackgroundDrawList()->AddRect({ headPosToScreen.x - width, headPosToScreen.y }, { headPosToScreen.x + width, originalPosToScreen.y }, ImColor(espConf.colours[0], espConf.colours[1], espConf.colours[2]), 0, 0, 2.f); 106 | } 107 | 108 | if (espConf.isHealthBar) { 109 | makeHealthBar(health); 110 | } 111 | 112 | if (espConf.isPawnName) { 113 | makeName(name.c_str()); 114 | } 115 | 116 | if (espConf.isPawnGun) { 117 | makeWeaponname(); 118 | } 119 | 120 | if (espConf.skeleton) { 121 | makeSkeleton(viewMatrix, boneArray); 122 | } 123 | 124 | if (espConf.snapLines) { 125 | ImGui::GetBackgroundDrawList()->AddLine({ headPosToScreen.x - (width / 2), originalPosToScreen.y }, { (float)GetSystemMetrics(SM_CXSCREEN) / 2, (float)GetSystemMetrics(SM_CYSCREEN) }, ImColor(1.0f, 1.0f, 1.0f, 1.0f)); 126 | } 127 | 128 | if (espConf.distance) { 129 | makeDistance(); 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /features/esp.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "../gui/overlay.hpp" 6 | 7 | #include "../util/MemMan.hpp" 8 | #include "../util/attributes.hpp" 9 | #include "../util/config.hpp" 10 | #include "../util/Vectors.h" 11 | 12 | namespace esp { 13 | inline namespace sharedData { 14 | inline float width, height; 15 | inline Vector3 headPos, origin, headPosToScreen, originalPosToScreen; 16 | inline Vector3 localOrigin; 17 | inline Vector3 entityOrigin; 18 | inline uint64_t weaponID; 19 | inline int distance; 20 | }; 21 | 22 | void makeHealthBar(float health); 23 | void makeSkeleton(view_matrix_t viewMatrix, uintptr_t boneArray); 24 | void makeName(std::string name); 25 | void makeWeaponname(); 26 | void makeDistance(); 27 | 28 | void boundingBox(Vector3 origin, view_matrix_t viewMatrix, std::string name, int health, uintptr_t boneArray); 29 | } -------------------------------------------------------------------------------- /features/include.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "../util/attributes.hpp" 6 | #include "../util/Vectors.h" -------------------------------------------------------------------------------- /features/misc.cpp: -------------------------------------------------------------------------------- 1 | #include "misc.hpp" 2 | 3 | 4 | void misc::bunnyHop(DWORD_PTR base, int flags) { 5 | if (GetAsyncKeyState(VK_SPACE) && flags & bhopInAir) { 6 | MemMan.WriteMem(base + offsets::clientDLL["dwForceJump"]["value"], 65537); 7 | } 8 | else { 9 | MemMan.WriteMem(base + offsets::clientDLL["dwForceJump"]["value"], 256); 10 | } 11 | } 12 | 13 | 14 | void misc::triggerBot(LocalPlayer localPlayer,DWORD_PTR base) { 15 | int crossHairEntity = MemMan.ReadMem(localPlayer.getPlayerPawn() + clientDLL::C_CSPlayerPawnBase_["m_iIDEntIndex"]["value"]); 16 | if (!crossHairEntity) return; 17 | 18 | C_CSPlayerPawn crossHairPawn(base); 19 | crossHairPawn.getPlayerPawnByCrossHairID(crossHairEntity); 20 | 21 | bool isValidEntity = (crossHairEntity != -1 && crossHairPawn.getPawnHealth() > 0 && crossHairPawn.getPawnHealth() <= 100); 22 | 23 | if (miscConf.isHot) { 24 | if (GetAsyncKeyState(miscConf.hotKeyMap[miscConf.hotKey[miscConf.hotSelect]])) { 25 | if (isValidEntity) { 26 | mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); 27 | mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); 28 | }; 29 | } 30 | } 31 | else { 32 | if (isValidEntity) { 33 | mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); 34 | mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); 35 | }; 36 | } 37 | } -------------------------------------------------------------------------------- /features/misc.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "include.hpp" 4 | 5 | #include "../util/config.hpp" 6 | 7 | namespace misc { 8 | 9 | inline namespace sharedData { 10 | inline int bhopInAir = (1 << 0); 11 | }; 12 | 13 | void bunnyHop(DWORD_PTR base, int flags); 14 | void triggerBot(LocalPlayer localPlayer, DWORD_PTR base); 15 | } -------------------------------------------------------------------------------- /gui/menu.cpp: -------------------------------------------------------------------------------- 1 | #include "menu.hpp" 2 | 3 | #include "../features/entry.hpp" 4 | #include "../util/config.hpp" 5 | 6 | 7 | void imGuiMenu::setStyle() { 8 | // Setting styles 9 | ImGuiStyle* style = &ImGui::GetStyle(); 10 | 11 | // Sizes 12 | style->FramePadding = ImVec2(7,7); 13 | style->FrameBorderSize = 1.f; 14 | style->FrameRounding = 0.f; 15 | 16 | style->WindowPadding = ImVec2(6, 6); 17 | 18 | style->GrabRounding = 0.f; 19 | style->GrabMinSize = 20.f; 20 | 21 | style->ButtonTextAlign = ImVec2(0.5, 0.5); 22 | 23 | style->ItemSpacing = ImVec2(9,4); 24 | 25 | // Colour setup 26 | ImColor darkGrey = ImColor(29, 31, 31, 255); 27 | ImColor lightGrey = ImColor(38, 42, 43, 255); 28 | ImColor lightGreyTrans = ImColor(38, 42, 43, 175); 29 | 30 | ImColor darkBlue = ImColor(52, 98, 237, 255); 31 | ImColor lightBlue = ImColor(78, 139, 246, 255); 32 | 33 | // Colours 34 | style->Colors[ImGuiCol_FrameBg] = lightGrey; 35 | style->Colors[ImGuiCol_FrameBgHovered] = darkGrey; 36 | style->Colors[ImGuiCol_FrameBgActive] = darkGrey; 37 | 38 | style->Colors[ImGuiCol_TitleBgActive] = darkBlue; 39 | style->Colors[ImGuiCol_TitleBgCollapsed] = lightGreyTrans; 40 | 41 | style->Colors[ImGuiCol_ChildBg] = darkGrey; 42 | 43 | style->Colors[ImGuiCol_MenuBarBg] = lightGrey; 44 | style->Colors[ImGuiCol_WindowBg] = lightGrey; 45 | 46 | style->Colors[ImGuiCol_CheckMark] = darkBlue; 47 | 48 | style->Colors[ImGuiCol_Button] = darkBlue; 49 | style->Colors[ImGuiCol_ButtonHovered] = lightBlue; 50 | 51 | style->Colors[ImGuiCol_SliderGrab] = darkBlue; 52 | style->Colors[ImGuiCol_SliderGrabActive] = lightBlue; 53 | 54 | style->Colors[ImGuiCol_ResizeGrip] = darkBlue; 55 | style->Colors[ImGuiCol_ResizeGripHovered] = lightBlue; 56 | 57 | style->Colors[ImGuiCol_HeaderHovered] = darkBlue; 58 | style->Colors[ImGuiCol_HeaderActive] = lightBlue; 59 | } 60 | 61 | 62 | void imGuiMenu::verticalSplitter(float width,float height) { 63 | ImGui::SameLine(); 64 | ImGui::InvisibleButton("vsplitter", ImVec2(8.0f, height)); 65 | if (ImGui::IsItemActive()) 66 | width += ImGui::GetIO().MouseDelta.x; 67 | ImGui::SameLine(); 68 | } 69 | 70 | 71 | void imGuiMenu::horizontalSplitter(float height) { 72 | ImGui::InvisibleButton("hsplitter", ImVec2(-1, 8.0f)); 73 | if (ImGui::IsItemActive()) 74 | height += ImGui::GetIO().MouseDelta.y; 75 | } 76 | 77 | 78 | void imGuiMenu::espRender() { 79 | if (tabCount == 1) { 80 | 81 | ImGui::BeginChild("Features", ImVec2(imGuiMenu::widthSeparatorInt, imGuiMenu::heightSeparatorInt + 20), true); 82 | ImGui::PushFont(imGuiMenu::titleText); 83 | ImGui::Text("Attributes"); 84 | ImGui::PopFont(); 85 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 86 | ImGui::Checkbox("ESP toggle", &espConf.state); 87 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 88 | ImGui::Checkbox("Bounding Box", &espConf.boundBox); 89 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 90 | ImGui::Checkbox("Show player name", &espConf.isPawnName); 91 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 92 | ImGui::Checkbox("Reveal gun", &espConf.isPawnGun); 93 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 94 | ImGui::Checkbox("Health bar", &espConf.isHealthBar); 95 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 96 | ImGui::Checkbox("Skeleton", &espConf.skeleton); 97 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 98 | ImGui::Checkbox("Snap lines", &espConf.snapLines); 99 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 100 | ImGui::Checkbox("Distance", &espConf.distance); 101 | ImGui::EndChild(); 102 | 103 | verticalSplitter(imGuiMenu::widthSeparatorInt, imGuiMenu::heightSeparatorInt); 104 | 105 | ImGui::BeginChild("Feature options", ImVec2(0, imGuiMenu::heightSeparatorInt), true); 106 | ImGui::PushFont(imGuiMenu::titleText); 107 | ImGui::Text("Feature options"); 108 | ImGui::PopFont(); 109 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 110 | ImGui::Checkbox("Visibility check", &espConf.checkSpotted); 111 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 112 | ImGui::Checkbox("HP counter", &espConf.hpCounter); 113 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 114 | ImGui::SliderFloat("Box width", &espConf.width, 1.f, 5.f); 115 | ImGui::EndChild(); 116 | 117 | horizontalSplitter(HEIGHT); 118 | 119 | ImGui::BeginChild("Colours", ImVec2(0, 0), true); 120 | ImGui::PushFont(imGuiMenu::titleText); 121 | ImGui::Text("Colours"); 122 | ImGui::PopFont(); 123 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 124 | ImGui::ColorEdit3("Box colour", (float*)&espConf.colours); 125 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 126 | ImGui::ColorEdit3("Skeleton colour", (float*)&espConf.skeletonColours); 127 | ImGui::EndChild(); 128 | } 129 | } 130 | 131 | void imGuiMenu::aimRender() { 132 | if (tabCount == 2) { 133 | 134 | ImGui::BeginChild("Aimbot", ImVec2(imGuiMenu::widthSeparatorInt, imGuiMenu::heightSeparatorInt), true); 135 | ImGui::PushFont(imGuiMenu::titleText); 136 | ImGui::Text("Aimbot"); 137 | ImGui::PopFont(); 138 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 139 | ImGui::Checkbox("Aimbot", &aimConf.state); 140 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 141 | ImGui::Checkbox("Fov circle", &aimConf.fovCircle); 142 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 143 | ImGui::Checkbox("Visibility check", &aimConf.checkSpotted); 144 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 145 | ImGui::SliderFloat("FOV", &aimConf.fov, 1.f, 25.f); 146 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 147 | ImGui::SliderFloat("Smoothing", &aimConf.smoothing, 1.f, 5.f); 148 | ImGui::EndChild(); 149 | 150 | verticalSplitter(imGuiMenu::widthSeparatorInt, imGuiMenu::heightSeparatorInt); 151 | 152 | ImGui::BeginChild("Misc", ImVec2(0, imGuiMenu::heightSeparatorInt), true); 153 | ImGui::PushFont(imGuiMenu::titleText); 154 | ImGui::Text("Miscellaneous aim functions"); 155 | ImGui::PopFont(); 156 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 157 | ImGui::Checkbox("Recoil Control", &aimConf.rcs); 158 | ImGui::EndChild(); 159 | 160 | horizontalSplitter(HEIGHT); 161 | 162 | ImGui::BeginChild("Hitboxes", ImVec2(0, 0), true); 163 | ImGui::PushFont(imGuiMenu::titleText); 164 | ImGui::Text("Hitboxes"); 165 | ImGui::PopFont(); 166 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 167 | if (ImGui::BeginCombo("Hit box", aimConf.bones[aimConf.boneSelect].c_str())) { 168 | for (int i = 0; i < aimConf.bones.size(); ++i) { 169 | const bool isSelected = (aimConf.bone == i); 170 | 171 | if (ImGui::Selectable(aimConf.bones[i].c_str(), isSelected)) { 172 | aimConf.boneSelect = i; 173 | } 174 | 175 | if (isSelected) { 176 | ImGui::SetItemDefaultFocus(); 177 | } 178 | } 179 | ImGui::EndCombo(); 180 | } 181 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 182 | ImGui::Checkbox("Hot key state", &aimConf.isHot); 183 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 184 | if (aimConf.isHot) { 185 | if (ImGui::BeginCombo("Hot key", aimConf.hotKey[aimConf.hotSelect].c_str())) { 186 | for (int i = 0; i < aimConf.hotKey.size(); ++i) { 187 | const bool isSelected = (aimConf.hot == i); 188 | 189 | if (ImGui::Selectable(aimConf.hotKey[i].c_str(), isSelected)) { 190 | aimConf.hotSelect = i; 191 | } 192 | 193 | if (isSelected) { 194 | ImGui::SetItemDefaultFocus(); 195 | } 196 | } 197 | ImGui::EndCombo(); 198 | } 199 | } 200 | ImGui::EndChild(); 201 | } 202 | } 203 | 204 | void imGuiMenu::miscRender() { 205 | if (tabCount == 3) { 206 | ImGui::BeginChild("Aim", ImVec2(imGuiMenu::widthSeparatorInt, imGuiMenu::heightSeparatorInt), true); 207 | ImGui::PushFont(imGuiMenu::titleText); 208 | ImGui::Text("Aim"); 209 | ImGui::PopFont(); 210 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 211 | ImGui::Checkbox("Trigger Bot", &miscConf.trigger); 212 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 213 | ImGui::Checkbox("Hot key state", &miscConf.isHot); 214 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 215 | if (miscConf.isHot) { 216 | if (ImGui::BeginCombo("Hot key", miscConf.hotKey[miscConf.hotSelect].c_str())) { 217 | for (int i = 0; i < miscConf.hotKey.size(); ++i) { 218 | const bool isSelected = (miscConf.hot == i); 219 | 220 | if (ImGui::Selectable(miscConf.hotKey[i].c_str(), isSelected)) { 221 | miscConf.hotSelect = i; 222 | } 223 | 224 | if (isSelected) { 225 | ImGui::SetItemDefaultFocus(); 226 | } 227 | } 228 | ImGui::EndCombo(); 229 | } 230 | } 231 | ImGui::EndChild(); 232 | 233 | verticalSplitter(imGuiMenu::widthSeparatorInt, imGuiMenu::heightSeparatorInt); 234 | 235 | ImGui::BeginChild("Movement", ImVec2(0, imGuiMenu::heightSeparatorInt), true); 236 | ImGui::PushFont(imGuiMenu::titleText); 237 | ImGui::Text("Movement"); 238 | ImGui::PopFont(); 239 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 240 | ImGui::Checkbox("Bunny hop", &miscConf.bunnyHop); 241 | ImGui::EndChild(); 242 | 243 | horizontalSplitter(HEIGHT); 244 | 245 | ImGui::BeginChild("Visual", ImVec2(0, 0), true); 246 | ImGui::PushFont(imGuiMenu::titleText); 247 | ImGui::Text("Visual"); 248 | ImGui::PopFont(); 249 | ImGui::Dummy(ImVec2(0.0f, textSeparatorSpace)); 250 | ImGui::Checkbox("Anti flash", &miscConf.flash); 251 | ImGui::EndChild(); 252 | } 253 | } 254 | 255 | void imGuiMenu::menuBar() { 256 | ImGui::BeginMenuBar(); 257 | 258 | if (ImGui::MenuItem("ESP")) { 259 | tabCount = 1; 260 | } 261 | 262 | if (ImGui::MenuItem("Aim")) { 263 | tabCount = 2; 264 | } 265 | 266 | if (ImGui::MenuItem("Misc")) { 267 | tabCount = 3; 268 | } 269 | 270 | ImGui::EndMenuBar(); 271 | } 272 | 273 | 274 | void imGuiMenu::renderMenu(bool state) { 275 | ImGui::PushFont(normalText); 276 | ImGui::SetNextWindowSize({500,450}, ImGuiCond_FirstUseEver); 277 | ImGui::Begin("Tim Apple", &state, ImGuiWindowFlags_MenuBar); 278 | 279 | // Config 280 | setStyle(); 281 | menuBar(); 282 | 283 | // Menus 284 | espRender(); 285 | aimRender(); 286 | miscRender(); 287 | 288 | ImGui::PopFont(); 289 | ImGui::End(); 290 | } -------------------------------------------------------------------------------- /gui/menu.hpp: -------------------------------------------------------------------------------- 1 | #include "../imgui/imgui.h" 2 | 3 | namespace imGuiMenu { 4 | inline float WIDTH = 700.f; 5 | inline float HEIGHT = 650.f; 6 | 7 | inline int tabCount = 1; 8 | 9 | inline float areaSeparatorSpace = 8.f; 10 | inline float textSeparatorSpace = 4.f; 11 | inline float widthSeparatorInt = WIDTH / 2; 12 | inline float heightSeparatorInt = HEIGHT / 2 + 20; 13 | 14 | inline ImFont* normalText; 15 | inline ImFont* titleText; 16 | inline ImFont* highlightText; 17 | 18 | void menuBar(); 19 | void renderMenu(bool state); 20 | void setStyle(); 21 | 22 | void verticalSplitter(float width, float height); 23 | void horizontalSplitter(float height); 24 | 25 | 26 | void espRender(); 27 | void aimRender(); 28 | void miscRender(); 29 | } -------------------------------------------------------------------------------- /gui/overlay.cpp: -------------------------------------------------------------------------------- 1 | #include "overlay.hpp" 2 | #include "menu.hpp" 3 | 4 | #include "../util/Vectors.h" 5 | #include "../util/MemMan.hpp" 6 | #include "../util/attributes.hpp" 7 | 8 | #include "../features/entry.hpp" 9 | 10 | WNDCLASSEXW overlayESP::createWindowClass(HINSTANCE hInstance,WNDPROC Wndproc, LPCWSTR windowname) { 11 | this->hInstance = hInstance; 12 | 13 | windowClass.cbSize = sizeof(WNDCLASSEXA); 14 | windowClass.hInstance = hInstance; 15 | windowClass.lpfnWndProc = Wndproc; 16 | windowClass.style = CS_HREDRAW | CS_VREDRAW; 17 | windowClass.lpszClassName = windowname; 18 | 19 | return windowClass; 20 | }; 21 | 22 | 23 | HWND overlayESP::createWindow(int horizontalSize, int verticallSize) { 24 | HWND window = nullptr; 25 | RegisterClassExW(&windowClass); 26 | window = CreateWindowExW(WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED, windowClass.lpszClassName, windowClass.lpszClassName, WS_POPUP, 0, 0, 1920, 1080, 0, 0, windowClass.hInstance, 0); 27 | SetLayeredWindowAttributes(window, RGB(0, 0, 0), BYTE(255), LWA_ALPHA); 28 | 29 | this->window = window; 30 | 31 | return window; 32 | } 33 | 34 | 35 | void overlayESP::makeFrameIntoClientArea() { 36 | 37 | RECT clientArea{}; 38 | GetClientRect(window, &clientArea); 39 | 40 | RECT windowArea{}; 41 | GetWindowRect(window, &windowArea); 42 | 43 | POINT diff{}; 44 | ClientToScreen(window, &diff); 45 | 46 | const MARGINS margins{ 47 | windowArea.left + (diff.x - windowArea.left), 48 | windowArea.top + (diff.y - windowArea.top), 49 | clientArea.right, 50 | clientArea.bottom 51 | }; 52 | 53 | DwmExtendFrameIntoClientArea(window, &margins); 54 | } 55 | 56 | 57 | void overlayESP::makeDeviceAndSwapChain() { 58 | 59 | swapChain.BufferDesc.RefreshRate.Numerator = 60; 60 | swapChain.BufferDesc.RefreshRate.Denominator = 1; 61 | swapChain.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; 62 | swapChain.SampleDesc.Count = 1; 63 | swapChain.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; 64 | swapChain.BufferCount = 2; 65 | swapChain.OutputWindow = window; 66 | swapChain.Windowed = TRUE; 67 | swapChain.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; 68 | swapChain.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; 69 | 70 | D3D11CreateDeviceAndSwapChain(0, D3D_DRIVER_TYPE_HARDWARE, 0, 0, featureLevels, 2, D3D11_SDK_VERSION, &swapChain, &loadedSwapChain, &device, &loadedLevel, &deviceContext); 71 | 72 | loadedSwapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer)); 73 | 74 | if (backBuffer) { 75 | device->CreateRenderTargetView(backBuffer, 0, &renderTargetView); 76 | backBuffer->Release(); 77 | } 78 | }; 79 | 80 | void overlayESP::initWindow(int nShowCmd) { 81 | ShowWindow(window, nShowCmd); 82 | UpdateWindow(window); 83 | 84 | ImGui::CreateContext(); 85 | ImGuiIO& io = ImGui::GetIO(); 86 | io.Fonts->AddFontDefault(); 87 | imGuiMenu::normalText= io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\Verdana.ttf", 15.f); 88 | imGuiMenu::titleText = io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\verdanab.ttf", 15.f); 89 | imGuiMenu::highlightText = io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\verdanai.ttf", 13.f); 90 | ImGui::StyleColorsDark(); 91 | 92 | ImGui_ImplWin32_Init(window); 93 | ImGui_ImplDX11_Init(device, deviceContext); 94 | } 95 | 96 | void overlayESP::renderLoop(MemoryManagement::moduleData client) { 97 | bool state = true; 98 | bool menutoggle = true; 99 | 100 | while (state){ 101 | if (GetAsyncKeyState(VK_INSERT) & 1){ 102 | menutoggle = !menutoggle; 103 | } 104 | 105 | MSG msg; 106 | while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { 107 | TranslateMessage(&msg); 108 | DispatchMessage(&msg); 109 | 110 | if (msg.message == WM_QUIT) { 111 | state = false; 112 | } 113 | 114 | if (!state) { 115 | break; 116 | } 117 | } 118 | 119 | if (GetAsyncKeyState(VK_END)) { 120 | this->destroyWindow(); 121 | exit(0); 122 | } 123 | 124 | ImGui_ImplDX11_NewFrame(); 125 | ImGui_ImplWin32_NewFrame(); 126 | ImGui::NewFrame(); 127 | 128 | mainLoop(state,client); 129 | 130 | if (menutoggle) { 131 | imGuiMenu::renderMenu(state); 132 | SetWindowLong(window, GWL_EXSTYLE, WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TOOLWINDOW); 133 | } 134 | else { 135 | SetWindowLong(window, GWL_EXSTYLE, WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOOLWINDOW); 136 | } 137 | 138 | ImGui::EndFrame(); 139 | ImGui::Render(); 140 | 141 | float color[4]{ 0.f,0.f ,0.f ,0.f }; 142 | deviceContext->OMSetRenderTargets(1, &renderTargetView, 0); 143 | deviceContext->ClearRenderTargetView(renderTargetView, color); 144 | ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); 145 | 146 | loadedSwapChain->Present(1, 0); 147 | 148 | Sleep(1); 149 | } 150 | } 151 | 152 | void overlayESP::destroyWindow() { 153 | ImGui_ImplDX11_Shutdown(); 154 | ImGui_ImplWin32_Shutdown(); 155 | ImGui::DestroyContext(); 156 | 157 | if (loadedSwapChain) { 158 | loadedSwapChain->Release(); 159 | } 160 | if (deviceContext) { 161 | deviceContext->Release(); 162 | } 163 | if (device) { 164 | device->Release(); 165 | } 166 | if (renderTargetView) { 167 | renderTargetView->Release(); 168 | } 169 | 170 | DestroyWindow(window); 171 | UnregisterClassW(windowClass.lpszClassName, windowClass.hInstance); 172 | } -------------------------------------------------------------------------------- /gui/overlay.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define WIN32_LEAN_AND_MEAN 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #include "../imgui/imgui.h" 10 | #include "../imgui/imgui_impl_dx11.h" 11 | #include "../imgui/imgui_impl_win32.h" 12 | 13 | #include "../util/MemMan.hpp" 14 | 15 | extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); 16 | 17 | class overlayESP { 18 | public: 19 | 20 | HINSTANCE hInstance; 21 | WNDCLASSEXW windowClass; 22 | HWND window; 23 | 24 | DXGI_SWAP_CHAIN_DESC swapChain{}; 25 | D3D_FEATURE_LEVEL featureLevels[2]{ 26 | D3D_FEATURE_LEVEL_11_0, 27 | D3D_FEATURE_LEVEL_10_0 28 | }; 29 | ID3D11Device* device{ 0 }; 30 | ID3D11DeviceContext* deviceContext{ 0 }; 31 | IDXGISwapChain* loadedSwapChain{ 0 }; 32 | ID3D11RenderTargetView* renderTargetView{ 0 }; 33 | D3D_FEATURE_LEVEL loadedLevel{}; 34 | ID3D11Texture2D* backBuffer{ 0 }; 35 | 36 | 37 | WNDCLASSEXW createWindowClass(HINSTANCE hInstance,WNDPROC Wndproc,LPCWSTR windowname); 38 | 39 | HWND createWindow(int horizontalSize, int verticallSize); 40 | 41 | void makeFrameIntoClientArea(); 42 | 43 | void makeDeviceAndSwapChain(); 44 | 45 | void initWindow(int nShowCmd); 46 | 47 | void renderLoop(MemoryManagement::moduleData client); 48 | 49 | void destroyWindow(); 50 | }; -------------------------------------------------------------------------------- /imgui/imconfig.h: -------------------------------------------------------------------------------- 1 | //----------------------------------------------------------------------------- 2 | // DEAR IMGUI COMPILE-TIME OPTIONS 3 | // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. 4 | // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. 5 | //----------------------------------------------------------------------------- 6 | // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it) 7 | // B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template. 8 | //----------------------------------------------------------------------------- 9 | // You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp 10 | // files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures. 11 | // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts. 12 | // Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using. 13 | //----------------------------------------------------------------------------- 14 | 15 | #pragma once 16 | 17 | //---- Define assertion handler. Defaults to calling assert(). 18 | // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement. 19 | //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) 20 | //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts 21 | 22 | //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows 23 | // Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility. 24 | // DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions() 25 | // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details. 26 | //#define IMGUI_API __declspec( dllexport ) 27 | //#define IMGUI_API __declspec( dllimport ) 28 | 29 | //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names. 30 | //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS 31 | //#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions. 32 | 33 | //---- Disable all of Dear ImGui or don't implement standard windows/tools. 34 | // It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp. 35 | //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty. 36 | //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. 37 | //#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty. 38 | 39 | //---- Don't implement some functions to reduce linkage requirements. 40 | //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a) 41 | //#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW) 42 | //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a) 43 | //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME). 44 | //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default). 45 | //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf) 46 | //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself. 47 | //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies) 48 | //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function. 49 | //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions(). 50 | //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available 51 | 52 | //---- Include imgui_user.h at the end of imgui.h as a convenience 53 | //#define IMGUI_INCLUDE_IMGUI_USER_H 54 | 55 | //---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another) 56 | //#define IMGUI_USE_BGRA_PACKED_COLOR 57 | 58 | //---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...) 59 | //#define IMGUI_USE_WCHAR32 60 | 61 | //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version 62 | // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files. 63 | //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h" 64 | //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h" 65 | //#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined. 66 | //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION 67 | //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION 68 | //#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined. 69 | 70 | //---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined) 71 | // Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h. 72 | //#define IMGUI_USE_STB_SPRINTF 73 | 74 | //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui) 75 | // Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided). 76 | // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'. 77 | //#define IMGUI_ENABLE_FREETYPE 78 | 79 | //---- Use FreeType+lunasvg library to render OpenType SVG fonts (SVGinOT) 80 | // Requires lunasvg headers to be available in the include path + program to be linked with the lunasvg library (not provided). 81 | // Only works in combination with IMGUI_ENABLE_FREETYPE. 82 | // (implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement) 83 | //#define IMGUI_ENABLE_FREETYPE_LUNASVG 84 | 85 | //---- Use stb_truetype to build and rasterize the font atlas (default) 86 | // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend. 87 | //#define IMGUI_ENABLE_STB_TRUETYPE 88 | 89 | //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4. 90 | // This will be inlined as part of ImVec2 and ImVec4 class declarations. 91 | /* 92 | #define IM_VEC2_CLASS_EXTRA \ 93 | constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \ 94 | operator MyVec2() const { return MyVec2(x,y); } 95 | 96 | #define IM_VEC4_CLASS_EXTRA \ 97 | constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \ 98 | operator MyVec4() const { return MyVec4(x,y,z,w); } 99 | */ 100 | //---- ...Or use Dear ImGui's own very basic math operators. 101 | //#define IMGUI_DEFINE_MATH_OPERATORS 102 | 103 | //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices. 104 | // Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices). 105 | // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer. 106 | // Read about ImGuiBackendFlags_RendererHasVtxOffset for details. 107 | //#define ImDrawIdx unsigned int 108 | 109 | //---- Override ImDrawCallback signature (will need to modify renderer backends accordingly) 110 | //struct ImDrawList; 111 | //struct ImDrawCmd; 112 | //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data); 113 | //#define ImDrawCallback MyImDrawCallback 114 | 115 | //---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase) 116 | // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.) 117 | //#define IM_DEBUG_BREAK IM_ASSERT(0) 118 | //#define IM_DEBUG_BREAK __debugbreak() 119 | 120 | //---- Debug Tools: Enable slower asserts 121 | //#define IMGUI_DEBUG_PARANOID 122 | 123 | //---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files) 124 | /* 125 | namespace ImGui 126 | { 127 | void MyFunction(const char* name, MyMatrix44* mtx); 128 | } 129 | */ 130 | -------------------------------------------------------------------------------- /imgui/imgui_impl_dx11.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for DirectX11 2 | // This needs to be used along with a Platform Backend (e.g. Win32) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 10 | // Learn about Dear ImGui: 11 | // - FAQ https://dearimgui.com/faq 12 | // - Getting Started https://dearimgui.com/getting-started 13 | // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). 14 | // - Introduction, links and more at the top of imgui.cpp 15 | 16 | // CHANGELOG 17 | // (minor and older changes stripped away, please see git history for details) 18 | // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. 19 | // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). 20 | // 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement) 21 | // 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer. 22 | // 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled). 23 | // 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore. 24 | // 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag. 25 | // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state. 26 | // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile(). 27 | // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window. 28 | // 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility. 29 | // 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions. 30 | // 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example. 31 | // 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle. 32 | // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself. 33 | // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. 34 | // 2016-05-07: DirectX11: Disabling depth-write. 35 | 36 | #include "imgui.h" 37 | #ifndef IMGUI_DISABLE 38 | #include "imgui_impl_dx11.h" 39 | 40 | // DirectX 41 | #include 42 | #include 43 | #include 44 | #ifdef _MSC_VER 45 | #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below. 46 | #endif 47 | 48 | // DirectX11 data 49 | struct ImGui_ImplDX11_Data 50 | { 51 | ID3D11Device* pd3dDevice; 52 | ID3D11DeviceContext* pd3dDeviceContext; 53 | IDXGIFactory* pFactory; 54 | ID3D11Buffer* pVB; 55 | ID3D11Buffer* pIB; 56 | ID3D11VertexShader* pVertexShader; 57 | ID3D11InputLayout* pInputLayout; 58 | ID3D11Buffer* pVertexConstantBuffer; 59 | ID3D11PixelShader* pPixelShader; 60 | ID3D11SamplerState* pFontSampler; 61 | ID3D11ShaderResourceView* pFontTextureView; 62 | ID3D11RasterizerState* pRasterizerState; 63 | ID3D11BlendState* pBlendState; 64 | ID3D11DepthStencilState* pDepthStencilState; 65 | int VertexBufferSize; 66 | int IndexBufferSize; 67 | 68 | ImGui_ImplDX11_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; } 69 | }; 70 | 71 | struct VERTEX_CONSTANT_BUFFER_DX11 72 | { 73 | float mvp[4][4]; 74 | }; 75 | 76 | // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts 77 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. 78 | static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData() 79 | { 80 | return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; 81 | } 82 | 83 | // Functions 84 | static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* ctx) 85 | { 86 | ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); 87 | 88 | // Setup viewport 89 | D3D11_VIEWPORT vp; 90 | memset(&vp, 0, sizeof(D3D11_VIEWPORT)); 91 | vp.Width = draw_data->DisplaySize.x; 92 | vp.Height = draw_data->DisplaySize.y; 93 | vp.MinDepth = 0.0f; 94 | vp.MaxDepth = 1.0f; 95 | vp.TopLeftX = vp.TopLeftY = 0; 96 | ctx->RSSetViewports(1, &vp); 97 | 98 | // Setup shader and vertex buffers 99 | unsigned int stride = sizeof(ImDrawVert); 100 | unsigned int offset = 0; 101 | ctx->IASetInputLayout(bd->pInputLayout); 102 | ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset); 103 | ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); 104 | ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); 105 | ctx->VSSetShader(bd->pVertexShader, nullptr, 0); 106 | ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer); 107 | ctx->PSSetShader(bd->pPixelShader, nullptr, 0); 108 | ctx->PSSetSamplers(0, 1, &bd->pFontSampler); 109 | ctx->GSSetShader(nullptr, nullptr, 0); 110 | ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. 111 | ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. 112 | ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used.. 113 | 114 | // Setup blend state 115 | const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; 116 | ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff); 117 | ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0); 118 | ctx->RSSetState(bd->pRasterizerState); 119 | } 120 | 121 | // Render function 122 | void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) 123 | { 124 | // Avoid rendering when minimized 125 | if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f) 126 | return; 127 | 128 | ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); 129 | ID3D11DeviceContext* ctx = bd->pd3dDeviceContext; 130 | 131 | // Create and grow vertex/index buffers if needed 132 | if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount) 133 | { 134 | if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } 135 | bd->VertexBufferSize = draw_data->TotalVtxCount + 5000; 136 | D3D11_BUFFER_DESC desc; 137 | memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); 138 | desc.Usage = D3D11_USAGE_DYNAMIC; 139 | desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert); 140 | desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; 141 | desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; 142 | desc.MiscFlags = 0; 143 | if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0) 144 | return; 145 | } 146 | if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount) 147 | { 148 | if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } 149 | bd->IndexBufferSize = draw_data->TotalIdxCount + 10000; 150 | D3D11_BUFFER_DESC desc; 151 | memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); 152 | desc.Usage = D3D11_USAGE_DYNAMIC; 153 | desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx); 154 | desc.BindFlags = D3D11_BIND_INDEX_BUFFER; 155 | desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; 156 | if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0) 157 | return; 158 | } 159 | 160 | // Upload vertex/index data into a single contiguous GPU buffer 161 | D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource; 162 | if (ctx->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK) 163 | return; 164 | if (ctx->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK) 165 | return; 166 | ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData; 167 | ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData; 168 | for (int n = 0; n < draw_data->CmdListsCount; n++) 169 | { 170 | const ImDrawList* cmd_list = draw_data->CmdLists[n]; 171 | memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); 172 | memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); 173 | vtx_dst += cmd_list->VtxBuffer.Size; 174 | idx_dst += cmd_list->IdxBuffer.Size; 175 | } 176 | ctx->Unmap(bd->pVB, 0); 177 | ctx->Unmap(bd->pIB, 0); 178 | 179 | // Setup orthographic projection matrix into our constant buffer 180 | // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. 181 | { 182 | D3D11_MAPPED_SUBRESOURCE mapped_resource; 183 | if (ctx->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) 184 | return; 185 | VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData; 186 | float L = draw_data->DisplayPos.x; 187 | float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; 188 | float T = draw_data->DisplayPos.y; 189 | float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; 190 | float mvp[4][4] = 191 | { 192 | { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, 193 | { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, 194 | { 0.0f, 0.0f, 0.5f, 0.0f }, 195 | { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, 196 | }; 197 | memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); 198 | ctx->Unmap(bd->pVertexConstantBuffer, 0); 199 | } 200 | 201 | // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) 202 | struct BACKUP_DX11_STATE 203 | { 204 | UINT ScissorRectsCount, ViewportsCount; 205 | D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; 206 | D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; 207 | ID3D11RasterizerState* RS; 208 | ID3D11BlendState* BlendState; 209 | FLOAT BlendFactor[4]; 210 | UINT SampleMask; 211 | UINT StencilRef; 212 | ID3D11DepthStencilState* DepthStencilState; 213 | ID3D11ShaderResourceView* PSShaderResource; 214 | ID3D11SamplerState* PSSampler; 215 | ID3D11PixelShader* PS; 216 | ID3D11VertexShader* VS; 217 | ID3D11GeometryShader* GS; 218 | UINT PSInstancesCount, VSInstancesCount, GSInstancesCount; 219 | ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation 220 | D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology; 221 | ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; 222 | UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; 223 | DXGI_FORMAT IndexBufferFormat; 224 | ID3D11InputLayout* InputLayout; 225 | }; 226 | BACKUP_DX11_STATE old = {}; 227 | old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; 228 | ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects); 229 | ctx->RSGetViewports(&old.ViewportsCount, old.Viewports); 230 | ctx->RSGetState(&old.RS); 231 | ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask); 232 | ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); 233 | ctx->PSGetShaderResources(0, 1, &old.PSShaderResource); 234 | ctx->PSGetSamplers(0, 1, &old.PSSampler); 235 | old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256; 236 | ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount); 237 | ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount); 238 | ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); 239 | ctx->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount); 240 | 241 | ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology); 242 | ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); 243 | ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); 244 | ctx->IAGetInputLayout(&old.InputLayout); 245 | 246 | // Setup desired DX state 247 | ImGui_ImplDX11_SetupRenderState(draw_data, ctx); 248 | 249 | // Render command lists 250 | // (Because we merged all buffers into a single one, we maintain our own offset into them) 251 | int global_idx_offset = 0; 252 | int global_vtx_offset = 0; 253 | ImVec2 clip_off = draw_data->DisplayPos; 254 | for (int n = 0; n < draw_data->CmdListsCount; n++) 255 | { 256 | const ImDrawList* cmd_list = draw_data->CmdLists[n]; 257 | for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) 258 | { 259 | const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; 260 | if (pcmd->UserCallback != nullptr) 261 | { 262 | // User callback, registered via ImDrawList::AddCallback() 263 | // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.) 264 | if (pcmd->UserCallback == ImDrawCallback_ResetRenderState) 265 | ImGui_ImplDX11_SetupRenderState(draw_data, ctx); 266 | else 267 | pcmd->UserCallback(cmd_list, pcmd); 268 | } 269 | else 270 | { 271 | // Project scissor/clipping rectangles into framebuffer space 272 | ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y); 273 | ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y); 274 | if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y) 275 | continue; 276 | 277 | // Apply scissor/clipping rectangle 278 | const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y }; 279 | ctx->RSSetScissorRects(1, &r); 280 | 281 | // Bind texture, Draw 282 | ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID(); 283 | ctx->PSSetShaderResources(0, 1, &texture_srv); 284 | ctx->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset); 285 | } 286 | } 287 | global_idx_offset += cmd_list->IdxBuffer.Size; 288 | global_vtx_offset += cmd_list->VtxBuffer.Size; 289 | } 290 | 291 | // Restore modified DX state 292 | ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); 293 | ctx->RSSetViewports(old.ViewportsCount, old.Viewports); 294 | ctx->RSSetState(old.RS); if (old.RS) old.RS->Release(); 295 | ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release(); 296 | ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release(); 297 | ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release(); 298 | ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release(); 299 | ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release(); 300 | for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release(); 301 | ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release(); 302 | ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); 303 | ctx->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release(); 304 | for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release(); 305 | ctx->IASetPrimitiveTopology(old.PrimitiveTopology); 306 | ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); 307 | ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release(); 308 | ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); 309 | } 310 | 311 | static void ImGui_ImplDX11_CreateFontsTexture() 312 | { 313 | // Build texture atlas 314 | ImGuiIO& io = ImGui::GetIO(); 315 | ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); 316 | unsigned char* pixels; 317 | int width, height; 318 | io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); 319 | 320 | // Upload texture to graphics system 321 | { 322 | D3D11_TEXTURE2D_DESC desc; 323 | ZeroMemory(&desc, sizeof(desc)); 324 | desc.Width = width; 325 | desc.Height = height; 326 | desc.MipLevels = 1; 327 | desc.ArraySize = 1; 328 | desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; 329 | desc.SampleDesc.Count = 1; 330 | desc.Usage = D3D11_USAGE_DEFAULT; 331 | desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; 332 | desc.CPUAccessFlags = 0; 333 | 334 | ID3D11Texture2D* pTexture = nullptr; 335 | D3D11_SUBRESOURCE_DATA subResource; 336 | subResource.pSysMem = pixels; 337 | subResource.SysMemPitch = desc.Width * 4; 338 | subResource.SysMemSlicePitch = 0; 339 | bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); 340 | IM_ASSERT(pTexture != nullptr); 341 | 342 | // Create texture view 343 | D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; 344 | ZeroMemory(&srvDesc, sizeof(srvDesc)); 345 | srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; 346 | srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; 347 | srvDesc.Texture2D.MipLevels = desc.MipLevels; 348 | srvDesc.Texture2D.MostDetailedMip = 0; 349 | bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &bd->pFontTextureView); 350 | pTexture->Release(); 351 | } 352 | 353 | // Store our identifier 354 | io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView); 355 | 356 | // Create texture sampler 357 | // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling) 358 | { 359 | D3D11_SAMPLER_DESC desc; 360 | ZeroMemory(&desc, sizeof(desc)); 361 | desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; 362 | desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; 363 | desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; 364 | desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; 365 | desc.MipLODBias = 0.f; 366 | desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; 367 | desc.MinLOD = 0.f; 368 | desc.MaxLOD = 0.f; 369 | bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler); 370 | } 371 | } 372 | 373 | bool ImGui_ImplDX11_CreateDeviceObjects() 374 | { 375 | ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); 376 | if (!bd->pd3dDevice) 377 | return false; 378 | if (bd->pFontSampler) 379 | ImGui_ImplDX11_InvalidateDeviceObjects(); 380 | 381 | // By using D3DCompile() from / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) 382 | // If you would like to use this DX11 sample code but remove this dependency you can: 383 | // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution] 384 | // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. 385 | // See https://github.com/ocornut/imgui/pull/638 for sources and details. 386 | 387 | // Create the vertex shader 388 | { 389 | static const char* vertexShader = 390 | "cbuffer vertexBuffer : register(b0) \ 391 | {\ 392 | float4x4 ProjectionMatrix; \ 393 | };\ 394 | struct VS_INPUT\ 395 | {\ 396 | float2 pos : POSITION;\ 397 | float4 col : COLOR0;\ 398 | float2 uv : TEXCOORD0;\ 399 | };\ 400 | \ 401 | struct PS_INPUT\ 402 | {\ 403 | float4 pos : SV_POSITION;\ 404 | float4 col : COLOR0;\ 405 | float2 uv : TEXCOORD0;\ 406 | };\ 407 | \ 408 | PS_INPUT main(VS_INPUT input)\ 409 | {\ 410 | PS_INPUT output;\ 411 | output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ 412 | output.col = input.col;\ 413 | output.uv = input.uv;\ 414 | return output;\ 415 | }"; 416 | 417 | ID3DBlob* vertexShaderBlob; 418 | if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr))) 419 | return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! 420 | if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK) 421 | { 422 | vertexShaderBlob->Release(); 423 | return false; 424 | } 425 | 426 | // Create the input layout 427 | D3D11_INPUT_ELEMENT_DESC local_layout[] = 428 | { 429 | { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, 430 | { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)IM_OFFSETOF(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, 431 | { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)IM_OFFSETOF(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, 432 | }; 433 | if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK) 434 | { 435 | vertexShaderBlob->Release(); 436 | return false; 437 | } 438 | vertexShaderBlob->Release(); 439 | 440 | // Create the constant buffer 441 | { 442 | D3D11_BUFFER_DESC desc; 443 | desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11); 444 | desc.Usage = D3D11_USAGE_DYNAMIC; 445 | desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; 446 | desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; 447 | desc.MiscFlags = 0; 448 | bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer); 449 | } 450 | } 451 | 452 | // Create the pixel shader 453 | { 454 | static const char* pixelShader = 455 | "struct PS_INPUT\ 456 | {\ 457 | float4 pos : SV_POSITION;\ 458 | float4 col : COLOR0;\ 459 | float2 uv : TEXCOORD0;\ 460 | };\ 461 | sampler sampler0;\ 462 | Texture2D texture0;\ 463 | \ 464 | float4 main(PS_INPUT input) : SV_Target\ 465 | {\ 466 | float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ 467 | return out_col; \ 468 | }"; 469 | 470 | ID3DBlob* pixelShaderBlob; 471 | if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr))) 472 | return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! 473 | if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK) 474 | { 475 | pixelShaderBlob->Release(); 476 | return false; 477 | } 478 | pixelShaderBlob->Release(); 479 | } 480 | 481 | // Create the blending setup 482 | { 483 | D3D11_BLEND_DESC desc; 484 | ZeroMemory(&desc, sizeof(desc)); 485 | desc.AlphaToCoverageEnable = false; 486 | desc.RenderTarget[0].BlendEnable = true; 487 | desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; 488 | desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; 489 | desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; 490 | desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; 491 | desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; 492 | desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; 493 | desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; 494 | bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState); 495 | } 496 | 497 | // Create the rasterizer state 498 | { 499 | D3D11_RASTERIZER_DESC desc; 500 | ZeroMemory(&desc, sizeof(desc)); 501 | desc.FillMode = D3D11_FILL_SOLID; 502 | desc.CullMode = D3D11_CULL_NONE; 503 | desc.ScissorEnable = true; 504 | desc.DepthClipEnable = true; 505 | bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState); 506 | } 507 | 508 | // Create depth-stencil State 509 | { 510 | D3D11_DEPTH_STENCIL_DESC desc; 511 | ZeroMemory(&desc, sizeof(desc)); 512 | desc.DepthEnable = false; 513 | desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; 514 | desc.DepthFunc = D3D11_COMPARISON_ALWAYS; 515 | desc.StencilEnable = false; 516 | desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; 517 | desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; 518 | desc.BackFace = desc.FrontFace; 519 | bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState); 520 | } 521 | 522 | ImGui_ImplDX11_CreateFontsTexture(); 523 | 524 | return true; 525 | } 526 | 527 | void ImGui_ImplDX11_InvalidateDeviceObjects() 528 | { 529 | ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); 530 | if (!bd->pd3dDevice) 531 | return; 532 | 533 | if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; } 534 | if (bd->pFontTextureView) { bd->pFontTextureView->Release(); bd->pFontTextureView = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well. 535 | if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; } 536 | if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; } 537 | if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; } 538 | if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; } 539 | if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; } 540 | if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; } 541 | if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; } 542 | if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; } 543 | if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; } 544 | } 545 | 546 | bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context) 547 | { 548 | ImGuiIO& io = ImGui::GetIO(); 549 | IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!"); 550 | 551 | // Setup backend capabilities flags 552 | ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)(); 553 | io.BackendRendererUserData = (void*)bd; 554 | io.BackendRendererName = "imgui_impl_dx11"; 555 | io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes. 556 | 557 | // Get factory from device 558 | IDXGIDevice* pDXGIDevice = nullptr; 559 | IDXGIAdapter* pDXGIAdapter = nullptr; 560 | IDXGIFactory* pFactory = nullptr; 561 | 562 | if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK) 563 | if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK) 564 | if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK) 565 | { 566 | bd->pd3dDevice = device; 567 | bd->pd3dDeviceContext = device_context; 568 | bd->pFactory = pFactory; 569 | } 570 | if (pDXGIDevice) pDXGIDevice->Release(); 571 | if (pDXGIAdapter) pDXGIAdapter->Release(); 572 | bd->pd3dDevice->AddRef(); 573 | bd->pd3dDeviceContext->AddRef(); 574 | 575 | return true; 576 | } 577 | 578 | void ImGui_ImplDX11_Shutdown() 579 | { 580 | ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); 581 | IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?"); 582 | ImGuiIO& io = ImGui::GetIO(); 583 | 584 | ImGui_ImplDX11_InvalidateDeviceObjects(); 585 | if (bd->pFactory) { bd->pFactory->Release(); } 586 | if (bd->pd3dDevice) { bd->pd3dDevice->Release(); } 587 | if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); } 588 | io.BackendRendererName = nullptr; 589 | io.BackendRendererUserData = nullptr; 590 | io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset; 591 | IM_DELETE(bd); 592 | } 593 | 594 | void ImGui_ImplDX11_NewFrame() 595 | { 596 | ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData(); 597 | IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplDX11_Init()?"); 598 | 599 | if (!bd->pFontSampler) 600 | ImGui_ImplDX11_CreateDeviceObjects(); 601 | } 602 | 603 | //----------------------------------------------------------------------------- 604 | 605 | #endif // #ifndef IMGUI_DISABLE 606 | -------------------------------------------------------------------------------- /imgui/imgui_impl_dx11.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Renderer Backend for DirectX11 2 | // This needs to be used along with a Platform Backend (e.g. Win32) 3 | 4 | // Implemented features: 5 | // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID! 6 | // [X] Renderer: Large meshes support (64k+ vertices) with 16-bit indices. 7 | 8 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 9 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 10 | // Learn about Dear ImGui: 11 | // - FAQ https://dearimgui.com/faq 12 | // - Getting Started https://dearimgui.com/getting-started 13 | // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). 14 | // - Introduction, links and more at the top of imgui.cpp 15 | 16 | #pragma once 17 | #include "imgui.h" // IMGUI_IMPL_API 18 | #ifndef IMGUI_DISABLE 19 | 20 | struct ID3D11Device; 21 | struct ID3D11DeviceContext; 22 | 23 | IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context); 24 | IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown(); 25 | IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame(); 26 | IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data); 27 | 28 | // Use if you want to reset your rendering device without losing Dear ImGui state. 29 | IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects(); 30 | IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects(); 31 | 32 | #endif // #ifndef IMGUI_DISABLE 33 | -------------------------------------------------------------------------------- /imgui/imgui_impl_win32.cpp: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) 2 | // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) 3 | 4 | // Implemented features: 5 | // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) 6 | // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. 7 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 8 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 9 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. 10 | 11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 13 | // Learn about Dear ImGui: 14 | // - FAQ https://dearimgui.com/faq 15 | // - Getting Started https://dearimgui.com/getting-started 16 | // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). 17 | // - Introduction, links and more at the top of imgui.cpp 18 | 19 | #include "imgui.h" 20 | #ifndef IMGUI_DISABLE 21 | #include "imgui_impl_win32.h" 22 | #ifndef WIN32_LEAN_AND_MEAN 23 | #define WIN32_LEAN_AND_MEAN 24 | #endif 25 | #include 26 | #include // GET_X_LPARAM(), GET_Y_LPARAM() 27 | #include 28 | #include 29 | 30 | // Configuration flags to add in your imconfig.h file: 31 | //#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant. 32 | 33 | // Using XInput for gamepad (will load DLL dynamically) 34 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 35 | #include 36 | typedef DWORD (WINAPI *PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*); 37 | typedef DWORD (WINAPI *PFN_XInputGetState)(DWORD, XINPUT_STATE*); 38 | #endif 39 | 40 | // CHANGELOG 41 | // (minor and older changes stripped away, please see git history for details) 42 | // 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL). 43 | // 2023-09-07: Inputs: Added support for keyboard codepage conversion for when application is compiled in MBCS mode and using a non-Unicode window. 44 | // 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218) 45 | // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702) 46 | // 2023-02-15: Inputs: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse position over non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162) 47 | // 2023-02-02: Inputs: Flipping WM_MOUSEHWHEEL (horizontal mouse-wheel) value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463) 48 | // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11. 49 | // 2022-09-28: Inputs: Convert WM_CHAR values with MultiByteToWideChar() when window class was registered as MBCS (not Unicode). 50 | // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported). 51 | // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion. 52 | // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[]. 53 | // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+). 54 | // 2022-01-17: Inputs: always update key mods next and before a key event (not in NewFrame) to fix input queue with very low framerates. 55 | // 2022-01-12: Inputs: Update mouse inputs using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API. 56 | // 2022-01-12: Inputs: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted. 57 | // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range. 58 | // 2021-12-16: Inputs: Fill VK_LCONTROL/VK_RCONTROL/VK_LSHIFT/VK_RSHIFT/VK_LMENU/VK_RMENU for completeness. 59 | // 2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages. 60 | // 2021-08-02: Inputs: Fixed keyboard modifiers being reported when host window doesn't have focus. 61 | // 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using TrackMouseEvent() to receive WM_MOUSELEAVE events). 62 | // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX). 63 | // 2021-06-08: Fixed ImGui_ImplWin32_EnableDpiAwareness() and ImGui_ImplWin32_GetDpiScaleForMonitor() to handle Windows 8.1/10 features without a manifest (per-monitor DPI, and properly calls SetProcessDpiAwareness() on 8.1). 64 | // 2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS). 65 | // 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi). 66 | // 2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1. 67 | // 2021-01-25: Inputs: Dynamically loading XInput DLL. 68 | // 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed. 69 | // 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs) 70 | // 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions. 71 | // 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT. 72 | // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor. 73 | // 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter(). 74 | // 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent. 75 | // 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages. 76 | // 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application). 77 | // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window. 78 | // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor. 79 | // 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads). 80 | // 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples. 81 | // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. 82 | // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). 83 | // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. 84 | // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). 85 | // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. 86 | // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. 87 | // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert. 88 | // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag. 89 | // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read. 90 | // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging. 91 | // 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set. 92 | 93 | struct ImGui_ImplWin32_Data 94 | { 95 | HWND hWnd; 96 | HWND MouseHwnd; 97 | int MouseTrackedArea; // 0: not tracked, 1: client are, 2: non-client area 98 | int MouseButtonsDown; 99 | INT64 Time; 100 | INT64 TicksPerSecond; 101 | ImGuiMouseCursor LastMouseCursor; 102 | UINT32 KeyboardCodePage; 103 | 104 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 105 | bool HasGamepad; 106 | bool WantUpdateHasGamepad; 107 | HMODULE XInputDLL; 108 | PFN_XInputGetCapabilities XInputGetCapabilities; 109 | PFN_XInputGetState XInputGetState; 110 | #endif 111 | 112 | ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); } 113 | }; 114 | 115 | // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts 116 | // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts. 117 | // FIXME: multi-context support is not well tested and probably dysfunctional in this backend. 118 | // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context. 119 | static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData() 120 | { 121 | return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; 122 | } 123 | 124 | // Functions 125 | static void ImGui_ImplWin32_UpdateKeyboardCodePage() 126 | { 127 | // Retrieve keyboard code page, required for handling of non-Unicode Windows. 128 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); 129 | HKL keyboard_layout = ::GetKeyboardLayout(0); 130 | LCID keyboard_lcid = MAKELCID(HIWORD(keyboard_layout), SORT_DEFAULT); 131 | if (::GetLocaleInfoA(keyboard_lcid, (LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE), (LPSTR)&bd->KeyboardCodePage, sizeof(bd->KeyboardCodePage)) == 0) 132 | bd->KeyboardCodePage = CP_ACP; // Fallback to default ANSI code page when fails. 133 | } 134 | 135 | static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc) 136 | { 137 | ImGuiIO& io = ImGui::GetIO(); 138 | IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!"); 139 | 140 | INT64 perf_frequency, perf_counter; 141 | if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency)) 142 | return false; 143 | if (!::QueryPerformanceCounter((LARGE_INTEGER*)&perf_counter)) 144 | return false; 145 | 146 | // Setup backend capabilities flags 147 | ImGui_ImplWin32_Data* bd = IM_NEW(ImGui_ImplWin32_Data)(); 148 | io.BackendPlatformUserData = (void*)bd; 149 | io.BackendPlatformName = "imgui_impl_win32"; 150 | io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) 151 | io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) 152 | 153 | bd->hWnd = (HWND)hwnd; 154 | bd->TicksPerSecond = perf_frequency; 155 | bd->Time = perf_counter; 156 | bd->LastMouseCursor = ImGuiMouseCursor_COUNT; 157 | ImGui_ImplWin32_UpdateKeyboardCodePage(); 158 | 159 | // Set platform dependent data in viewport 160 | ImGui::GetMainViewport()->PlatformHandleRaw = (void*)hwnd; 161 | IM_UNUSED(platform_has_own_dc); // Used in 'docking' branch 162 | 163 | // Dynamically load XInput library 164 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 165 | bd->WantUpdateHasGamepad = true; 166 | const char* xinput_dll_names[] = 167 | { 168 | "xinput1_4.dll", // Windows 8+ 169 | "xinput1_3.dll", // DirectX SDK 170 | "xinput9_1_0.dll", // Windows Vista, Windows 7 171 | "xinput1_2.dll", // DirectX SDK 172 | "xinput1_1.dll" // DirectX SDK 173 | }; 174 | for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++) 175 | if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n])) 176 | { 177 | bd->XInputDLL = dll; 178 | bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities"); 179 | bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState"); 180 | break; 181 | } 182 | #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 183 | 184 | return true; 185 | } 186 | 187 | IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd) 188 | { 189 | return ImGui_ImplWin32_InitEx(hwnd, false); 190 | } 191 | 192 | IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd) 193 | { 194 | // OpenGL needs CS_OWNDC 195 | return ImGui_ImplWin32_InitEx(hwnd, true); 196 | } 197 | 198 | void ImGui_ImplWin32_Shutdown() 199 | { 200 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); 201 | IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?"); 202 | ImGuiIO& io = ImGui::GetIO(); 203 | 204 | // Unload XInput library 205 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 206 | if (bd->XInputDLL) 207 | ::FreeLibrary(bd->XInputDLL); 208 | #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 209 | 210 | io.BackendPlatformName = nullptr; 211 | io.BackendPlatformUserData = nullptr; 212 | io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad); 213 | IM_DELETE(bd); 214 | } 215 | 216 | static bool ImGui_ImplWin32_UpdateMouseCursor() 217 | { 218 | ImGuiIO& io = ImGui::GetIO(); 219 | if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) 220 | return false; 221 | 222 | ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); 223 | if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) 224 | { 225 | // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor 226 | ::SetCursor(nullptr); 227 | } 228 | else 229 | { 230 | // Show OS mouse cursor 231 | LPTSTR win32_cursor = IDC_ARROW; 232 | switch (imgui_cursor) 233 | { 234 | case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break; 235 | case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break; 236 | case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break; 237 | case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break; 238 | case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break; 239 | case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break; 240 | case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; 241 | case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break; 242 | case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break; 243 | } 244 | ::SetCursor(::LoadCursor(nullptr, win32_cursor)); 245 | } 246 | return true; 247 | } 248 | 249 | static bool IsVkDown(int vk) 250 | { 251 | return (::GetKeyState(vk) & 0x8000) != 0; 252 | } 253 | 254 | static void ImGui_ImplWin32_AddKeyEvent(ImGuiKey key, bool down, int native_keycode, int native_scancode = -1) 255 | { 256 | ImGuiIO& io = ImGui::GetIO(); 257 | io.AddKeyEvent(key, down); 258 | io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code) 259 | IM_UNUSED(native_scancode); 260 | } 261 | 262 | static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds() 263 | { 264 | // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one. 265 | if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT)) 266 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, false, VK_LSHIFT); 267 | if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT)) 268 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, false, VK_RSHIFT); 269 | 270 | // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW). 271 | if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN)) 272 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftSuper, false, VK_LWIN); 273 | if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN)) 274 | ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightSuper, false, VK_RWIN); 275 | } 276 | 277 | static void ImGui_ImplWin32_UpdateKeyModifiers() 278 | { 279 | ImGuiIO& io = ImGui::GetIO(); 280 | io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL)); 281 | io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT)); 282 | io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU)); 283 | io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_APPS)); 284 | } 285 | 286 | static void ImGui_ImplWin32_UpdateMouseData() 287 | { 288 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); 289 | ImGuiIO& io = ImGui::GetIO(); 290 | IM_ASSERT(bd->hWnd != 0); 291 | 292 | HWND focused_window = ::GetForegroundWindow(); 293 | const bool is_app_focused = (focused_window == bd->hWnd); 294 | if (is_app_focused) 295 | { 296 | // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) 297 | if (io.WantSetMousePos) 298 | { 299 | POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y }; 300 | if (::ClientToScreen(bd->hWnd, &pos)) 301 | ::SetCursorPos(pos.x, pos.y); 302 | } 303 | 304 | // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured) 305 | // This also fills a short gap when clicking non-client area: WM_NCMOUSELEAVE -> modal OS move -> gap -> WM_NCMOUSEMOVE 306 | if (!io.WantSetMousePos && bd->MouseTrackedArea == 0) 307 | { 308 | POINT pos; 309 | if (::GetCursorPos(&pos) && ::ScreenToClient(bd->hWnd, &pos)) 310 | io.AddMousePosEvent((float)pos.x, (float)pos.y); 311 | } 312 | } 313 | } 314 | 315 | // Gamepad navigation mapping 316 | static void ImGui_ImplWin32_UpdateGamepads() 317 | { 318 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 319 | ImGuiIO& io = ImGui::GetIO(); 320 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); 321 | //if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs. 322 | // return; 323 | 324 | // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow. 325 | // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE. 326 | if (bd->WantUpdateHasGamepad) 327 | { 328 | XINPUT_CAPABILITIES caps = {}; 329 | bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false; 330 | bd->WantUpdateHasGamepad = false; 331 | } 332 | 333 | io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad; 334 | XINPUT_STATE xinput_state; 335 | XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad; 336 | if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS) 337 | return; 338 | io.BackendFlags |= ImGuiBackendFlags_HasGamepad; 339 | 340 | #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V) 341 | #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); } 342 | #define MAP_ANALOG(KEY_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); io.AddKeyAnalogEvent(KEY_NO, vn > 0.10f, IM_SATURATE(vn)); } 343 | MAP_BUTTON(ImGuiKey_GamepadStart, XINPUT_GAMEPAD_START); 344 | MAP_BUTTON(ImGuiKey_GamepadBack, XINPUT_GAMEPAD_BACK); 345 | MAP_BUTTON(ImGuiKey_GamepadFaceLeft, XINPUT_GAMEPAD_X); 346 | MAP_BUTTON(ImGuiKey_GamepadFaceRight, XINPUT_GAMEPAD_B); 347 | MAP_BUTTON(ImGuiKey_GamepadFaceUp, XINPUT_GAMEPAD_Y); 348 | MAP_BUTTON(ImGuiKey_GamepadFaceDown, XINPUT_GAMEPAD_A); 349 | MAP_BUTTON(ImGuiKey_GamepadDpadLeft, XINPUT_GAMEPAD_DPAD_LEFT); 350 | MAP_BUTTON(ImGuiKey_GamepadDpadRight, XINPUT_GAMEPAD_DPAD_RIGHT); 351 | MAP_BUTTON(ImGuiKey_GamepadDpadUp, XINPUT_GAMEPAD_DPAD_UP); 352 | MAP_BUTTON(ImGuiKey_GamepadDpadDown, XINPUT_GAMEPAD_DPAD_DOWN); 353 | MAP_BUTTON(ImGuiKey_GamepadL1, XINPUT_GAMEPAD_LEFT_SHOULDER); 354 | MAP_BUTTON(ImGuiKey_GamepadR1, XINPUT_GAMEPAD_RIGHT_SHOULDER); 355 | MAP_ANALOG(ImGuiKey_GamepadL2, gamepad.bLeftTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); 356 | MAP_ANALOG(ImGuiKey_GamepadR2, gamepad.bRightTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255); 357 | MAP_BUTTON(ImGuiKey_GamepadL3, XINPUT_GAMEPAD_LEFT_THUMB); 358 | MAP_BUTTON(ImGuiKey_GamepadR3, XINPUT_GAMEPAD_RIGHT_THUMB); 359 | MAP_ANALOG(ImGuiKey_GamepadLStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); 360 | MAP_ANALOG(ImGuiKey_GamepadLStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); 361 | MAP_ANALOG(ImGuiKey_GamepadLStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); 362 | MAP_ANALOG(ImGuiKey_GamepadLStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); 363 | MAP_ANALOG(ImGuiKey_GamepadRStickLeft, gamepad.sThumbRX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); 364 | MAP_ANALOG(ImGuiKey_GamepadRStickRight, gamepad.sThumbRX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); 365 | MAP_ANALOG(ImGuiKey_GamepadRStickUp, gamepad.sThumbRY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767); 366 | MAP_ANALOG(ImGuiKey_GamepadRStickDown, gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768); 367 | #undef MAP_BUTTON 368 | #undef MAP_ANALOG 369 | #endif // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 370 | } 371 | 372 | void ImGui_ImplWin32_NewFrame() 373 | { 374 | ImGuiIO& io = ImGui::GetIO(); 375 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); 376 | IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplWin32_Init()?"); 377 | 378 | // Setup display size (every frame to accommodate for window resizing) 379 | RECT rect = { 0, 0, 0, 0 }; 380 | ::GetClientRect(bd->hWnd, &rect); 381 | io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); 382 | 383 | // Setup time step 384 | INT64 current_time = 0; 385 | ::QueryPerformanceCounter((LARGE_INTEGER*)¤t_time); 386 | io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond; 387 | bd->Time = current_time; 388 | 389 | // Update OS mouse position 390 | ImGui_ImplWin32_UpdateMouseData(); 391 | 392 | // Process workarounds for known Windows key handling issues 393 | ImGui_ImplWin32_ProcessKeyEventsWorkarounds(); 394 | 395 | // Update OS mouse cursor with the cursor requested by imgui 396 | ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); 397 | if (bd->LastMouseCursor != mouse_cursor) 398 | { 399 | bd->LastMouseCursor = mouse_cursor; 400 | ImGui_ImplWin32_UpdateMouseCursor(); 401 | } 402 | 403 | // Update game controllers (if enabled and available) 404 | ImGui_ImplWin32_UpdateGamepads(); 405 | } 406 | 407 | // There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED, we assign it an arbitrary value to make code more readable (VK_ codes go up to 255) 408 | #define IM_VK_KEYPAD_ENTER (VK_RETURN + 256) 409 | 410 | // Map VK_xxx to ImGuiKey_xxx. 411 | static ImGuiKey ImGui_ImplWin32_VirtualKeyToImGuiKey(WPARAM wParam) 412 | { 413 | switch (wParam) 414 | { 415 | case VK_TAB: return ImGuiKey_Tab; 416 | case VK_LEFT: return ImGuiKey_LeftArrow; 417 | case VK_RIGHT: return ImGuiKey_RightArrow; 418 | case VK_UP: return ImGuiKey_UpArrow; 419 | case VK_DOWN: return ImGuiKey_DownArrow; 420 | case VK_PRIOR: return ImGuiKey_PageUp; 421 | case VK_NEXT: return ImGuiKey_PageDown; 422 | case VK_HOME: return ImGuiKey_Home; 423 | case VK_END: return ImGuiKey_End; 424 | case VK_INSERT: return ImGuiKey_Insert; 425 | case VK_DELETE: return ImGuiKey_Delete; 426 | case VK_BACK: return ImGuiKey_Backspace; 427 | case VK_SPACE: return ImGuiKey_Space; 428 | case VK_RETURN: return ImGuiKey_Enter; 429 | case VK_ESCAPE: return ImGuiKey_Escape; 430 | case VK_OEM_7: return ImGuiKey_Apostrophe; 431 | case VK_OEM_COMMA: return ImGuiKey_Comma; 432 | case VK_OEM_MINUS: return ImGuiKey_Minus; 433 | case VK_OEM_PERIOD: return ImGuiKey_Period; 434 | case VK_OEM_2: return ImGuiKey_Slash; 435 | case VK_OEM_1: return ImGuiKey_Semicolon; 436 | case VK_OEM_PLUS: return ImGuiKey_Equal; 437 | case VK_OEM_4: return ImGuiKey_LeftBracket; 438 | case VK_OEM_5: return ImGuiKey_Backslash; 439 | case VK_OEM_6: return ImGuiKey_RightBracket; 440 | case VK_OEM_3: return ImGuiKey_GraveAccent; 441 | case VK_CAPITAL: return ImGuiKey_CapsLock; 442 | case VK_SCROLL: return ImGuiKey_ScrollLock; 443 | case VK_NUMLOCK: return ImGuiKey_NumLock; 444 | case VK_SNAPSHOT: return ImGuiKey_PrintScreen; 445 | case VK_PAUSE: return ImGuiKey_Pause; 446 | case VK_NUMPAD0: return ImGuiKey_Keypad0; 447 | case VK_NUMPAD1: return ImGuiKey_Keypad1; 448 | case VK_NUMPAD2: return ImGuiKey_Keypad2; 449 | case VK_NUMPAD3: return ImGuiKey_Keypad3; 450 | case VK_NUMPAD4: return ImGuiKey_Keypad4; 451 | case VK_NUMPAD5: return ImGuiKey_Keypad5; 452 | case VK_NUMPAD6: return ImGuiKey_Keypad6; 453 | case VK_NUMPAD7: return ImGuiKey_Keypad7; 454 | case VK_NUMPAD8: return ImGuiKey_Keypad8; 455 | case VK_NUMPAD9: return ImGuiKey_Keypad9; 456 | case VK_DECIMAL: return ImGuiKey_KeypadDecimal; 457 | case VK_DIVIDE: return ImGuiKey_KeypadDivide; 458 | case VK_MULTIPLY: return ImGuiKey_KeypadMultiply; 459 | case VK_SUBTRACT: return ImGuiKey_KeypadSubtract; 460 | case VK_ADD: return ImGuiKey_KeypadAdd; 461 | case IM_VK_KEYPAD_ENTER: return ImGuiKey_KeypadEnter; 462 | case VK_LSHIFT: return ImGuiKey_LeftShift; 463 | case VK_LCONTROL: return ImGuiKey_LeftCtrl; 464 | case VK_LMENU: return ImGuiKey_LeftAlt; 465 | case VK_LWIN: return ImGuiKey_LeftSuper; 466 | case VK_RSHIFT: return ImGuiKey_RightShift; 467 | case VK_RCONTROL: return ImGuiKey_RightCtrl; 468 | case VK_RMENU: return ImGuiKey_RightAlt; 469 | case VK_RWIN: return ImGuiKey_RightSuper; 470 | case VK_APPS: return ImGuiKey_Menu; 471 | case '0': return ImGuiKey_0; 472 | case '1': return ImGuiKey_1; 473 | case '2': return ImGuiKey_2; 474 | case '3': return ImGuiKey_3; 475 | case '4': return ImGuiKey_4; 476 | case '5': return ImGuiKey_5; 477 | case '6': return ImGuiKey_6; 478 | case '7': return ImGuiKey_7; 479 | case '8': return ImGuiKey_8; 480 | case '9': return ImGuiKey_9; 481 | case 'A': return ImGuiKey_A; 482 | case 'B': return ImGuiKey_B; 483 | case 'C': return ImGuiKey_C; 484 | case 'D': return ImGuiKey_D; 485 | case 'E': return ImGuiKey_E; 486 | case 'F': return ImGuiKey_F; 487 | case 'G': return ImGuiKey_G; 488 | case 'H': return ImGuiKey_H; 489 | case 'I': return ImGuiKey_I; 490 | case 'J': return ImGuiKey_J; 491 | case 'K': return ImGuiKey_K; 492 | case 'L': return ImGuiKey_L; 493 | case 'M': return ImGuiKey_M; 494 | case 'N': return ImGuiKey_N; 495 | case 'O': return ImGuiKey_O; 496 | case 'P': return ImGuiKey_P; 497 | case 'Q': return ImGuiKey_Q; 498 | case 'R': return ImGuiKey_R; 499 | case 'S': return ImGuiKey_S; 500 | case 'T': return ImGuiKey_T; 501 | case 'U': return ImGuiKey_U; 502 | case 'V': return ImGuiKey_V; 503 | case 'W': return ImGuiKey_W; 504 | case 'X': return ImGuiKey_X; 505 | case 'Y': return ImGuiKey_Y; 506 | case 'Z': return ImGuiKey_Z; 507 | case VK_F1: return ImGuiKey_F1; 508 | case VK_F2: return ImGuiKey_F2; 509 | case VK_F3: return ImGuiKey_F3; 510 | case VK_F4: return ImGuiKey_F4; 511 | case VK_F5: return ImGuiKey_F5; 512 | case VK_F6: return ImGuiKey_F6; 513 | case VK_F7: return ImGuiKey_F7; 514 | case VK_F8: return ImGuiKey_F8; 515 | case VK_F9: return ImGuiKey_F9; 516 | case VK_F10: return ImGuiKey_F10; 517 | case VK_F11: return ImGuiKey_F11; 518 | case VK_F12: return ImGuiKey_F12; 519 | default: return ImGuiKey_None; 520 | } 521 | } 522 | 523 | // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. 524 | #ifndef WM_MOUSEHWHEEL 525 | #define WM_MOUSEHWHEEL 0x020E 526 | #endif 527 | #ifndef DBT_DEVNODES_CHANGED 528 | #define DBT_DEVNODES_CHANGED 0x0007 529 | #endif 530 | 531 | // Win32 message handler (process Win32 mouse/keyboard inputs, etc.) 532 | // Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. 533 | // When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs. 534 | // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. 535 | // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. 536 | // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags. 537 | // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinates when dragging mouse outside of our window bounds. 538 | // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag. 539 | #if 0 540 | // Copy this line into your .cpp file to forward declare the function. 541 | extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); 542 | #endif 543 | 544 | // See https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages 545 | // Prefer to call this at the top of the message handler to avoid the possibility of other Win32 calls interfering with this. 546 | static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo() 547 | { 548 | LPARAM extra_info = ::GetMessageExtraInfo(); 549 | if ((extra_info & 0xFFFFFF80) == 0xFF515700) 550 | return ImGuiMouseSource_Pen; 551 | if ((extra_info & 0xFFFFFF80) == 0xFF515780) 552 | return ImGuiMouseSource_TouchScreen; 553 | return ImGuiMouseSource_Mouse; 554 | } 555 | 556 | IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 557 | { 558 | if (ImGui::GetCurrentContext() == nullptr) 559 | return 0; 560 | 561 | ImGuiIO& io = ImGui::GetIO(); 562 | ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(); 563 | 564 | switch (msg) 565 | { 566 | case WM_MOUSEMOVE: 567 | case WM_NCMOUSEMOVE: 568 | { 569 | // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events 570 | ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); 571 | const int area = (msg == WM_MOUSEMOVE) ? 1 : 2; 572 | bd->MouseHwnd = hwnd; 573 | if (bd->MouseTrackedArea != area) 574 | { 575 | TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 }; 576 | TRACKMOUSEEVENT tme_track = { sizeof(tme_track), (DWORD)((area == 2) ? (TME_LEAVE | TME_NONCLIENT) : TME_LEAVE), hwnd, 0 }; 577 | if (bd->MouseTrackedArea != 0) 578 | ::TrackMouseEvent(&tme_cancel); 579 | ::TrackMouseEvent(&tme_track); 580 | bd->MouseTrackedArea = area; 581 | } 582 | POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) }; 583 | if (msg == WM_NCMOUSEMOVE && ::ScreenToClient(hwnd, &mouse_pos) == FALSE) // WM_NCMOUSEMOVE are provided in absolute coordinates. 584 | break; 585 | io.AddMouseSourceEvent(mouse_source); 586 | io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y); 587 | break; 588 | } 589 | case WM_MOUSELEAVE: 590 | case WM_NCMOUSELEAVE: 591 | { 592 | const int area = (msg == WM_MOUSELEAVE) ? 1 : 2; 593 | if (bd->MouseTrackedArea == area) 594 | { 595 | if (bd->MouseHwnd == hwnd) 596 | bd->MouseHwnd = nullptr; 597 | bd->MouseTrackedArea = 0; 598 | io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); 599 | } 600 | break; 601 | } 602 | case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: 603 | case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: 604 | case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: 605 | case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: 606 | { 607 | ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); 608 | int button = 0; 609 | if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; } 610 | if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; } 611 | if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; } 612 | if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } 613 | if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr) 614 | ::SetCapture(hwnd); 615 | bd->MouseButtonsDown |= 1 << button; 616 | io.AddMouseSourceEvent(mouse_source); 617 | io.AddMouseButtonEvent(button, true); 618 | return 0; 619 | } 620 | case WM_LBUTTONUP: 621 | case WM_RBUTTONUP: 622 | case WM_MBUTTONUP: 623 | case WM_XBUTTONUP: 624 | { 625 | ImGuiMouseSource mouse_source = GetMouseSourceFromMessageExtraInfo(); 626 | int button = 0; 627 | if (msg == WM_LBUTTONUP) { button = 0; } 628 | if (msg == WM_RBUTTONUP) { button = 1; } 629 | if (msg == WM_MBUTTONUP) { button = 2; } 630 | if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; } 631 | bd->MouseButtonsDown &= ~(1 << button); 632 | if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd) 633 | ::ReleaseCapture(); 634 | io.AddMouseSourceEvent(mouse_source); 635 | io.AddMouseButtonEvent(button, false); 636 | return 0; 637 | } 638 | case WM_MOUSEWHEEL: 639 | io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA); 640 | return 0; 641 | case WM_MOUSEHWHEEL: 642 | io.AddMouseWheelEvent(-(float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f); 643 | return 0; 644 | case WM_KEYDOWN: 645 | case WM_KEYUP: 646 | case WM_SYSKEYDOWN: 647 | case WM_SYSKEYUP: 648 | { 649 | const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN); 650 | if (wParam < 256) 651 | { 652 | // Submit modifiers 653 | ImGui_ImplWin32_UpdateKeyModifiers(); 654 | 655 | // Obtain virtual key code 656 | // (keypad enter doesn't have its own... VK_RETURN with KF_EXTENDED flag means keypad enter, see IM_VK_KEYPAD_ENTER definition for details, it is mapped to ImGuiKey_KeyPadEnter.) 657 | int vk = (int)wParam; 658 | if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED)) 659 | vk = IM_VK_KEYPAD_ENTER; 660 | const ImGuiKey key = ImGui_ImplWin32_VirtualKeyToImGuiKey(vk); 661 | const int scancode = (int)LOBYTE(HIWORD(lParam)); 662 | 663 | // Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event. 664 | if (key == ImGuiKey_PrintScreen && !is_key_down) 665 | ImGui_ImplWin32_AddKeyEvent(key, true, vk, scancode); 666 | 667 | // Submit key event 668 | if (key != ImGuiKey_None) 669 | ImGui_ImplWin32_AddKeyEvent(key, is_key_down, vk, scancode); 670 | 671 | // Submit individual left/right modifier events 672 | if (vk == VK_SHIFT) 673 | { 674 | // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds() 675 | if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); } 676 | if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); } 677 | } 678 | else if (vk == VK_CONTROL) 679 | { 680 | if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); } 681 | if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); } 682 | } 683 | else if (vk == VK_MENU) 684 | { 685 | if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); } 686 | if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); } 687 | } 688 | } 689 | return 0; 690 | } 691 | case WM_SETFOCUS: 692 | case WM_KILLFOCUS: 693 | io.AddFocusEvent(msg == WM_SETFOCUS); 694 | return 0; 695 | case WM_INPUTLANGCHANGE: 696 | ImGui_ImplWin32_UpdateKeyboardCodePage(); 697 | return 0; 698 | case WM_CHAR: 699 | if (::IsWindowUnicode(hwnd)) 700 | { 701 | // You can also use ToAscii()+GetKeyboardState() to retrieve characters. 702 | if (wParam > 0 && wParam < 0x10000) 703 | io.AddInputCharacterUTF16((unsigned short)wParam); 704 | } 705 | else 706 | { 707 | wchar_t wch = 0; 708 | ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1); 709 | io.AddInputCharacter(wch); 710 | } 711 | return 0; 712 | case WM_SETCURSOR: 713 | // This is required to restore cursor when transitioning from e.g resize borders to client area. 714 | if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor()) 715 | return 1; 716 | return 0; 717 | case WM_DEVICECHANGE: 718 | #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD 719 | if ((UINT)wParam == DBT_DEVNODES_CHANGED) 720 | bd->WantUpdateHasGamepad = true; 721 | #endif 722 | return 0; 723 | } 724 | return 0; 725 | } 726 | 727 | 728 | //-------------------------------------------------------------------------------------------------------- 729 | // DPI-related helpers (optional) 730 | //-------------------------------------------------------------------------------------------------------- 731 | // - Use to enable DPI awareness without having to create an application manifest. 732 | // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. 733 | // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. 734 | // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, 735 | // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. 736 | //--------------------------------------------------------------------------------------------------------- 737 | // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable. 738 | // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically. 739 | // If you are trying to implement your own backend for your own engine, you may ignore that noise. 740 | //--------------------------------------------------------------------------------------------------------- 741 | 742 | // Perform our own check with RtlVerifyVersionInfo() instead of using functions from as they 743 | // require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200 744 | static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD) 745 | { 746 | typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG); 747 | static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr; 748 | if (RtlVerifyVersionInfoFn == nullptr) 749 | if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll")) 750 | RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo"); 751 | if (RtlVerifyVersionInfoFn == nullptr) 752 | return FALSE; 753 | 754 | RTL_OSVERSIONINFOEXW versionInfo = { }; 755 | ULONGLONG conditionMask = 0; 756 | versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); 757 | versionInfo.dwMajorVersion = major; 758 | versionInfo.dwMinorVersion = minor; 759 | VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); 760 | VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); 761 | return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE; 762 | } 763 | 764 | #define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA 765 | #define _IsWindows8OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8 766 | #define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE 767 | #define _IsWindows10OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10 768 | 769 | #ifndef DPI_ENUMS_DECLARED 770 | typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS; 771 | typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE; 772 | #endif 773 | #ifndef _DPI_AWARENESS_CONTEXTS_ 774 | DECLARE_HANDLE(DPI_AWARENESS_CONTEXT); 775 | #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3 776 | #endif 777 | #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 778 | #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4 779 | #endif 780 | typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+ 781 | typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+ 782 | typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update) 783 | 784 | // Helper function to enable DPI awareness without setting up a manifest 785 | void ImGui_ImplWin32_EnableDpiAwareness() 786 | { 787 | if (_IsWindows10OrGreater()) 788 | { 789 | static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process 790 | if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext")) 791 | { 792 | SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); 793 | return; 794 | } 795 | } 796 | if (_IsWindows8Point1OrGreater()) 797 | { 798 | static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process 799 | if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness")) 800 | { 801 | SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE); 802 | return; 803 | } 804 | } 805 | #if _WIN32_WINNT >= 0x0600 806 | ::SetProcessDPIAware(); 807 | #endif 808 | } 809 | 810 | #if defined(_MSC_VER) && !defined(NOGDI) 811 | #pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32' 812 | #endif 813 | 814 | float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor) 815 | { 816 | UINT xdpi = 96, ydpi = 96; 817 | if (_IsWindows8Point1OrGreater()) 818 | { 819 | static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process 820 | static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr; 821 | if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr) 822 | GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor"); 823 | if (GetDpiForMonitorFn != nullptr) 824 | { 825 | GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi); 826 | IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! 827 | return xdpi / 96.0f; 828 | } 829 | } 830 | #ifndef NOGDI 831 | const HDC dc = ::GetDC(nullptr); 832 | xdpi = ::GetDeviceCaps(dc, LOGPIXELSX); 833 | ydpi = ::GetDeviceCaps(dc, LOGPIXELSY); 834 | IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert! 835 | ::ReleaseDC(nullptr, dc); 836 | #endif 837 | return xdpi / 96.0f; 838 | } 839 | 840 | float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd) 841 | { 842 | HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST); 843 | return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor); 844 | } 845 | 846 | //--------------------------------------------------------------------------------------------------------- 847 | // Transparency related helpers (optional) 848 | //-------------------------------------------------------------------------------------------------------- 849 | 850 | #if defined(_MSC_VER) 851 | #pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi' 852 | #endif 853 | 854 | // [experimental] 855 | // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c 856 | // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW) 857 | void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd) 858 | { 859 | if (!_IsWindowsVistaOrGreater()) 860 | return; 861 | 862 | BOOL composition; 863 | if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition) 864 | return; 865 | 866 | BOOL opaque; 867 | DWORD color; 868 | if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque)) 869 | { 870 | HRGN region = ::CreateRectRgn(0, 0, -1, -1); 871 | DWM_BLURBEHIND bb = {}; 872 | bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION; 873 | bb.hRgnBlur = region; 874 | bb.fEnable = TRUE; 875 | ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); 876 | ::DeleteObject(region); 877 | } 878 | else 879 | { 880 | DWM_BLURBEHIND bb = {}; 881 | bb.dwFlags = DWM_BB_ENABLE; 882 | ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb); 883 | } 884 | } 885 | 886 | //--------------------------------------------------------------------------------------------------------- 887 | 888 | #endif // #ifndef IMGUI_DISABLE 889 | -------------------------------------------------------------------------------- /imgui/imgui_impl_win32.h: -------------------------------------------------------------------------------- 1 | // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications) 2 | // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..) 3 | 4 | // Implemented features: 5 | // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui) 6 | // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen. 7 | // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set] 8 | // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'. 9 | // [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. 10 | 11 | // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this. 12 | // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need. 13 | // Learn about Dear ImGui: 14 | // - FAQ https://dearimgui.com/faq 15 | // - Getting Started https://dearimgui.com/getting-started 16 | // - Documentation https://dearimgui.com/docs (same as your local docs/ folder). 17 | // - Introduction, links and more at the top of imgui.cpp 18 | 19 | #pragma once 20 | #include "imgui.h" // IMGUI_IMPL_API 21 | #ifndef IMGUI_DISABLE 22 | 23 | IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd); 24 | IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd); 25 | IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown(); 26 | IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame(); 27 | 28 | // Win32 message handler your application need to call. 29 | // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on from this helper. 30 | // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it. 31 | // - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE. 32 | 33 | #if 0 34 | extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); 35 | #endif 36 | 37 | // DPI-related helpers (optional) 38 | // - Use to enable DPI awareness without having to create an application manifest. 39 | // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps. 40 | // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc. 41 | // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime, 42 | // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies. 43 | IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness(); 44 | IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd 45 | IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor 46 | 47 | // Transparency related helpers (optional) [experimental] 48 | // - Use to enable alpha compositing transparency with the desktop. 49 | // - Use together with e.g. clearing your framebuffer with zero-alpha. 50 | IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd 51 | 52 | #endif // #ifndef IMGUI_DISABLE 53 | -------------------------------------------------------------------------------- /imgui/imstb_rectpack.h: -------------------------------------------------------------------------------- 1 | // [DEAR IMGUI] 2 | // This is a slightly modified version of stb_rect_pack.h 1.01. 3 | // Grep for [DEAR IMGUI] to find the changes. 4 | // 5 | // stb_rect_pack.h - v1.01 - public domain - rectangle packing 6 | // Sean Barrett 2014 7 | // 8 | // Useful for e.g. packing rectangular textures into an atlas. 9 | // Does not do rotation. 10 | // 11 | // Before #including, 12 | // 13 | // #define STB_RECT_PACK_IMPLEMENTATION 14 | // 15 | // in the file that you want to have the implementation. 16 | // 17 | // Not necessarily the awesomest packing method, but better than 18 | // the totally naive one in stb_truetype (which is primarily what 19 | // this is meant to replace). 20 | // 21 | // Has only had a few tests run, may have issues. 22 | // 23 | // More docs to come. 24 | // 25 | // No memory allocations; uses qsort() and assert() from stdlib. 26 | // Can override those by defining STBRP_SORT and STBRP_ASSERT. 27 | // 28 | // This library currently uses the Skyline Bottom-Left algorithm. 29 | // 30 | // Please note: better rectangle packers are welcome! Please 31 | // implement them to the same API, but with a different init 32 | // function. 33 | // 34 | // Credits 35 | // 36 | // Library 37 | // Sean Barrett 38 | // Minor features 39 | // Martins Mozeiko 40 | // github:IntellectualKitty 41 | // 42 | // Bugfixes / warning fixes 43 | // Jeremy Jaussaud 44 | // Fabian Giesen 45 | // 46 | // Version history: 47 | // 48 | // 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section 49 | // 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles 50 | // 0.99 (2019-02-07) warning fixes 51 | // 0.11 (2017-03-03) return packing success/fail result 52 | // 0.10 (2016-10-25) remove cast-away-const to avoid warnings 53 | // 0.09 (2016-08-27) fix compiler warnings 54 | // 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) 55 | // 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) 56 | // 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort 57 | // 0.05: added STBRP_ASSERT to allow replacing assert 58 | // 0.04: fixed minor bug in STBRP_LARGE_RECTS support 59 | // 0.01: initial release 60 | // 61 | // LICENSE 62 | // 63 | // See end of file for license information. 64 | 65 | ////////////////////////////////////////////////////////////////////////////// 66 | // 67 | // INCLUDE SECTION 68 | // 69 | 70 | #ifndef STB_INCLUDE_STB_RECT_PACK_H 71 | #define STB_INCLUDE_STB_RECT_PACK_H 72 | 73 | #define STB_RECT_PACK_VERSION 1 74 | 75 | #ifdef STBRP_STATIC 76 | #define STBRP_DEF static 77 | #else 78 | #define STBRP_DEF extern 79 | #endif 80 | 81 | #ifdef __cplusplus 82 | extern "C" { 83 | #endif 84 | 85 | typedef struct stbrp_context stbrp_context; 86 | typedef struct stbrp_node stbrp_node; 87 | typedef struct stbrp_rect stbrp_rect; 88 | 89 | typedef int stbrp_coord; 90 | 91 | #define STBRP__MAXVAL 0x7fffffff 92 | // Mostly for internal use, but this is the maximum supported coordinate value. 93 | 94 | STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects); 95 | // Assign packed locations to rectangles. The rectangles are of type 96 | // 'stbrp_rect' defined below, stored in the array 'rects', and there 97 | // are 'num_rects' many of them. 98 | // 99 | // Rectangles which are successfully packed have the 'was_packed' flag 100 | // set to a non-zero value and 'x' and 'y' store the minimum location 101 | // on each axis (i.e. bottom-left in cartesian coordinates, top-left 102 | // if you imagine y increasing downwards). Rectangles which do not fit 103 | // have the 'was_packed' flag set to 0. 104 | // 105 | // You should not try to access the 'rects' array from another thread 106 | // while this function is running, as the function temporarily reorders 107 | // the array while it executes. 108 | // 109 | // To pack into another rectangle, you need to call stbrp_init_target 110 | // again. To continue packing into the same rectangle, you can call 111 | // this function again. Calling this multiple times with multiple rect 112 | // arrays will probably produce worse packing results than calling it 113 | // a single time with the full rectangle array, but the option is 114 | // available. 115 | // 116 | // The function returns 1 if all of the rectangles were successfully 117 | // packed and 0 otherwise. 118 | 119 | struct stbrp_rect 120 | { 121 | // reserved for your use: 122 | int id; 123 | 124 | // input: 125 | stbrp_coord w, h; 126 | 127 | // output: 128 | stbrp_coord x, y; 129 | int was_packed; // non-zero if valid packing 130 | 131 | }; // 16 bytes, nominally 132 | 133 | 134 | STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes); 135 | // Initialize a rectangle packer to: 136 | // pack a rectangle that is 'width' by 'height' in dimensions 137 | // using temporary storage provided by the array 'nodes', which is 'num_nodes' long 138 | // 139 | // You must call this function every time you start packing into a new target. 140 | // 141 | // There is no "shutdown" function. The 'nodes' memory must stay valid for 142 | // the following stbrp_pack_rects() call (or calls), but can be freed after 143 | // the call (or calls) finish. 144 | // 145 | // Note: to guarantee best results, either: 146 | // 1. make sure 'num_nodes' >= 'width' 147 | // or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1' 148 | // 149 | // If you don't do either of the above things, widths will be quantized to multiples 150 | // of small integers to guarantee the algorithm doesn't run out of temporary storage. 151 | // 152 | // If you do #2, then the non-quantized algorithm will be used, but the algorithm 153 | // may run out of temporary storage and be unable to pack some rectangles. 154 | 155 | STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem); 156 | // Optionally call this function after init but before doing any packing to 157 | // change the handling of the out-of-temp-memory scenario, described above. 158 | // If you call init again, this will be reset to the default (false). 159 | 160 | 161 | STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic); 162 | // Optionally select which packing heuristic the library should use. Different 163 | // heuristics will produce better/worse results for different data sets. 164 | // If you call init again, this will be reset to the default. 165 | 166 | enum 167 | { 168 | STBRP_HEURISTIC_Skyline_default=0, 169 | STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default, 170 | STBRP_HEURISTIC_Skyline_BF_sortHeight 171 | }; 172 | 173 | 174 | ////////////////////////////////////////////////////////////////////////////// 175 | // 176 | // the details of the following structures don't matter to you, but they must 177 | // be visible so you can handle the memory allocations for them 178 | 179 | struct stbrp_node 180 | { 181 | stbrp_coord x,y; 182 | stbrp_node *next; 183 | }; 184 | 185 | struct stbrp_context 186 | { 187 | int width; 188 | int height; 189 | int align; 190 | int init_mode; 191 | int heuristic; 192 | int num_nodes; 193 | stbrp_node *active_head; 194 | stbrp_node *free_head; 195 | stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' 196 | }; 197 | 198 | #ifdef __cplusplus 199 | } 200 | #endif 201 | 202 | #endif 203 | 204 | ////////////////////////////////////////////////////////////////////////////// 205 | // 206 | // IMPLEMENTATION SECTION 207 | // 208 | 209 | #ifdef STB_RECT_PACK_IMPLEMENTATION 210 | #ifndef STBRP_SORT 211 | #include 212 | #define STBRP_SORT qsort 213 | #endif 214 | 215 | #ifndef STBRP_ASSERT 216 | #include 217 | #define STBRP_ASSERT assert 218 | #endif 219 | 220 | #ifdef _MSC_VER 221 | #define STBRP__NOTUSED(v) (void)(v) 222 | #define STBRP__CDECL __cdecl 223 | #else 224 | #define STBRP__NOTUSED(v) (void)sizeof(v) 225 | #define STBRP__CDECL 226 | #endif 227 | 228 | enum 229 | { 230 | STBRP__INIT_skyline = 1 231 | }; 232 | 233 | STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic) 234 | { 235 | switch (context->init_mode) { 236 | case STBRP__INIT_skyline: 237 | STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight); 238 | context->heuristic = heuristic; 239 | break; 240 | default: 241 | STBRP_ASSERT(0); 242 | } 243 | } 244 | 245 | STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem) 246 | { 247 | if (allow_out_of_mem) 248 | // if it's ok to run out of memory, then don't bother aligning them; 249 | // this gives better packing, but may fail due to OOM (even though 250 | // the rectangles easily fit). @TODO a smarter approach would be to only 251 | // quantize once we've hit OOM, then we could get rid of this parameter. 252 | context->align = 1; 253 | else { 254 | // if it's not ok to run out of memory, then quantize the widths 255 | // so that num_nodes is always enough nodes. 256 | // 257 | // I.e. num_nodes * align >= width 258 | // align >= width / num_nodes 259 | // align = ceil(width/num_nodes) 260 | 261 | context->align = (context->width + context->num_nodes-1) / context->num_nodes; 262 | } 263 | } 264 | 265 | STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes) 266 | { 267 | int i; 268 | 269 | for (i=0; i < num_nodes-1; ++i) 270 | nodes[i].next = &nodes[i+1]; 271 | nodes[i].next = NULL; 272 | context->init_mode = STBRP__INIT_skyline; 273 | context->heuristic = STBRP_HEURISTIC_Skyline_default; 274 | context->free_head = &nodes[0]; 275 | context->active_head = &context->extra[0]; 276 | context->width = width; 277 | context->height = height; 278 | context->num_nodes = num_nodes; 279 | stbrp_setup_allow_out_of_mem(context, 0); 280 | 281 | // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) 282 | context->extra[0].x = 0; 283 | context->extra[0].y = 0; 284 | context->extra[0].next = &context->extra[1]; 285 | context->extra[1].x = (stbrp_coord) width; 286 | context->extra[1].y = (1<<30); 287 | context->extra[1].next = NULL; 288 | } 289 | 290 | // find minimum y position if it starts at x1 291 | static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) 292 | { 293 | stbrp_node *node = first; 294 | int x1 = x0 + width; 295 | int min_y, visited_width, waste_area; 296 | 297 | STBRP__NOTUSED(c); 298 | 299 | STBRP_ASSERT(first->x <= x0); 300 | 301 | #if 0 302 | // skip in case we're past the node 303 | while (node->next->x <= x0) 304 | ++node; 305 | #else 306 | STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency 307 | #endif 308 | 309 | STBRP_ASSERT(node->x <= x0); 310 | 311 | min_y = 0; 312 | waste_area = 0; 313 | visited_width = 0; 314 | while (node->x < x1) { 315 | if (node->y > min_y) { 316 | // raise min_y higher. 317 | // we've accounted for all waste up to min_y, 318 | // but we'll now add more waste for everything we've visted 319 | waste_area += visited_width * (node->y - min_y); 320 | min_y = node->y; 321 | // the first time through, visited_width might be reduced 322 | if (node->x < x0) 323 | visited_width += node->next->x - x0; 324 | else 325 | visited_width += node->next->x - node->x; 326 | } else { 327 | // add waste area 328 | int under_width = node->next->x - node->x; 329 | if (under_width + visited_width > width) 330 | under_width = width - visited_width; 331 | waste_area += under_width * (min_y - node->y); 332 | visited_width += under_width; 333 | } 334 | node = node->next; 335 | } 336 | 337 | *pwaste = waste_area; 338 | return min_y; 339 | } 340 | 341 | typedef struct 342 | { 343 | int x,y; 344 | stbrp_node **prev_link; 345 | } stbrp__findresult; 346 | 347 | static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height) 348 | { 349 | int best_waste = (1<<30), best_x, best_y = (1 << 30); 350 | stbrp__findresult fr; 351 | stbrp_node **prev, *node, *tail, **best = NULL; 352 | 353 | // align to multiple of c->align 354 | width = (width + c->align - 1); 355 | width -= width % c->align; 356 | STBRP_ASSERT(width % c->align == 0); 357 | 358 | // if it can't possibly fit, bail immediately 359 | if (width > c->width || height > c->height) { 360 | fr.prev_link = NULL; 361 | fr.x = fr.y = 0; 362 | return fr; 363 | } 364 | 365 | node = c->active_head; 366 | prev = &c->active_head; 367 | while (node->x + width <= c->width) { 368 | int y,waste; 369 | y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste); 370 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL 371 | // bottom left 372 | if (y < best_y) { 373 | best_y = y; 374 | best = prev; 375 | } 376 | } else { 377 | // best-fit 378 | if (y + height <= c->height) { 379 | // can only use it if it first vertically 380 | if (y < best_y || (y == best_y && waste < best_waste)) { 381 | best_y = y; 382 | best_waste = waste; 383 | best = prev; 384 | } 385 | } 386 | } 387 | prev = &node->next; 388 | node = node->next; 389 | } 390 | 391 | best_x = (best == NULL) ? 0 : (*best)->x; 392 | 393 | // if doing best-fit (BF), we also have to try aligning right edge to each node position 394 | // 395 | // e.g, if fitting 396 | // 397 | // ____________________ 398 | // |____________________| 399 | // 400 | // into 401 | // 402 | // | | 403 | // | ____________| 404 | // |____________| 405 | // 406 | // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned 407 | // 408 | // This makes BF take about 2x the time 409 | 410 | if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) { 411 | tail = c->active_head; 412 | node = c->active_head; 413 | prev = &c->active_head; 414 | // find first node that's admissible 415 | while (tail->x < width) 416 | tail = tail->next; 417 | while (tail) { 418 | int xpos = tail->x - width; 419 | int y,waste; 420 | STBRP_ASSERT(xpos >= 0); 421 | // find the left position that matches this 422 | while (node->next->x <= xpos) { 423 | prev = &node->next; 424 | node = node->next; 425 | } 426 | STBRP_ASSERT(node->next->x > xpos && node->x <= xpos); 427 | y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste); 428 | if (y + height <= c->height) { 429 | if (y <= best_y) { 430 | if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) { 431 | best_x = xpos; 432 | //STBRP_ASSERT(y <= best_y); [DEAR IMGUI] 433 | best_y = y; 434 | best_waste = waste; 435 | best = prev; 436 | } 437 | } 438 | } 439 | tail = tail->next; 440 | } 441 | } 442 | 443 | fr.prev_link = best; 444 | fr.x = best_x; 445 | fr.y = best_y; 446 | return fr; 447 | } 448 | 449 | static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height) 450 | { 451 | // find best position according to heuristic 452 | stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height); 453 | stbrp_node *node, *cur; 454 | 455 | // bail if: 456 | // 1. it failed 457 | // 2. the best node doesn't fit (we don't always check this) 458 | // 3. we're out of memory 459 | if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) { 460 | res.prev_link = NULL; 461 | return res; 462 | } 463 | 464 | // on success, create new node 465 | node = context->free_head; 466 | node->x = (stbrp_coord) res.x; 467 | node->y = (stbrp_coord) (res.y + height); 468 | 469 | context->free_head = node->next; 470 | 471 | // insert the new node into the right starting point, and 472 | // let 'cur' point to the remaining nodes needing to be 473 | // stiched back in 474 | 475 | cur = *res.prev_link; 476 | if (cur->x < res.x) { 477 | // preserve the existing one, so start testing with the next one 478 | stbrp_node *next = cur->next; 479 | cur->next = node; 480 | cur = next; 481 | } else { 482 | *res.prev_link = node; 483 | } 484 | 485 | // from here, traverse cur and free the nodes, until we get to one 486 | // that shouldn't be freed 487 | while (cur->next && cur->next->x <= res.x + width) { 488 | stbrp_node *next = cur->next; 489 | // move the current node to the free list 490 | cur->next = context->free_head; 491 | context->free_head = cur; 492 | cur = next; 493 | } 494 | 495 | // stitch the list back in 496 | node->next = cur; 497 | 498 | if (cur->x < res.x + width) 499 | cur->x = (stbrp_coord) (res.x + width); 500 | 501 | #ifdef _DEBUG 502 | cur = context->active_head; 503 | while (cur->x < context->width) { 504 | STBRP_ASSERT(cur->x < cur->next->x); 505 | cur = cur->next; 506 | } 507 | STBRP_ASSERT(cur->next == NULL); 508 | 509 | { 510 | int count=0; 511 | cur = context->active_head; 512 | while (cur) { 513 | cur = cur->next; 514 | ++count; 515 | } 516 | cur = context->free_head; 517 | while (cur) { 518 | cur = cur->next; 519 | ++count; 520 | } 521 | STBRP_ASSERT(count == context->num_nodes+2); 522 | } 523 | #endif 524 | 525 | return res; 526 | } 527 | 528 | static int STBRP__CDECL rect_height_compare(const void *a, const void *b) 529 | { 530 | const stbrp_rect *p = (const stbrp_rect *) a; 531 | const stbrp_rect *q = (const stbrp_rect *) b; 532 | if (p->h > q->h) 533 | return -1; 534 | if (p->h < q->h) 535 | return 1; 536 | return (p->w > q->w) ? -1 : (p->w < q->w); 537 | } 538 | 539 | static int STBRP__CDECL rect_original_order(const void *a, const void *b) 540 | { 541 | const stbrp_rect *p = (const stbrp_rect *) a; 542 | const stbrp_rect *q = (const stbrp_rect *) b; 543 | return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); 544 | } 545 | 546 | STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects) 547 | { 548 | int i, all_rects_packed = 1; 549 | 550 | // we use the 'was_packed' field internally to allow sorting/unsorting 551 | for (i=0; i < num_rects; ++i) { 552 | rects[i].was_packed = i; 553 | } 554 | 555 | // sort according to heuristic 556 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); 557 | 558 | for (i=0; i < num_rects; ++i) { 559 | if (rects[i].w == 0 || rects[i].h == 0) { 560 | rects[i].x = rects[i].y = 0; // empty rect needs no space 561 | } else { 562 | stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); 563 | if (fr.prev_link) { 564 | rects[i].x = (stbrp_coord) fr.x; 565 | rects[i].y = (stbrp_coord) fr.y; 566 | } else { 567 | rects[i].x = rects[i].y = STBRP__MAXVAL; 568 | } 569 | } 570 | } 571 | 572 | // unsort 573 | STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); 574 | 575 | // set was_packed flags and all_rects_packed status 576 | for (i=0; i < num_rects; ++i) { 577 | rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL); 578 | if (!rects[i].was_packed) 579 | all_rects_packed = 0; 580 | } 581 | 582 | // return the all_rects_packed status 583 | return all_rects_packed; 584 | } 585 | #endif 586 | 587 | /* 588 | ------------------------------------------------------------------------------ 589 | This software is available under 2 licenses -- choose whichever you prefer. 590 | ------------------------------------------------------------------------------ 591 | ALTERNATIVE A - MIT License 592 | Copyright (c) 2017 Sean Barrett 593 | Permission is hereby granted, free of charge, to any person obtaining a copy of 594 | this software and associated documentation files (the "Software"), to deal in 595 | the Software without restriction, including without limitation the rights to 596 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 597 | of the Software, and to permit persons to whom the Software is furnished to do 598 | so, subject to the following conditions: 599 | The above copyright notice and this permission notice shall be included in all 600 | copies or substantial portions of the Software. 601 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 602 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 603 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 604 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 605 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 606 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 607 | SOFTWARE. 608 | ------------------------------------------------------------------------------ 609 | ALTERNATIVE B - Public Domain (www.unlicense.org) 610 | This is free and unencumbered software released into the public domain. 611 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute this 612 | software, either in source code form or as a compiled binary, for any purpose, 613 | commercial or non-commercial, and by any means. 614 | In jurisdictions that recognize copyright laws, the author or authors of this 615 | software dedicate any and all copyright interest in the software to the public 616 | domain. We make this dedication for the benefit of the public at large and to 617 | the detriment of our heirs and successors. We intend this dedication to be an 618 | overt act of relinquishment in perpetuity of all present and future rights to 619 | this software under copyright law. 620 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 621 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 622 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 623 | AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 624 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 625 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 626 | ------------------------------------------------------------------------------ 627 | */ 628 | -------------------------------------------------------------------------------- /json/jsonOps.cpp: -------------------------------------------------------------------------------- 1 | #include "jsonOps.hpp" 2 | 3 | nlohmann::json json::readFromJsonFile(std::wstring fileName) { 4 | nlohmann::json fileContent; 5 | try { 6 | std::wstring currentPath; 7 | currentPath = utils::getExePath().append(fileName); 8 | 9 | std::ifstream f(currentPath); 10 | fileContent = nlohmann::json::parse(f); 11 | 12 | f.close(); 13 | } 14 | catch (nlohmann::json::parse_error& ex) { 15 | return 0; 16 | } 17 | return fileContent; 18 | } 19 | -------------------------------------------------------------------------------- /json/jsonOps.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "json.hpp" 6 | 7 | #include "../util/utilFunctions.hpp" 8 | 9 | namespace json { 10 | inline std::wstring clientDLLFile = L"\\client.dll.json"; 11 | inline std::wstring offsetFile = L"\\offsets.json"; 12 | 13 | nlohmann::json readFromJsonFile(std::wstring fileName); 14 | } 15 | -------------------------------------------------------------------------------- /offset_download.ps1: -------------------------------------------------------------------------------- 1 | Invoke-WebRequest -Uri https://raw.githubusercontent.com/a2x/cs2-dumper/main/generated/offsets.json -OutFile offsets.json 2 | Invoke-WebRequest -Uri https://raw.githubusercontent.com/a2x/cs2-dumper/main/generated/client.dll.json -OutFile client.dll.json -------------------------------------------------------------------------------- /screenshots/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gmh5225/tim_apple/a2f7d420425ca7e95302857236fe7309d2b991f5/screenshots/preview.png -------------------------------------------------------------------------------- /tim_apple.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33712.159 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tim_apple", "tim_apple.vcxproj", "{E6CBDC8B-C819-4A41-85B1-27203F206E29}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|x64 = Debug|x64 11 | Debug|x86 = Debug|x86 12 | Release|x64 = Release|x64 13 | Release|x86 = Release|x86 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Debug|x64.ActiveCfg = Debug|x64 17 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Debug|x64.Build.0 = Debug|x64 18 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Debug|x86.ActiveCfg = Debug|Win32 19 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Debug|x86.Build.0 = Debug|Win32 20 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Release|x64.ActiveCfg = Release|x64 21 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Release|x64.Build.0 = Release|x64 22 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Release|x86.ActiveCfg = Release|Win32 23 | {E6CBDC8B-C819-4A41-85B1-27203F206E29}.Release|x86.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {BA245855-1478-4589-815A-D7EB18E8634B} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /tim_apple.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | Debug 14 | x64 15 | 16 | 17 | Release 18 | x64 19 | 20 | 21 | 22 | 16.0 23 | Win32Proj 24 | {e6cbdc8b-c819-4a41-85b1-27203f206e29} 25 | timapple 26 | 10.0 27 | 28 | 29 | 30 | Application 31 | true 32 | v143 33 | Unicode 34 | 35 | 36 | Application 37 | false 38 | v143 39 | true 40 | Unicode 41 | 42 | 43 | Application 44 | true 45 | v143 46 | Unicode 47 | 48 | 49 | Application 50 | false 51 | v143 52 | true 53 | Unicode 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Level3 76 | true 77 | WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) 78 | true 79 | 80 | 81 | Console 82 | true 83 | 84 | 85 | 86 | 87 | Level3 88 | true 89 | true 90 | true 91 | WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 92 | true 93 | 94 | 95 | Console 96 | true 97 | true 98 | true 99 | 100 | 101 | 102 | 103 | Level3 104 | true 105 | _DEBUG;_CONSOLE;%(PreprocessorDefinitions) 106 | true 107 | 108 | 109 | Console 110 | true 111 | 112 | 113 | 114 | 115 | Level3 116 | true 117 | true 118 | true 119 | NDEBUG;_CONSOLE;%(PreprocessorDefinitions) 120 | true 121 | stdcpp20 122 | MultiThreaded 123 | 124 | 125 | Windows 126 | true 127 | true 128 | true 129 | d3d11.lib;%(AdditionalDependencies) 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | -------------------------------------------------------------------------------- /tim_apple.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /tim_apple.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | true 5 | 6 | -------------------------------------------------------------------------------- /timapple.cpp: -------------------------------------------------------------------------------- 1 | #define WIN32_LEAN_AND_MEAN 2 | 3 | #include 4 | 5 | #include "gui/overlay.hpp" 6 | #include "util/MemMan.hpp" 7 | #include "util/attributes.hpp" 8 | 9 | LRESULT Wndproc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { 10 | if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) { 11 | return 0; 12 | } 13 | switch (msg) { 14 | case WM_SYSCOMMAND: { 15 | if ((wParam & 0xfff0) == SC_KEYMENU) 16 | return 0; 17 | break; 18 | } 19 | 20 | case WM_DESTROY: { 21 | PostQuitMessage(0); 22 | return 0; 23 | } 24 | } 25 | return DefWindowProc(hWnd, msg, wParam, lParam); 26 | } 27 | 28 | 29 | int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { 30 | // Memory and game related vars (used in entry and passed through overlay) 31 | int procId = MemMan.getPid(L"cs2.exe"); 32 | if (procId == 0) exit(-1); 33 | 34 | MemoryManagement::moduleData client; 35 | client.module = MemMan.getModule(procId, L"client.dll"); 36 | client.base = MemMan.getModuleBase(procId, L"client.dll"); 37 | 38 | // Overlay 39 | overlayESP overlayClass; 40 | WNDCLASSEXW windowClass = overlayClass.createWindowClass(hInstance, Wndproc, L"Tim Apple"); 41 | HWND window = overlayClass.createWindow(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)); 42 | 43 | overlayClass.makeFrameIntoClientArea(); 44 | overlayClass.makeDeviceAndSwapChain(); 45 | overlayClass.initWindow(nShowCmd); 46 | overlayClass.renderLoop(client); 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /util/MemMan.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning (disable : 6001 ) 3 | #pragma warning (disable : 4244 ) 4 | 5 | #define WIN32_LEAN_AND_MEAN 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | 12 | class MemoryManagement { 13 | public: 14 | HANDLE proc; 15 | 16 | struct moduleData { 17 | HMODULE module; 18 | DWORD_PTR base; 19 | uintptr_t size; 20 | }; 21 | 22 | 23 | template 24 | T ReadMem(uintptr_t addr) 25 | { 26 | T x; 27 | ReadProcessMemory(proc, (LPBYTE*)addr, &x, sizeof(x), NULL); 28 | return x; 29 | } 30 | 31 | bool ReadRawMem(uintptr_t addr, void* buffer, size_t size) 32 | { 33 | SIZE_T bytesRead; 34 | if (ReadProcessMemory(proc, reinterpret_cast(addr), buffer, size, &bytesRead)) 35 | { 36 | return bytesRead == size; 37 | } 38 | return false; 39 | } 40 | 41 | 42 | template 43 | T WriteMem(uintptr_t addr, T x) 44 | { 45 | WriteProcessMemory(proc, (LPBYTE*)addr, &x, sizeof(x), NULL); 46 | return x; 47 | } 48 | 49 | 50 | HANDLE getProcess(const wchar_t* name) { 51 | HANDLE processID = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 52 | uintptr_t process; 53 | PROCESSENTRY32W processEntry; 54 | processEntry.dwSize = sizeof(processEntry); 55 | 56 | do { 57 | if (!_wcsicmp(processEntry.szExeFile, name)) { 58 | process = processEntry.th32ProcessID; 59 | CloseHandle(processID); 60 | proc = OpenProcess(PROCESS_ALL_ACCESS, false, process); 61 | } 62 | } while (Process32NextW(processID, &processEntry)); 63 | 64 | return proc; 65 | }; 66 | 67 | 68 | uintptr_t getPid(const wchar_t* name) { 69 | HANDLE processID = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 70 | uintptr_t process; 71 | PROCESSENTRY32W processEntry; 72 | processEntry.dwSize = sizeof(processEntry); 73 | 74 | do { 75 | if (!_wcsicmp(processEntry.szExeFile, name)) { 76 | process = processEntry.th32ProcessID; 77 | CloseHandle(processID); 78 | proc = OpenProcess(PROCESS_ALL_ACCESS, false, process); 79 | } 80 | } while (Process32NextW(processID, &processEntry)); 81 | 82 | return process; 83 | } 84 | 85 | 86 | HMODULE getModule(uintptr_t pid, const wchar_t* name) { 87 | HANDLE module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid); 88 | MODULEENTRY32W moduleEntry; 89 | moduleEntry.dwSize = sizeof(moduleEntry); 90 | 91 | do { 92 | if (!_wcsicmp(moduleEntry.szModule, name)) { 93 | CloseHandle(module); 94 | return moduleEntry.hModule; 95 | } 96 | } while (Module32NextW(module, &moduleEntry)); 97 | 98 | return 0; 99 | } 100 | 101 | 102 | DWORD_PTR getModuleBase(DWORD pid, LPCTSTR name) { 103 | DWORD_PTR dwBase = 0; 104 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid); 105 | MODULEENTRY32 ModuleEntry32; 106 | ModuleEntry32.dwSize = sizeof(MODULEENTRY32); 107 | 108 | if (Module32First(hSnapshot, &ModuleEntry32)) { 109 | do { 110 | if (_tcsicmp(ModuleEntry32.szModule, name) == 0) { 111 | dwBase = (DWORD_PTR)ModuleEntry32.modBaseAddr; 112 | } 113 | } while (Module32Next(hSnapshot, &ModuleEntry32)); 114 | }; 115 | 116 | return dwBase; 117 | } 118 | 119 | 120 | DWORD getModuleSize(DWORD pid, LPCTSTR name) { 121 | DWORD dwSize = 0; 122 | 123 | do { 124 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid); 125 | if (hSnapshot == INVALID_HANDLE_VALUE) { continue; } 126 | 127 | MODULEENTRY32 ModuleEntry32; 128 | ModuleEntry32.dwSize = sizeof(MODULEENTRY32); 129 | 130 | if (Module32First(hSnapshot, &ModuleEntry32)) { 131 | do { 132 | if (_tcsicmp(ModuleEntry32.szModule, name) == 0) { 133 | dwSize = ModuleEntry32.modBaseSize; 134 | break; 135 | } 136 | } while (Module32Next(hSnapshot, &ModuleEntry32)); 137 | } 138 | 139 | CloseHandle(hSnapshot); 140 | } while (!dwSize); 141 | 142 | return dwSize; 143 | } 144 | }; -------------------------------------------------------------------------------- /util/Vectors.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning (disable: 4172) 3 | 4 | 5 | #define WIN32_LEAN_AND_MEAN 6 | 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | 13 | struct view_matrix_t { 14 | float* operator[ ](int index) { 15 | return matrix[index]; 16 | } 17 | float matrix[4][4]; 18 | }; 19 | 20 | 21 | struct Vector2 { 22 | float x, y; 23 | }; 24 | 25 | 26 | struct Vector3 { 27 | constexpr Vector3( 28 | const float x = 0.f, 29 | const float y = 0.f, 30 | const float z = 0.f) noexcept : 31 | x(x), y(y), z(z) { } 32 | 33 | constexpr const Vector3& operator-(const Vector3& other) const noexcept 34 | { 35 | return Vector3{ x - other.x, y - other.y, z - other.z }; 36 | } 37 | 38 | constexpr const Vector3& operator+(const Vector3& other) const noexcept 39 | { 40 | return Vector3{ x + other.x, y + other.y, z + other.z }; 41 | } 42 | 43 | constexpr const Vector3& operator/(const float factor) const noexcept 44 | { 45 | return Vector3{ x / factor, y / factor, z / factor }; 46 | } 47 | 48 | constexpr const Vector3& operator*(const float factor) const noexcept 49 | { 50 | return Vector3{ x * factor, y * factor, z * factor }; 51 | } 52 | 53 | constexpr const Vector3& ToAngle() const noexcept 54 | { 55 | return Vector3{ 56 | std::atan2(-z, std::hypot(x, y)) * (180.0f / std::numbers::pi_v), 57 | std::atan2(y, x) * (180.0f / std::numbers::pi_v), 58 | 0.0f 59 | }; 60 | } 61 | 62 | 63 | Vector3 worldToScreen(view_matrix_t matrix) { 64 | float _x = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z + matrix[0][3]; 65 | float _y = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z + matrix[1][3]; 66 | 67 | float w = matrix[3][0] * x + matrix[3][1] * y + matrix[3][2] * z + matrix[3][3]; 68 | 69 | float inv_w = 1.f / w; 70 | _x *= inv_w; 71 | _y *= inv_w; 72 | 73 | float screen_x = GetSystemMetrics(SM_CXSCREEN) * 0.5f; 74 | float screen_y = GetSystemMetrics(SM_CYSCREEN) * 0.5f; 75 | 76 | screen_x += 0.5f * _x * GetSystemMetrics(SM_CXSCREEN) + 0.5f; 77 | screen_y -= 0.5f * _y * GetSystemMetrics(SM_CYSCREEN) + 0.5f; 78 | 79 | return { screen_x, screen_y, w }; 80 | } 81 | 82 | constexpr const bool IsZero() const noexcept 83 | { 84 | return x == 0.f && y == 0.f && z == 0.f; 85 | } 86 | 87 | float x, y, z; 88 | }; 89 | 90 | 91 | inline constexpr Vector3 CalculateAngle( 92 | const Vector3& localPosition, 93 | const Vector3& enemyPosition, 94 | const Vector3& viewAngles) noexcept 95 | { 96 | return ((enemyPosition - localPosition).ToAngle() - viewAngles); 97 | }; 98 | 99 | 100 | inline Vector3 clampAngles(Vector3 angles) { 101 | if (angles.x > 89.0f && angles.x <= 180.0f){ 102 | angles.x = 89.0f; 103 | } 104 | 105 | if (angles.x > 180.0f){ 106 | angles.x -= 360.0f; 107 | } 108 | 109 | if (angles.x < -89.0f){ 110 | angles.x = -89.0f; 111 | } 112 | 113 | if (angles.y > 180.0f){ 114 | angles.y -= 360.0f; 115 | } 116 | 117 | if (angles.y < -180.0f){ 118 | angles.y += 360.0f; 119 | } 120 | angles.z = 0; 121 | 122 | return angles; 123 | }; 124 | 125 | 126 | inline Vector3 normalizeAngles(Vector3 angle) { 127 | while (angle.x > 180.f) 128 | angle.x -= 360.0f; 129 | 130 | while (angle.x < -180.0f) 131 | angle.x += 360.0f; 132 | 133 | while (angle.y > 180.0f) 134 | angle.y -= 360.0f; 135 | 136 | while (angle.y < -180.0f) 137 | angle.y += 360.0f; 138 | 139 | return angle; 140 | }; 141 | 142 | 143 | 144 | inline Vector3 calculateBestAngle(Vector3 angle,float configFov) { 145 | Vector3 newAngle; 146 | 147 | float calcFov = std::hypot(angle.x, angle.y); 148 | float fov = configFov; 149 | 150 | if (calcFov < fov) { 151 | fov = calcFov; 152 | newAngle = angle; 153 | } 154 | return newAngle; 155 | } -------------------------------------------------------------------------------- /util/attributes.cpp: -------------------------------------------------------------------------------- 1 | #include "attributes.hpp" 2 | 3 | 4 | uintptr_t Classes::getListEntry(int id) { 5 | listEntry = MemMan.ReadMem(entity_list + (8 * (id & 0x7FFF) >> 9) + 16); 6 | return listEntry; 7 | } 8 | 9 | uintptr_t Classes::getCCSPlayerControllerBase(int id) { 10 | CCSPlayerController_ = MemMan.ReadMem(listEntry + 120 * (id & 0x1FF)); 11 | return CCSPlayerController_; 12 | } 13 | 14 | 15 | 16 | 17 | int CCSPlayerController::getPawnHealth() { 18 | pawnHealth = MemMan.ReadMem(value + clientDLL::CCSPlayerController_["m_iPawnHealth"]["value"]); 19 | return pawnHealth; 20 | } 21 | 22 | std::uint32_t CCSPlayerController::getC_CSPlayerPawn() { 23 | C_CSPlayerPawn_ = MemMan.ReadMem(value + clientDLL::CCSPlayerController_["m_hPlayerPawn"]["value"]); 24 | return C_CSPlayerPawn_; 25 | } 26 | 27 | uintptr_t CCSPlayerController::getPawnTeam() { 28 | pawnTeam = MemMan.ReadMem(value + clientDLL::C_BaseEntity_["m_iTeamNum"]["value"]); 29 | return pawnTeam; 30 | } 31 | 32 | std::string CCSPlayerController::getPawnName() { 33 | pawnNameAddress = MemMan.ReadMem(value + clientDLL::CCSPlayerController_["m_sSanitizedPlayerName"]["value"]); 34 | if (pawnNameAddress) { 35 | char buf[256] = {}; 36 | MemMan.ReadRawMem(pawnNameAddress, buf, sizeof(buf)); 37 | pawnName = std::string(buf); 38 | } 39 | else { 40 | pawnName = "Unknown"; 41 | } 42 | return pawnName; 43 | } 44 | 45 | 46 | 47 | 48 | uintptr_t C_CSPlayerPawn::getPlayerPawn() { 49 | playerPawn = MemMan.ReadMem(listEntry + 120 * (value & 0x1FF)); 50 | return playerPawn; 51 | } 52 | 53 | uintptr_t C_CSPlayerPawn::getPlayerPawnByCrossHairID(int crossHairEntity) { 54 | uintptr_t crosshairEntityEntry = MemMan.ReadMem(entity_list + static_cast(0x8) * (crossHairEntity >> 9) + 16); 55 | playerPawn = MemMan.ReadMem(crosshairEntityEntry + 120 * (crossHairEntity & 0x1FF)); 56 | return playerPawn; 57 | } 58 | 59 | Vector3 C_CSPlayerPawn::getOrigin() { 60 | origin = MemMan.ReadMem(playerPawn + clientDLL::C_BasePlayerPawn_["m_vOldOrigin"]["value"]); 61 | return origin; 62 | } 63 | 64 | Vector3 C_CSPlayerPawn::getCameraPos() { 65 | cameraPos = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_vecLastClipCameraPos"]["value"]); 66 | return cameraPos; 67 | } 68 | 69 | uintptr_t C_CSPlayerPawn::getCGameSceneNode() { 70 | CGameSceneNode = MemMan.ReadMem(playerPawn + clientDLL::C_BaseEntity_["m_pGameSceneNode"]["value"]); 71 | return CGameSceneNode; 72 | } 73 | 74 | Vector3 C_CSPlayerPawn::getViewAngles() { 75 | viewAngles = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_angEyeAngles"]["value"]); 76 | return viewAngles; 77 | } 78 | 79 | Vector3 C_CSPlayerPawn::getPosition() { 80 | position = MemMan.ReadMem(playerPawn + clientDLL::CBaseAnimGraph_["m_vLastSlopeCheckPos"]["value"]); 81 | return position; 82 | } 83 | 84 | uint16_t C_CSPlayerPawn::getWeaponID() { 85 | C_CSWeaponBase = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_pClippingWeapon"]["value"]); 86 | weaponID = MemMan.ReadMem(C_CSWeaponBase + clientDLL::C_EconItemView_["m_iItemDefinitionIndex"]["value"] + clientDLL::C_AttributeContainer_["m_Item"]["value"] + clientDLL::C_EconEntity_["m_AttributeManager"]["value"]); 87 | return weaponID; 88 | } 89 | 90 | int C_CSPlayerPawn::getPawnHealth() { 91 | pawnHealth = MemMan.ReadMem(playerPawn + clientDLL::C_BaseEntity_["m_iHealth"]["value"]); 92 | return pawnHealth; 93 | } 94 | 95 | uintptr_t C_CSPlayerPawn::getPawnTeam() { 96 | pawnTeam = MemMan.ReadMem(value + clientDLL::C_BaseEntity_["m_iTeamNum"]["value"]); 97 | return pawnTeam; 98 | } 99 | 100 | int C_CSPlayerPawn::getEntitySpotted() { 101 | spotted = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_entitySpottedState"]["value"] + clientDLL::EntitySpottedState_t_["m_bSpottedByMask"]["value"]); 102 | return spotted; 103 | } 104 | 105 | 106 | 107 | 108 | uintptr_t LocalPlayer::getPlayerPawn() { 109 | playerPawn = MemMan.ReadMem(moduleData.base + offsets::clientDLL["dwLocalPlayerPawn"]["value"]); 110 | return playerPawn; 111 | } 112 | 113 | uintptr_t LocalPlayer::getTeam() { 114 | team = MemMan.ReadMem(localPlayer + clientDLL::C_BaseEntity_["m_iTeamNum"]["value"]); 115 | return team; 116 | } 117 | 118 | Vector3 LocalPlayer::getCameraPos() { 119 | cameraPos = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_vecLastClipCameraPos"]["value"]); 120 | return cameraPos; 121 | } 122 | 123 | Vector3 LocalPlayer::getViewAngles() { 124 | viewAngles = MemMan.ReadMem(playerPawn + clientDLL::C_BasePlayerPawn_["v_angle"]["value"]); 125 | return viewAngles; 126 | } 127 | 128 | Vector3 LocalPlayer::getPosition() { 129 | position = MemMan.ReadMem(playerPawn + clientDLL::CBaseAnimGraph_["m_vLastSlopeCheckPos"]["value"]); 130 | return position; 131 | } 132 | 133 | Vector3 LocalPlayer::getOrigin() { 134 | origin = MemMan.ReadMem(playerPawn + clientDLL::C_BasePlayerPawn_["m_vOldOrigin"]["value"]); 135 | return origin; 136 | } 137 | 138 | int LocalPlayer::getFlags() { 139 | flags = MemMan.ReadMem(playerPawn + clientDLL::C_BaseEntity_["m_fFlags"]["value"]); 140 | return flags; 141 | } 142 | 143 | C_UTL_VECTOR LocalPlayer::getAimPunchCache() { 144 | aimPunchCache = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawn_["m_aimPunchCache"]["value"]); 145 | return aimPunchCache; 146 | } 147 | 148 | Vector2 LocalPlayer::getAimPunchAngle() { 149 | aimPunchAngle = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawn_["m_aimPunchAngle"]["value"]); 150 | return aimPunchAngle; 151 | } 152 | 153 | int LocalPlayer::getShotsFired() { 154 | shotsFired = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_iShotsFired"]["value"]); 155 | return shotsFired; 156 | } 157 | 158 | void LocalPlayer::noFlash() { 159 | MemMan.WriteMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_flFlashDuration"]["value"], 0.f); 160 | } 161 | 162 | int LocalPlayer::getEntitySpotted() { 163 | spotted = MemMan.ReadMem(playerPawn + clientDLL::C_CSPlayerPawnBase_["m_entitySpottedState"]["value"] + clientDLL::EntitySpottedState_t_["m_bSpottedByMask"]["value"]); 164 | return spotted; 165 | } 166 | 167 | 168 | 169 | uintptr_t CGameSceneNode::getBoneArray() { 170 | boneArray = MemMan.ReadMem(value + clientDLL::CSkeletonInstance_["m_modelState"]["value"] + clientDLL::CGameSceneNode_["m_vecOrigin"]["value"]); 171 | return boneArray; 172 | } 173 | 174 | 175 | 176 | 177 | bool SharedFunctions::spottedCheck(C_CSPlayerPawn C_CSPlayerPawn, LocalPlayer localPlayer) { 178 | if (C_CSPlayerPawn.getEntitySpotted() & (1 << (localPlayer.playerPawn)) || localPlayer.getEntitySpotted() & (1 << (C_CSPlayerPawn.playerPawn))) return 1; 179 | return 0; 180 | } 181 | -------------------------------------------------------------------------------- /util/attributes.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning (disable: 26495) 3 | 4 | #include 5 | #include 6 | 7 | #include "Vectors.h" 8 | #include "MemMan.hpp" 9 | 10 | #include "../json/jsonOps.hpp" 11 | 12 | struct C_UTL_VECTOR 13 | { 14 | DWORD_PTR count = 0; 15 | DWORD_PTR data = 0; 16 | }; 17 | 18 | 19 | inline MemoryManagement MemMan; 20 | 21 | namespace clientDLL { 22 | inline nlohmann::json clientDLLOffsets = json::readFromJsonFile(json::clientDLLFile); 23 | 24 | inline nlohmann::json C_BaseEntity_ = clientDLLOffsets["C_BaseEntity"]["data"]; 25 | inline nlohmann::json CCSPlayerController_ = clientDLLOffsets["CCSPlayerController"]["data"]; 26 | inline nlohmann::json C_BasePlayerPawn_ = clientDLLOffsets["C_BasePlayerPawn"]["data"]; 27 | inline nlohmann::json C_CSPlayerPawn_ = clientDLLOffsets["C_CSPlayerPawn"]["data"]; 28 | inline nlohmann::json C_CSPlayerPawnBase_ = clientDLLOffsets["C_CSPlayerPawnBase"]["data"]; 29 | inline nlohmann::json CBaseAnimGraph_ = clientDLLOffsets["CBaseAnimGraph"]["data"]; 30 | inline nlohmann::json C_EconItemView_ = clientDLLOffsets["C_EconItemView"]["data"]; 31 | inline nlohmann::json C_AttributeContainer_ = clientDLLOffsets["C_AttributeContainer"]["data"]; 32 | inline nlohmann::json C_EconEntity_ = clientDLLOffsets["C_EconEntity"]["data"]; 33 | inline nlohmann::json CSkeletonInstance_ = clientDLLOffsets["CSkeletonInstance"]["data"]; 34 | inline nlohmann::json CGameSceneNode_ = clientDLLOffsets["CGameSceneNode"]["data"]; 35 | inline nlohmann::json EntitySpottedState_t_ = clientDLLOffsets["EntitySpottedState_t"]["data"]; 36 | }; 37 | 38 | 39 | namespace offsets { 40 | inline nlohmann::json clientDLL = json::readFromJsonFile(json::offsetFile)["client_dll"]["data"]; 41 | }; 42 | 43 | 44 | class Classes { 45 | public: 46 | MemoryManagement::moduleData moduleData; 47 | uintptr_t entity_list; 48 | 49 | Classes(MemoryManagement::moduleData module) { 50 | moduleData = module; 51 | entity_list = MemMan.ReadMem(moduleData.base + offsets::clientDLL["dwEntityList"]["value"]); 52 | } 53 | 54 | uintptr_t listEntry; 55 | uintptr_t getListEntry(int id); 56 | 57 | // CCSPlayerController 58 | uintptr_t CCSPlayerController_; 59 | uintptr_t getCCSPlayerControllerBase(int id); 60 | }; 61 | 62 | 63 | class CCSPlayerController{ 64 | public: 65 | uintptr_t value; 66 | 67 | CCSPlayerController(uintptr_t playerController) { 68 | value = playerController; 69 | } 70 | 71 | int pawnHealth; 72 | int getPawnHealth(); 73 | 74 | uintptr_t pawnTeam; 75 | uintptr_t getPawnTeam(); 76 | 77 | uintptr_t pawnNameAddress; 78 | std::string pawnName; 79 | std::string getPawnName(); 80 | 81 | // C_CSPlayerPawn 82 | std::uint32_t C_CSPlayerPawn_; 83 | std::uint32_t getC_CSPlayerPawn(); 84 | }; 85 | 86 | 87 | class C_CSPlayerPawn { 88 | public: 89 | std::uint32_t value; 90 | 91 | uintptr_t entity_list; 92 | uintptr_t listEntry; 93 | uintptr_t moduleBase; 94 | 95 | C_CSPlayerPawn(uintptr_t base) { 96 | moduleBase = base; 97 | entity_list = MemMan.ReadMem(base + offsets::clientDLL["dwEntityList"]["value"]); 98 | listEntry = MemMan.ReadMem(entity_list + static_cast(0x8) * ((value & 0x7FFF) >> 9) + 16); 99 | } 100 | 101 | uintptr_t playerPawn; 102 | uintptr_t getPlayerPawn(); 103 | uintptr_t getPlayerPawnByCrossHairID(int crossHairEntity); 104 | 105 | Vector3 origin; 106 | Vector3 getOrigin(); 107 | 108 | Vector3 cameraPos; 109 | Vector3 getCameraPos(); 110 | 111 | Vector3 viewAngles; 112 | Vector3 getViewAngles(); 113 | 114 | Vector3 position; 115 | Vector3 getPosition(); 116 | 117 | int pawnHealth; 118 | int getPawnHealth(); 119 | 120 | uintptr_t pawnTeam; 121 | uintptr_t getPawnTeam(); 122 | 123 | 124 | /* 125 | TODO: Define classes to properly get weapon data 126 | C_CSWeaponBase (look at offsets for inheritance) 127 | uint16_t getC_CSWeaponBase(); 128 | uint16_t C_CSWeaponBase; 129 | */ 130 | uint64_t C_CSWeaponBase; 131 | uint16_t weaponID; 132 | uint16_t getWeaponID(); 133 | 134 | int spotted; 135 | int getEntitySpotted(); 136 | 137 | // CGameSceneNode 138 | uintptr_t CGameSceneNode; 139 | uintptr_t getCGameSceneNode(); 140 | 141 | }; 142 | 143 | class CGameSceneNode { 144 | public: 145 | uintptr_t value; 146 | 147 | uintptr_t boneArray; 148 | uintptr_t getBoneArray(); 149 | }; 150 | 151 | 152 | class LocalPlayer { 153 | public: 154 | MemoryManagement::moduleData moduleData; 155 | uintptr_t localPlayer; 156 | 157 | LocalPlayer(MemoryManagement::moduleData module) { 158 | moduleData = module; 159 | localPlayer = MemMan.ReadMem(moduleData.base + offsets::clientDLL["dwLocalPlayerController"]["value"]); 160 | } 161 | 162 | uintptr_t playerPawn; 163 | uintptr_t getPlayerPawn(); 164 | 165 | uintptr_t team; 166 | uintptr_t getTeam(); 167 | 168 | Vector3 cameraPos; 169 | Vector3 getCameraPos(); 170 | 171 | Vector3 origin; 172 | Vector3 getOrigin(); 173 | 174 | Vector3 viewAngles; 175 | Vector3 getViewAngles(); 176 | 177 | Vector3 position; 178 | Vector3 getPosition(); 179 | 180 | int flags; 181 | int getFlags(); 182 | 183 | C_UTL_VECTOR aimPunchCache; 184 | C_UTL_VECTOR getAimPunchCache(); 185 | 186 | Vector2 aimPunchAngle; 187 | Vector2 getAimPunchAngle(); 188 | 189 | int shotsFired; 190 | int getShotsFired(); 191 | 192 | void noFlash(); 193 | 194 | int spotted; 195 | int getEntitySpotted(); 196 | }; 197 | 198 | 199 | // This is unrelated to all the other classes, but this is the most convenient way to share functions between features 200 | class SharedFunctions { 201 | public: 202 | static bool spottedCheck(C_CSPlayerPawn C_CSPlayerPawn, LocalPlayer localPlayer); 203 | }; -------------------------------------------------------------------------------- /util/config.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | struct espConfig { 8 | bool state = false; 9 | bool checkSpotted; 10 | 11 | bool boundBox; 12 | float colours[3] = { 1.f,1.f,1.f }; 13 | float width = 2.5f; 14 | 15 | bool isPawnName; 16 | std::string pawnName; 17 | 18 | bool isPawnGun; 19 | std::string pawnGun; 20 | 21 | bool isHealthBar; 22 | bool hpCounter; 23 | float health[3]; 24 | 25 | bool skeleton; 26 | float skeletonColours[3] = { 1.f,1.f,1.f }; 27 | 28 | bool snapLines; 29 | 30 | bool distance; 31 | }; 32 | inline espConfig espConf = {}; 33 | 34 | 35 | struct aimConfig { 36 | bool state = false; 37 | bool checkSpotted; 38 | float smoothing = 1.f; 39 | 40 | float fov = 2; 41 | bool fovCircle; 42 | 43 | int bone; 44 | int boneSelect = 0; 45 | std::vector bones = { "Head", "Neck","Chest", "Crotch"}; 46 | std::map boneMap = { {"Head",6},{"Neck",5},{"Chest",4},{"Crotch",0}}; 47 | 48 | bool isHot; 49 | int hotSelect = 0; 50 | int hot; 51 | std::vector hotKey = {"Shift","Left mouse key","Alt"}; 52 | std::map hotKeyMap = { {"Shift",VK_SHIFT},{"Left mouse key",VK_LBUTTON}, {"Alt",VK_MENU}}; 53 | 54 | bool rcs; 55 | }; 56 | inline aimConfig aimConf; 57 | 58 | 59 | struct miscConfig{ 60 | bool bunnyHop; 61 | bool flash; 62 | 63 | bool trigger; 64 | bool isHot; 65 | int hotSelect = 0; 66 | int hot; 67 | std::vector hotKey = { "Shift","Left mouse key","Alt" }; 68 | std::map hotKeyMap = { {"Shift",VK_SHIFT},{"Left mouse key",VK_LBUTTON}, {"Alt",VK_MENU} }; 69 | }; 70 | inline miscConfig miscConf; 71 | 72 | 73 | enum bones : int { 74 | head = 6, 75 | neck = 5, 76 | chest = 4, 77 | shoulderRight = 8, 78 | shoulderLeft = 13, 79 | elbowRight = 9, 80 | elbowLeft = 14, 81 | handRight = 11, 82 | handLeft = 16, 83 | crotch = 0, 84 | kneeRight = 23, 85 | kneeLeft = 26, 86 | ankleRight = 24, 87 | ankleLeft = 27, 88 | }; 89 | 90 | 91 | inline namespace boneGroups { 92 | inline std::vector mid = {bones::head,bones::neck,bones::chest,bones::crotch}; 93 | inline std::vector leftArm = { bones::neck,bones::shoulderLeft,bones::elbowLeft,bones::handLeft}; 94 | inline std::vector righttArm = { bones::neck,bones::shoulderRight,bones::elbowRight,bones::handRight }; 95 | inline std::vector leftLeg = {bones::crotch,bones::kneeLeft,bones::ankleLeft}; 96 | inline std::vector rightLeg = { bones::crotch,bones::kneeRight,bones::ankleRight}; 97 | inline std::vector> allGroups = {mid,leftArm,righttArm,leftLeg,rightLeg}; 98 | }; -------------------------------------------------------------------------------- /util/utilFunctions.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "Vectors.h" 6 | 7 | inline namespace utils { 8 | // https://www.unknowncheats.me/forum/dayz-sa/129893-calculate-distance-meters.html 9 | // https://www.unknowncheats.me/forum/general-programming-and-reversing/478087-calculate-size-esp-boxes-based-distance.html 10 | inline float getDistance(Vector3 from, Vector3 to) { 11 | return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2) + pow(to.z - from.z, 2)); 12 | }; 13 | 14 | inline std::wstring getExePath() { 15 | TCHAR buffer[MAX_PATH] = { 0 }; 16 | GetModuleFileName(NULL, buffer, MAX_PATH); 17 | std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/"); 18 | return std::wstring(buffer).substr(0, pos); 19 | } 20 | } -------------------------------------------------------------------------------- /util/weaponInfo.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | enum ItemDefinitionIndex { 4 | weapon_deagle = 1, 5 | weapon_elite = 2, 6 | weapon_fiveseven = 3, 7 | weapon_glock = 4, 8 | weapon_ak47 = 7, 9 | weapon_aug = 8, 10 | weapon_awp = 9, 11 | weapon_famas = 10, 12 | weapon_g3sg1 = 11, 13 | weapon_galilar = 13, 14 | weapon_m249 = 14, 15 | weapon_m4a1 = 16, 16 | weapon_mac10 = 17, 17 | weapon_p90 = 19, 18 | weapon_ump = 24, 19 | weapon_xm1014 = 25, 20 | weapon_bizon = 26, 21 | weapon_mag7 = 27, 22 | weapon_negev = 28, 23 | weapon_sawedoff = 29, 24 | weapon_tec9 = 30, 25 | weapon_taser = 31, 26 | weapon_hkp2000 = 32, 27 | weapon_mp7 = 33, 28 | weapon_mp9 = 34, 29 | weapon_nova = 35, 30 | weapon_p250 = 36, 31 | weapon_scar20 = 38, 32 | weapon_sg556 = 39, 33 | weapon_ssg08 = 40, 34 | weapon_knife = 42, 35 | weapon_flashbang = 43, 36 | weapon_hegrenade = 44, 37 | weapon_smokegrenade = 45, 38 | weapon_molotov = 46, 39 | weapon_decoy = 47, 40 | weapon_incgrenade = 48, 41 | weapon_c4 = 49, 42 | weapon_knife_t = 59, 43 | weapon_m4a1_silencer = 60, 44 | weapon_usp_silencer = 61, 45 | weapon_cz75a = 63, 46 | weapon_revolver = 64, 47 | weapon_bayonet = 500, 48 | weapon_knife_flip = 505, 49 | weapon_knife_gut = 506, 50 | weapon_knife_karambit = 507, 51 | weapon_knife_m9_bayonet = 508, 52 | weapon_knife_tactical = 509, 53 | weapon_knife_falchion = 512, 54 | weapon_knife_survival_bowie = 514, 55 | weapon_knife_butterfly = 515, 56 | weapon_knife_push = 516 57 | }; 58 | 59 | inline const char* getWeaponFromID(uint16_t id) { 60 | switch (id) { 61 | case weapon_deagle: return "Desert Eagle"; 62 | case weapon_elite: return "Dual-Elites"; 63 | case weapon_fiveseven: return "Five-Seven"; 64 | case weapon_glock: return "Glock"; 65 | case weapon_ak47: return "AK-47"; 66 | case weapon_aug: return "AUG"; 67 | case weapon_awp: return "AWP"; 68 | case weapon_famas: return "Famas"; 69 | case weapon_g3sg1: return "G3SG1"; 70 | case weapon_galilar: return "Galil"; 71 | case weapon_m249: return "M249"; 72 | case weapon_m4a1: return "M4A4"; 73 | case weapon_mac10: return "MAC-10"; 74 | case weapon_p90: return "P90"; 75 | case weapon_ump: return "UMP"; 76 | case weapon_xm1014: return "XM1014"; 77 | case weapon_bizon: return "PP-Bizon"; 78 | case weapon_mag7: return "Mag7"; 79 | case weapon_negev: return "Negev"; 80 | case weapon_sawedoff: return "Sawed-off"; 81 | case weapon_tec9: return "Tec9"; 82 | case weapon_taser: return "Zeus"; 83 | case weapon_hkp2000: return "P2000"; 84 | case weapon_mp7: return "MP7"; 85 | case weapon_mp9: return "MP9"; 86 | case weapon_nova: return "Nova"; 87 | case weapon_p250: return "P-250"; 88 | case weapon_scar20: return "Scar20"; 89 | case weapon_sg556: return "SG556"; 90 | case weapon_ssg08: return "SSG-08"; 91 | case weapon_flashbang: return "Flashbang"; 92 | case weapon_hegrenade: return "HE Granade"; 93 | case weapon_smokegrenade: return "Smoke"; 94 | case weapon_molotov: return "Molotov"; 95 | case weapon_decoy: return "Decoy"; 96 | case weapon_incgrenade: return "Molotov"; 97 | case weapon_c4: return "C4"; 98 | case weapon_m4a1_silencer: return "M4A1-S"; 99 | case weapon_usp_silencer: return "USP-S"; 100 | case weapon_cz75a: return "CZ-75a"; 101 | case weapon_revolver: return "Revolver"; 102 | case weapon_bayonet: 103 | case weapon_knife: 104 | case weapon_knife_t: 105 | case weapon_knife_flip: 106 | case weapon_knife_gut: 107 | case weapon_knife_karambit: 108 | case weapon_knife_m9_bayonet: 109 | case weapon_knife_tactical: 110 | case weapon_knife_falchion: 111 | case weapon_knife_survival_bowie: 112 | case weapon_knife_butterfly: 113 | case weapon_knife_push: 114 | return "Knife"; 115 | default: 116 | return "Unknown"; 117 | } 118 | } --------------------------------------------------------------------------------