From 20e7a995161dfc055e20056e4c30d8f67a9db505 Mon Sep 17 00:00:00 2001 From: jerrrrycho Date: Sat, 4 Jul 2026 05:22:52 +0200 Subject: [PATCH] reformat: use auto on certain types --- Console.cpp | 6 +- Console/PoKeys55.cpp | 4 +- EU07.cpp | 14 +- McZapkie/Mover.cpp | 162 ++--- McZapkie/Oerlikon_ESt.cpp | 8 +- McZapkie/hamulce.cpp | 44 +- application/application.cpp | 38 +- application/drivermode.cpp | 6 +- application/driveruilayer.cpp | 2 +- application/driveruipanels.cpp | 38 +- application/editormode.cpp | 24 +- application/editoruilayer.cpp | 2 +- application/editoruipanels.cpp | 10 +- application/scenarioloaderuilayer.cpp | 8 +- application/uilayer.cpp | 20 +- audio/audio.cpp | 6 +- audio/audiorenderer.cpp | 4 +- audio/sound.cpp | 12 +- environment/moon.cpp | 40 +- environment/sun.cpp | 34 +- gl/buffer.cpp | 2 +- gl/fence.cpp | 2 +- gl/framebuffer.cpp | 4 +- gl/pbo.cpp | 4 +- gl/shader.cpp | 14 +- imgui/ImGuizmo.cpp | 156 ++--- imgui/imgui.cpp | 748 ++++++++++++----------- imgui/imgui.h | 30 +- imgui/imgui_demo.cpp | 153 ++--- imgui/imgui_draw.cpp | 120 ++-- imgui/imgui_impl_glfw.cpp | 6 +- imgui/imgui_impl_opengl2.cpp | 12 +- imgui/imgui_impl_opengl3.cpp | 50 +- imgui/imgui_internal.h | 53 +- imgui/imgui_widgets.cpp | 684 +++++++++++---------- imgui/imstb_rectpack.h | 16 +- imgui/imstb_truetype.h | 350 +++++------ input/command.cpp | 10 +- input/drivermouseinput.cpp | 4 +- input/keyboardinput.cpp | 2 +- input/messaging.cpp | 18 +- input/zmq_input.cpp | 4 +- launcher/deferred_image.h | 2 +- launcher/keymapper.cpp | 6 +- launcher/launcheruilayer.cpp | 2 +- launcher/scenery_list.cpp | 26 +- launcher/scenery_scanner.cpp | 2 +- launcher/textures_scanner.cpp | 8 +- launcher/vehicle_picker.cpp | 16 +- model/AnimModel.cpp | 4 +- model/MdlMngr.cpp | 10 +- model/Model3d.cpp | 44 +- model/Texture.cpp | 32 +- network/backend/asio.cpp | 14 +- network/manager.cpp | 10 +- network/message.cpp | 6 +- network/network.cpp | 15 +- rendering/flip-s3tc.h | 6 +- rendering/frustum.cpp | 2 +- rendering/geometrybank.cpp | 6 +- rendering/lightarray.cpp | 2 +- rendering/opengl33particles.cpp | 2 +- rendering/opengl33precipitation.cpp | 6 +- rendering/opengl33renderer.cpp | 40 +- rendering/openglgeometrybank.cpp | 10 +- rendering/openglgeometrybank.h | 2 +- rendering/openglprecipitation.cpp | 6 +- rendering/openglrenderer.cpp | 14 +- rendering/openglskydome.cpp | 2 +- rendering/renderer.cpp | 2 +- rendering/screenshot.cpp | 2 +- scene/scene.cpp | 24 +- scene/scenenode.cpp | 4 +- scene/scenenodegroups.cpp | 26 +- scene/sn_utils.cpp | 4 +- scripting/PyInt.cpp | 14 +- scripting/lua.cpp | 62 +- scripting/pythonscreenviewer.cpp | 14 +- simulation/simulationstateserializer.cpp | 8 +- simulation/simulationtime.cpp | 16 +- stb/stb_image.h | 308 +++++----- stb/stb_image_write.h | 70 +-- utilities/Globals.cpp | 2 +- utilities/Logs.cpp | 4 +- utilities/Names.h | 8 +- utilities/Timer.cpp | 2 +- utilities/parser.cpp | 4 +- utilities/translation.cpp | 10 +- utilities/uart.cpp | 2 +- utilities/utilities.cpp | 12 +- utilities/utilities.h | 4 +- utilities/uuid.hpp | 4 +- vehicle/AirCoupler.cpp | 2 +- vehicle/Camera.cpp | 6 +- vehicle/Driver.cpp | 84 +-- vehicle/DynObj.cpp | 32 +- vehicle/Gauge.cpp | 6 +- vehicle/Train.cpp | 84 +-- vr/openvr_imp.cpp | 6 +- vr/vr_interface.cpp | 2 +- widgets/cameraview_extcam.cpp | 14 +- widgets/map.cpp | 12 +- widgets/map_objects.h | 2 +- widgets/perfgraphs.cpp | 4 +- widgets/time.cpp | 2 +- widgets/trainingcard.cpp | 10 +- widgets/vehiclelist.cpp | 6 +- widgets/vehicleparams.cpp | 16 +- world/EvLaunch.cpp | 6 +- world/Event.cpp | 24 +- world/Event.h | 2 +- world/MemCell.cpp | 4 +- world/Segment.cpp | 12 +- world/Track.cpp | 12 +- world/Traction.cpp | 2 +- world/TractionPower.cpp | 2 +- world/TrkFoll.cpp | 2 +- world/station.cpp | 2 +- 118 files changed, 2118 insertions(+), 2063 deletions(-) diff --git a/Console.cpp b/Console.cpp index f06a1e7c..13534c28 100644 --- a/Console.cpp +++ b/Console.cpp @@ -158,7 +158,7 @@ void Console::BitsSet(int mask, int entry) { // ustawienie bitów o podanej masce (mask) na wejściu (entry) if ((iBits & mask) != mask) // jeżeli zmiana { - int old = iBits; // poprzednie stany + const int old = iBits; // poprzednie stany iBits |= mask; BitsUpdate(old ^ iBits); // 1 dla bitów zmienionych if (iMode == 4) @@ -171,7 +171,7 @@ void Console::BitsClear(int mask, int entry) { // zerowanie bitów o podanej masce (mask) na wejściu (entry) if (iBits & mask) // jeżeli zmiana { - int old = iBits; // poprzednie stany + const int old = iBits; // poprzednie stany iBits &= ~mask; BitsUpdate(old ^ iBits); // 1 dla bitów zmienionych } @@ -267,7 +267,7 @@ void Console::ValueSet(int x, double y) WriteLog( " fraction=" + std::to_string( y ) ); } } - double temp = ((((( + const double temp = ((((( Global.fCalibrateOut[x][5] * y) + Global.fCalibrateOut[x][4]) * y + Global.fCalibrateOut[x][3]) * y diff --git a/Console/PoKeys55.cpp b/Console/PoKeys55.cpp index 1e320543..747f3adc 100644 --- a/Console/PoKeys55.cpp +++ b/Console/PoKeys55.cpp @@ -56,10 +56,10 @@ void TPoKeys55::Close() bool TPoKeys55::Connect() { // Ra: to jest do wyczyszcznia z niepotrzebnych zmiennych i komunikatów Close(); - GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, + const GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}; // wszystkie HID tak mają HDEVINFO DeviceInfoTable; - auto InterfaceDataStructure = new SP_DEVICE_INTERFACE_DATA; + const auto InterfaceDataStructure = new SP_DEVICE_INTERFACE_DATA; auto DetailedInterfaceDataStructure = new SP_DEVICE_INTERFACE_DETAIL_DATA; SP_DEVINFO_DATA DevInfoData; diff --git a/EU07.cpp b/EU07.cpp index fd66c3fd..cf0a4dec 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -54,9 +54,9 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) oss << "crash_" << std::setw(4) << std::setfill('0') << st.wYear << "-" << std::setw(2) << std::setfill('0') << st.wMonth << "-" << std::setw(2) << std::setfill('0') << st.wDay << "_" << std::setw(2) << std::setfill('0') << st.wHour << "-" << std::setw(2) << std::setfill('0') << st.wMinute << "-" << std::setw(2) << std::setfill('0') << st.wSecond << ".dmp"; - std::string filename = oss.str(); + const std::string filename = oss.str(); - HANDLE hFile = CreateFileA(filename.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + const HANDLE hFile = CreateFileA(filename.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile != INVALID_HANDLE_VALUE) { MINIDUMP_EXCEPTION_INFORMATION dumpInfo; @@ -65,7 +65,7 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) dumpInfo.ClientPointers = FALSE; // Wybrana kombinacja flag - auto dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | + const auto dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR); @@ -92,10 +92,10 @@ int main(int argc, char *argv[]) // quick short-circuit for standalone e3d export if (argc == 6 && std::string(argv[1]) == "-e3d") { - std::string in(argv[2]); - std::string out(argv[3]); - int flags = std::stoi(std::string(argv[4])); - int dynamic = std::stoi(std::string(argv[5])); + const std::string in(argv[2]); + const std::string out(argv[3]); + const int flags = std::stoi(std::string(argv[4])); + const int dynamic = std::stoi(std::string(argv[5])); export_e3d_standalone(in, out, flags, dynamic); } else diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 72808684..e6efa436 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -46,9 +46,9 @@ double ComputeCollision(double &v1, double &v2, double m1, double m2, double bet return 0; else { - double sum = m1 + m2; - double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum; - double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum; + const double sum = m1 + m2; + const double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum; + const double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum; v1 = w1 * std::sqrt(1.0 - beta); // niejawna zmiana predkosci wskutek zderzenia v2 = w2 * std::sqrt(1.0 - beta); return m1 * (w2 - w1) * (1 - beta); @@ -130,8 +130,8 @@ void TSecuritySystem::update(double dt, double vel, bool pwr, int cab) return; } - bool just_powered_on = !power && pwr; - bool just_activated = CabDependent && cabactive != cab; + const bool just_powered_on = !power && pwr; + const bool just_activated = CabDependent && cabactive != cab; /* enabling battery */ if (cabsignal_enabled && (just_powered_on || just_activated)) @@ -233,7 +233,7 @@ bool TSecuritySystem::is_engine_blocked() const void TSecuritySystem::load(std::string const &line, double Vmax) { - std::string awaresystem = extract_value("AwareSystem", line); + const std::string awaresystem = extract_value("AwareSystem", line); if (awaresystem.find("Active") != std::string::npos) vigilance_enabled = true; if (awaresystem.find("CabSignal") != std::string::npos) @@ -274,7 +274,7 @@ double TableInterpolation(std::map &Map, double Parameter) lower--; upper--; } - double ratio = (upper->second - lower->second) / (upper->first - lower->first); + const double ratio = (upper->second - lower->second) / (upper->first - lower->first); return lower->second + (Parameter - lower->first) * ratio; } @@ -660,7 +660,7 @@ bool TMoverParameters::Dettach(int ConnectNo) { // rozlaczanie auto &coupler{Couplers[ConnectNo]}; - auto &othervehicle{coupler.Connected}; + const auto &othervehicle{coupler.Connected}; auto &othercoupler{othervehicle->Couplers[coupler.ConnectedNr]}; if (othervehicle == nullptr) @@ -735,7 +735,7 @@ void TMoverParameters::BrakeLevelSet(double b) fBrakeCtrlPos = Handle->GetPos(bh_MAX); // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable BrakeCtrlPosR = fBrakeCtrlPos; - int x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być + const int x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być // obcięte a nie zaokrągone while (x > BrakeCtrlPos && BrakeCtrlPos < BrakeCtrlPosNo) // jeśli zwiększyło się o 1 if (!IncBrakeLevelOld()) // T_MoverParameters:: @@ -1188,10 +1188,10 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) return; } // shouldn't normally happen but, eh - auto &coupler{Couplers[End]}; + const auto &coupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; + const auto &othercoupler{othervehicle->Couplers[otherend]}; auto velocity{V}; auto othervehiclevelocity{othervehicle->V}; @@ -1573,7 +1573,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) // Uproszczona symulacja wentylatorow rezystora hamowania // Prad oddawany na rezystor - double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); + const double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora if (Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) @@ -2287,7 +2287,7 @@ void TMoverParameters::PantographsCheck(double const Timestep) { { - auto &valve{PantsValve}; + const auto &valve{PantsValve}; auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; auto const autostart{valve.start_type == start_t::automatic || valve.start_type == start_t::manualwithautofallback}; auto const manualcontrol{valve.start_type == start_t::manual || valve.start_type == start_t::manualwithautofallback}; @@ -2912,7 +2912,7 @@ bool TMoverParameters::CabActivisation(bool const Enforce) bool TMoverParameters::CabActivisationAuto(bool const Enforce) { - bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false; + const bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false; return OK; } @@ -2959,7 +2959,7 @@ bool TMoverParameters::CabDeactivisation(bool const Enforce) bool TMoverParameters::CabDeactivisationAuto(bool const Enforce) { - bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false; + const bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false; return OK; } @@ -3029,7 +3029,7 @@ bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) { bool result{false}; - bool NewState = State && SandDoseAutoAllow; + const bool NewState = State && SandDoseAutoAllow; if (SandDoseAuto != NewState) { if (SandDoseAuto == false) @@ -3137,7 +3137,7 @@ void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP // ************************************************************************************************* void TMoverParameters::SecuritySystemCheck(double dt) { - bool isPower = Power24vIsAvailable || Power110vIsAvailable; + const bool isPower = Power24vIsAvailable || Power110vIsAvailable; SecuritySystem.update(dt, Vel, isPower, CabActive); if (!Battery || !Radio) @@ -4121,7 +4121,7 @@ bool TMoverParameters::BrakeReleaser(int state) // ************************************************************************************************* bool TMoverParameters::UniversalBrakeButton(int button, int state) { - bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 + const bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 UniversalBrakeButtonActive[button] = state > 0; int flag = 0; if (Power24vIsAvailable || Power110vIsAvailable) @@ -4342,7 +4342,7 @@ void TMoverParameters::CompressorCheck(double dt) EmergencyValveOpen = Compressor > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); if (EmergencyValveOpen) { - float dV = PF(0, Compressor, EmergencyValveArea) * dt; + const float dV = PF(0, Compressor, EmergencyValveArea) * dt; CompressedVolume -= dV; } @@ -4513,13 +4513,13 @@ void TMoverParameters::UpdatePipePressure(double dt) // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. - double lbpa = SplitEDPneumaticBrake ? LocalBrakePosA : 0.0; + const double lbpa = SplitEDPneumaticBrake ? LocalBrakePosA : 0.0; dpLocalValve = LocHandle->GetPF(std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); } LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); - bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz - bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions + const bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz + const bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; if (lock_old || lock_new) @@ -4830,18 +4830,18 @@ void TMoverParameters::UpdateScndPipePressure(double dt) // ************************************************************************************************* void TMoverParameters::UpdateSpringBrake(double dt) { - double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; - double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; + const double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; + const double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; if (!SpringBrake.Activate) { - double desired_press = std::min(std::max(MSP, BP), Pipe2->P()); - double dv = PF(desired_press, SpringBrake.SBP, SpringBrake.ValveOffArea); + const double desired_press = std::min(std::max(MSP, BP), Pipe2->P()); + const double dv = PF(desired_press, SpringBrake.SBP, SpringBrake.ValveOffArea); SpringBrake.Cylinder->Flow(-dv); Pipe2->Flow(std::max(dv, 0.0)); } else { - double dv = PF(BP, SpringBrake.SBP, SpringBrake.ValveOnArea); + const double dv = PF(BP, SpringBrake.SBP, SpringBrake.ValveOnArea); SpringBrake.Cylinder->Flow(-dv); } if (SpringBrake.SBP > SpringBrake.ResetPressure) @@ -5029,7 +5029,7 @@ void TMoverParameters::ComputeTotalForce(double dt) // TBD, TODO: more accurate approach? FStand *= 1e20; } - double old_nrot = abs(nrot); + const double old_nrot = abs(nrot); nrot = v2n(); // przeliczenie prędkości liniowej na obrotową if (true == TestFlag(BrakeMethod, bp_MHS) && PipePress < 3.0 // ustawione na sztywno na 3 bar @@ -5103,7 +5103,7 @@ void TMoverParameters::ComputeTotalForce(double dt) } else { - double factor = FTrain - Fb * Sign(V) != 0 ? Fwheels / (FTrain - Fb * Sign(V)) : 1.0; + const double factor = FTrain - Fb * Sign(V) != 0 ? Fwheels / (FTrain - Fb * Sign(V)) : 1.0; Fb *= factor; FTrain *= factor; } @@ -5874,7 +5874,7 @@ double TMoverParameters::TractionForce(double dt) // jazda manewrowa if (EIMCtrlType > 0) // sterowanie cyfrowe { - auto eimic_positive = std::max(0.0, eimic_real); + const auto eimic_positive = std::max(0.0, eimic_real); auto const rpmratio{EngineRPMRatio()}; tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); @@ -6007,8 +6007,8 @@ double TMoverParameters::TractionForce(double dt) } else { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; - auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; + const auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; + const auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); EngineVoltage /= tempMCPN - 1; @@ -6231,7 +6231,7 @@ double TMoverParameters::TractionForce(double dt) if (true == Mains && !SecuritySystem.is_engine_blocked()) { double ActiveInverters = 0.0; - for (auto &inv : Inverters) + for (const auto &inv : Inverters) { if (inv.IsActive) ActiveInverters += 1.0; @@ -6298,7 +6298,7 @@ double TMoverParameters::TractionForce(double dt) SpeedCtrlTimer += dt; if (SpeedCtrlTimer > SpeedCtrlDelay) { - int NewSCAP = (float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax; + const int NewSCAP = (float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax; if (NewSCAP != SpeedCtrlValue) { SpeedCtrlValue = NewSCAP; @@ -6414,7 +6414,7 @@ double TMoverParameters::TractionForce(double dt) else tmp = eimc[eimc_f_Uzmax]; - auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; + const auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; @@ -7324,8 +7324,8 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify void TMoverParameters::CheckEIMIC(double dt) { - double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; - double multiplier = (EIMCtrlEmergency ? 1.0 : 0.0) + offset; + const double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; + const double multiplier = (EIMCtrlEmergency ? 1.0 : 0.0) + offset; // gdy SplitEDPneumaticBrake jest wlaczone, sterowanie ujemne (hamowanie ED) bierzemy // z osobnego nastawnika DynamicBrakeCtrl, a nie z hamulca pomocniczego (LocalBrake). // Dodatkowo zapotrzebowanie ED jest ograniczone przez strefe Vh0..Vh1: powyzej Vh1 - pelny ED, @@ -7389,7 +7389,7 @@ void TMoverParameters::CheckEIMIC(double dt) case 2: if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) { - double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; + const double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; switch (MainCtrlPos) { case 0: @@ -7549,10 +7549,10 @@ void TMoverParameters::CheckSpeedCtrl(double dt) if (eimic > 0.0009) eimic = 1.0; } - double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; - double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; + const double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; + const double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module - bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; + const bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; if (eSCP < -1.0) { SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; @@ -7563,7 +7563,7 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { // TODO: check how to disable integral part when braking in smart way // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + const double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); } else @@ -7624,7 +7624,7 @@ void TMoverParameters::SpeedCtrlInc() { if (SpeedCtrl && ScndCtrlPos > 0) { - double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; + const double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); } } @@ -7633,7 +7633,7 @@ void TMoverParameters::SpeedCtrlDec() { if (SpeedCtrl && ScndCtrlPos > 0) { - double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; + const double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); } } @@ -8071,7 +8071,7 @@ double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) if (hydro_TC) // jesli przetwornik momentu { // napelnianie przetwornika - bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; + const bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; if (IsPower && Mains && enrot > dizel_nmin * 0.9) hydro_TC_Fill += hydro_TC_FillRateInc * dt; // oproznianie przetwornika @@ -8111,7 +8111,7 @@ double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; - double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); + const double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); if (hydro_TC_Table.size() > 1) { hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); @@ -8181,8 +8181,8 @@ double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) dizel_engagedeltaomega = 0; gearMoment = Moment; enMoment = 0; - double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) - Moment) / dizel_AIM * dt; - double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) + Moment) / dizel_AIM * dt; + const double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) - Moment) / dizel_AIM * dt; + const double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) + Moment) / dizel_AIM * dt; enrot = safe_clamp(n, enrot_min, enrot_max); } if (hydro_R && hydro_R_Placement == 1) @@ -8236,10 +8236,10 @@ double TMoverParameters::dizel_MomentumRetarder(double n, double dt) } double Moment = hydro_R_MaxTorque; - double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; + const double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; if (pwr > hydro_R_MaxPower) Moment = Moment * hydro_R_MaxPower / pwr; - double moment_in = n * n * hydro_R_TorqueInIn; + const double moment_in = n * n * hydro_R_TorqueInIn; Moment = std::min(moment_in, Moment * hydro_R_Fill); hydro_R_Torque = Moment; @@ -8983,7 +8983,7 @@ double TMoverParameters::GetTrainsetVoltage(int const Coupling) const { continue; } - auto *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_high : + const auto *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_high : (Coupling & coupling::power110v) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_110v : (Coupling & coupling::power24v) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_24v : nullptr; @@ -9238,7 +9238,7 @@ bool TMoverParameters::readRList(std::string const &Input) WriteLog("Read RList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + const auto idx = LISTLINE++; if (idx >= sizeof(RList) / sizeof(TScheme)) { WriteLog("Read RList: number of entries exceeded capacity of the data table"); @@ -9263,7 +9263,7 @@ bool TMoverParameters::readUCList(std::string const &line) cParser parser(line); parser.getTokens(10, false); - auto idx = LISTLINE++; + const auto idx = LISTLINE++; if (idx >= sizeof(UniCtrlList) / sizeof(TUniversalCtrl)) { WriteLog("Read UCList: number of entries exceeded capacity of the data table"); @@ -9281,7 +9281,7 @@ bool TMoverParameters::readDList(std::string const &line) cParser parser(line); parser.getTokens(3, false); - auto idx = LISTLINE++; + const auto idx = LISTLINE++; if (idx >= sizeof(RList) / sizeof(TScheme)) { WriteLog("Read DList: number of entries exceeded capacity of the data table"); @@ -9381,7 +9381,7 @@ bool TMoverParameters::readFFList(std::string const &line) WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + const int idx = LISTLINE++; if (idx >= sizeof(FFlist) / sizeof(TFFScheme)) { WriteLog("Read FList: number of entries exceeded capacity of the data table"); @@ -9401,7 +9401,7 @@ bool TMoverParameters::readFFEDList(std::string const &line) WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + const int idx = LISTLINE++; if (idx >= sizeof(FFEDlist) / sizeof(TFFScheme)) { WriteLog("Read FList: number of entries exceeded capacity of the data table"); @@ -9421,7 +9421,7 @@ bool TMoverParameters::readWiperList(std::string const &line) WriteLog("Read WiperList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + const int idx = LISTLINE++; if (idx >= sizeof(WiperList) / sizeof(TWiperScheme)) { WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); @@ -9457,7 +9457,7 @@ bool TMoverParameters::readWWList(std::string const &line) WriteLog("Read WWList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + const int idx = LISTLINE++; if (idx >= sizeof(DElist) / sizeof(TDEScheme)) { WriteLog("Read WWList: number of entries exceeded capacity of the data table"); @@ -9485,7 +9485,7 @@ bool TMoverParameters::readLightsList(std::string const &Input) WriteLog("Read LightsList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + const int idx = LISTLINE++; if (idx > 16) { WriteLog("Read LightsList: number of entries exceeded capacity of the data table"); @@ -9505,7 +9505,7 @@ bool TMoverParameters::readCompressorList(std::string const &Input) WriteLog("Read CompressorList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + const int idx = LISTLINE++; if (idx > 8 - 1) { WriteLog("Read CompressorList: number of entries exceeded capacity of the data table"); @@ -9551,7 +9551,7 @@ void TMoverParameters::BrakeValveDecode(std::string const &Valve) {"CV1_L_TR", TBrakeValve::CV1_L_TR}, {"CV1", TBrakeValve::CV1}, {"CV1_R", TBrakeValve::CV1_R}}; - auto lookup = valvetypes.find(Valve); + const auto lookup = valvetypes.find(Valve); BrakeValve = lookup != valvetypes.end() ? lookup->second : TBrakeValve::Other; if (BrakeValve == TBrakeValve::Other && contains(Valve, "ESt")) @@ -10256,7 +10256,7 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) std::map categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; std::string category; extract_value(category, "Category", line, "none"); - auto lookup = categories.find(category); + const auto lookup = categories.find(category); CategoryFlag = lookup != categories.end() ? lookup->second : 0; if (CategoryFlag == 0) { @@ -10280,7 +10280,7 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) }; std::string type; extract_value(type, "Type", line, "none"); - auto lookup = types.find(ToLower(type)); + const auto lookup = types.find(ToLower(type)); TrainType = lookup != types.end() ? lookup->second : dt_Default; } @@ -10452,7 +10452,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) { std::map brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; - auto lookup = brakemethods.find(extract_value("BM", line)); + const auto lookup = brakemethods.find(extract_value("BM", line)); BrakeMethod = lookup != brakemethods.end() ? lookup->second : 0; } @@ -10502,7 +10502,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) {"Coupler1", 4}, // włączana w silnikowym EZT z przodu {"Coupler2", 5} // włączana w silnikowym EZT z tyłu }; - auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); + const auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); CompressorPower = lookup != compressorpowers.end() ? lookup->second : 1; } @@ -10541,12 +10541,12 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) {"Passenger", control_t::passenger}, {"AutomaticCtrl", control_t::autonomous}, {"DriverCtrl", control_t::driver}, {"Conductor", control_t::conductor}, {"Mixed", control_t::mixed}}; // opening method { - auto lookup = doorcontrols.find(extract_value("OpenCtrl", line)); + const auto lookup = doorcontrols.find(extract_value("OpenCtrl", line)); Doors.open_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; } // closing method { - auto lookup = doorcontrols.find(extract_value("CloseCtrl", line)); + const auto lookup = doorcontrols.find(extract_value("CloseCtrl", line)); Doors.close_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; } // automatic closing conditions @@ -10556,7 +10556,7 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) // operation permit extract_value(Doors.permit_needed, "DoorNeedPermit", line, ""); { - auto permitpresets = Split(extract_value("DoorPermitList", line), '|'); + const auto permitpresets = Split(extract_value("DoorPermitList", line), '|'); for (auto const &permit : permitpresets) { Doors.permit_presets.emplace_back(std::stoi(permit)); @@ -10585,7 +10585,7 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) }; // opening method { - auto lookup = doortypes.find(extract_value("DoorOpenMethod", line)); + const auto lookup = doortypes.find(extract_value("DoorOpenMethod", line)); Doors.type = lookup != doortypes.end() ? lookup->second : 2; // default type is plain, rotating door } @@ -10632,7 +10632,7 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde std::map couplertypes{ {"Automatic", TCouplerType::Automatic}, {"Screw", TCouplerType::Screw}, {"Chain", TCouplerType::Chain}, {"Bare", TCouplerType::Bare}, {"Articulated", TCouplerType::Articulated}, }; - auto lookup = couplertypes.find(extract_value("CType", line)); + const auto lookup = couplertypes.find(extract_value("CType", line)); coupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; extract_value(coupler->SpringKC, "kC", line, ""); @@ -11087,7 +11087,7 @@ void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) SpeedCtrlTypeTime = extract_value("SpeedCtrlType", Line) == "Time" ? true : false; extract_value(SpeedCtrlAutoTurnOffFlag, "SpeedCtrlATOF", Line, ""); - auto speedpresets = Split(extract_value("SpeedButtons", Line), '|'); + const auto speedpresets = Split(extract_value("SpeedButtons", Line), '|'); int speed_no = 0; for (auto const &speed : speedpresets) { @@ -11121,11 +11121,11 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); - std::string transmission = extract_value("Trans", Input); + const std::string transmission = extract_value("Trans", Input); if (false == transmission.empty()) { // transmission type. moved here because more than one engine type has this entry - auto ratios = Split(transmission, ':'); // e.g. 18:79 + const auto ratios = Split(transmission, ':'); // e.g. 18:79 if (ratios.size() != 2) { @@ -11499,9 +11499,9 @@ void TMoverParameters::LoadFIZ_DList(std::string const &Input) } // Calculation of fuel consumption coefficient for futher calculation - double dizel_max_power = dizel_nmax * (dizel_Mnmax - dizel_Mstand) * M_PI * 2 * 0.001; // power in kW - double dizel_max_energy = dizel_max_power; // energy per one hour in kWh is equal to power in kW times 1 h - double fuel_density = 850; // g/l + const double dizel_max_power = dizel_nmax * (dizel_Mnmax - dizel_Mstand) * M_PI * 2 * 0.001; // power in kW + const double dizel_max_energy = dizel_max_power; // energy per one hour in kWh is equal to power in kW times 1 h + const double fuel_density = 850; // g/l dizel_FuelConsumption = dizel_NominalFuelConsumptionRate * dizel_max_energy / fuel_density / dizel_nmax; } @@ -11670,7 +11670,7 @@ TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Power) std::map powertypes{ {"BioPower", TPowerType::BioPower}, {"MechPower", TPowerType::MechPower}, {"ElectricPower", TPowerType::ElectricPower}, {"SteamPower", TPowerType::SteamPower}}; - auto lookup = powertypes.find(Power); + const auto lookup = powertypes.find(Power); return lookup != powertypes.end() ? lookup->second : TPowerType::NoPower; } @@ -11682,7 +11682,7 @@ TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) {"Accumulator", TPowerSource::Accumulator}, {"CurrentCollector", TPowerSource::CurrentCollector}, {"PowerCable", TPowerSource::PowerCable}, {"Heater", TPowerSource::Heater}, {"Internal", TPowerSource::InternalSource}, {"Main", TPowerSource::Main}}; - auto lookup = powersources.find(Source); + const auto lookup = powersources.find(Source); return lookup != powersources.end() ? lookup->second : TPowerSource::NotDefined; } @@ -11698,7 +11698,7 @@ TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) {"DumbDE", TEngineType::DieselElectric}, {"ElectricInductionMotor", TEngineType::ElectricInductionMotor}, {"Main", TEngineType::Main}}; - auto lookup = enginetypes.find(Engine); + const auto lookup = enginetypes.find(Engine); return lookup != enginetypes.end() ? lookup->second : TEngineType::None; } @@ -12051,7 +12051,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) BrakeOpModeFlag = bom_PN; // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - int DefBrakeTable[8] = {15, 4, 25, 25, 13, 3, 12, 2}; + const int DefBrakeTable[8] = {15, 4, 25, 25, 13, 3, 12, 2}; for (b = 1; b < 4; b++) { @@ -12790,7 +12790,7 @@ bool TMoverParameters::reload_FIZ() WriteLog("[DEV] Reloading FIZ for " + Name); // pause simulation Global.iPause |= 0b1000; - bool result = LoadFIZ(chkPath); + const bool result = LoadFIZ(chkPath); if (result == true) { // jesli sie udalo przeladowac FIZ diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp index 1df5fe81..768bd729 100644 --- a/McZapkie/Oerlikon_ESt.cpp +++ b/McZapkie/Oerlikon_ESt.cpp @@ -59,8 +59,8 @@ void TPrzekladnik::Update(double dt) { double dV; - double BCP{ Next->P() }; - double BVP{ BrakeRes->P() }; + const double BCP{ Next->P() }; + const double BVP{ BrakeRes->P() }; if ( BCP > P() ) dV = -PFVd(BCP, 0, d2A(10), P()) * dt; @@ -101,8 +101,8 @@ void TRapid::SetRapidStatus(bool rs) void TRapid::Update(double dt) { - double BVP{ BrakeRes->P() }; - double BCP{ Next->P() }; + const double BVP{ BrakeRes->P() }; + const double BCP{ Next->P() }; double ActMult; double dV; diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index 44e8be4b..8009474a 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -45,8 +45,8 @@ double const TFVE408::pos_table[11] = {0, 10, 0, 0, 10, 7, 8, 9, 0, 1, 5}; /// Dimensionless flow driver (positive when P2 > P1). double PR(double P1, double P2) { - double PH = std::max(P1, P2) + 0.1; - double PL = P1 + P2 - PH + 0.2; + const double PH = std::max(P1, P2) + 0.1; + const double PL = P1 + P2 - PH + 0.2; return (P2 - P1) / (1.13 * PH - PL); } @@ -59,8 +59,8 @@ double PR(double P1, double P2) /// Volumetric flow rate (signed). double PF_old(double P1, double P2, double S) { - double PH = std::max(P1, P2) + 1; - double PL = P1 + P2 - PH + 2; + const double PH = std::max(P1, P2) + 1; + const double PL = P1 + P2 - PH + 2; if (PH - PL < 0.0001) return 0; else if (PH - PL < 0.05) @@ -139,7 +139,7 @@ double PFVa(double PH, double PL, double const S, double LIM, double const DP) LIM = LIM + 1; PH = PH + 1; // wyzsze cisnienie absolutne PL = PL + 1; // nizsze cisnienie absolutne - double sg = std::min(1.0, PL / PH); // bezwymiarowy stosunek cisnien. NOTE: sg is capped at 1 to prevent calculations from going awry. TODO, TBD: log these as errors? + const double sg = std::min(1.0, PL / PH); // bezwymiarowy stosunek cisnien. NOTE: sg is capped at 1 to prevent calculations from going awry. TODO, TBD: log these as errors? double FM = PH * 197 * S; // najwyzszy mozliwy przeplyw, wraz z kierunkiem if (LIM - PL < DP) FM = FM * (LIM - PL) / DP; // jesli jestesmy przy nastawieniu, to zawor sie przymyka @@ -173,7 +173,7 @@ double PFVd(double PH, double PL, double const S, double LIM, double const DP) LIM = LIM + 1; PH = PH + 1.0; // wyzsze cisnienie absolutne PL = PL + 1.0; // nizsze cisnienie absolutne - double sg = std::min(1.0, PL / PH); // bezwymiarowy stosunek cisnien + const double sg = std::min(1.0, PL / PH); // bezwymiarowy stosunek cisnien double FM = PH * 197.0 * S; // najwyzszy mozliwy przeplyw, wraz z kierunkiem if (PH - LIM < 0.1) FM = FM * (PH - LIM) / DP; // jesli jestesmy przy nastawieniu, to zawor sie przymyka @@ -302,7 +302,7 @@ double TBrakeCyl::P() static double const cD = 1; static double const pD = VD - cD; - double VtoC = Cap > 0.0 ? Vol / Cap : 0.0; // stosunek cisnienia do objetosci. + const double VtoC = Cap > 0.0 ? Vol / Cap : 0.0; // stosunek cisnienia do objetosci. // Added div/0 trap for vehicles with incomplete definitions (cars etc) // P:=VtoC; if (VtoC < VS) @@ -583,7 +583,7 @@ int TBrake::GetStatus() /// int TBrake::GetSoundFlag() { - int result = SoundFlag; + const int result = SoundFlag; SoundFlag = 0; return result; } @@ -833,8 +833,8 @@ void TWest::SetLP(double const TM, double const LM, double const TBP) /// Time step [s]. void TESt::CheckReleaser(double const dt) { - double VVP = std::min(ValveRes->P(), BrakeRes->P() + 0.05); - double CVP = CntrlRes->P() - 0.0; + const double VVP = std::min(ValveRes->P(), BrakeRes->P() + 0.05); + const double CVP = CntrlRes->P() - 0.0; // odluzniacz if ((BrakeStatus & b_rls) == b_rls) @@ -1298,8 +1298,8 @@ void TEStEP2::SetLP(double const TM, double const LM, double const TBP) /// Time step [s]. void TEStEP2::EPCalc(double dt) { - double temp = BrakeRes->P() * int(EPS > 0); - double dv = PF(temp, LBP, 0.00053 + 0.00060 * int(EPS < 0)) * dt * EPS * EPS * int(LBP * EPS < MaxBP * LoadC); + const double temp = BrakeRes->P() * int(EPS > 0); + const double dv = PF(temp, LBP, 0.00053 + 0.00060 * int(EPS < 0)) * dt * EPS * EPS * int(LBP * EPS < MaxBP * LoadC); LBP = LBP - dv; } @@ -1312,10 +1312,10 @@ void TEStEP2::EPCalc(double dt) /// Time step [s]. void TEStEP1::EPCalc(double dt) { - double temp = EPS - std::floor(EPS); // część ułamkowa jest hamulcem EP - double LBPLim = std::min(MaxBP * LoadC * temp, BrakeRes->P()); // do czego dążymy - double S = 10 * std::clamp(LBPLim - LBP, -0.1, 0.1); // przymykanie zaworku - double dv = PF(S > 0 ? BrakeRes->P() : 0, LBP, abs(S) * (0.00053 + 0.00060 * int(S < 0))) * dt; // przepływ + const double temp = EPS - std::floor(EPS); // część ułamkowa jest hamulcem EP + const double LBPLim = std::min(MaxBP * LoadC * temp, BrakeRes->P()); // do czego dążymy + const double S = 10 * std::clamp(LBPLim - LBP, -0.1, 0.1); // przymykanie zaworku + const double dv = PF(S > 0 ? BrakeRes->P() : 0, LBP, abs(S) * (0.00053 + 0.00060 * int(S < 0))) * dt; // przepływ LBP = LBP - dv; } @@ -1342,9 +1342,9 @@ void TEStEP1::SetEPS(double const nEPS) /// Net volume exchanged with the brake pipe. double TESt3::GetPF(double const PP, double const dt, double const Vel) { - double BVP{BrakeRes->P()}; + const double BVP{BrakeRes->P()}; double VVP{ValveRes->P()}; - double BCP{BrakeCyl->P()}; + const double BCP{BrakeCyl->P()}; double CVP{CntrlRes->P() - 0.0}; double dv{0.0}; @@ -1715,7 +1715,7 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) SoundFlag |= sf_CylU; } // equivalent of checkreleaser() in the base class? - bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; + const bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; if (is_releasing) { if (CVP < 0.0) @@ -2949,7 +2949,7 @@ double TFV4a::GetPF(double i_bcp, double PP, double HP, double dt, double ep) ep = PP; // SPKS!! double LimPP = std::min(BPT[std::lround(i_bcp) + 2][1], HP); - double ActFlowSpeed = BPT[std::lround(i_bcp) + 2][0]; + const double ActFlowSpeed = BPT[std::lround(i_bcp) + 2][0]; if (i_bcp == i_bcpno) LimPP = 2.9; @@ -2958,7 +2958,7 @@ double TFV4a::GetPF(double i_bcp, double PP, double HP, double dt, double ep) RP = RP + 20 * std::min(std::abs(ep - RP), 0.05) * PR(RP, ep) * dt / 2.5; LimPP = CP; - double dpPipe = std::min(HP, LimPP); + const double dpPipe = std::min(HP, LimPP); double dpMainValve = PF(dpPipe, PP, ActFlowSpeed / LBDelay) * dt; if (CP > RP + 0.05) @@ -3964,7 +3964,7 @@ double TH14K1::GetPF(double i_bcp, double PP, double HP, double dt, double ep) { LimPP = CP; } - double ActFlowSpeed = BPT_K[BCP + 1][0]; + const double ActFlowSpeed = BPT_K[BCP + 1][0]; CP = CP + 6 * std::min(std::abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy diff --git a/application/application.cpp b/application/application.cpp index 4657aff0..9c469ac6 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -209,8 +209,8 @@ void eu07_application::DiscordRPCService() Discord_Initialize(discord_app_id, &handlers, 1, nullptr); // calculate startup timestamp - auto now = std::chrono::system_clock::now(); - auto now_c = std::chrono::system_clock::to_time_t(now); + const auto now = std::chrono::system_clock::now(); + const auto now_c = std::chrono::system_clock::to_time_t(now); // Init RPC object static DiscordRichPresence discord_rpc; @@ -221,7 +221,7 @@ void eu07_application::DiscordRPCService() // run loop while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty() && !Global.applicationQuitOrder) { - auto currentMode = m_modestack.top(); + const auto currentMode = m_modestack.top(); if (currentMode == mode::launcher) { // in launcher mode @@ -278,7 +278,7 @@ void eu07_application::DiscordRPCService() PlayerVehicle = Translations.lookup_s("Driving: ") + PlayerVehicle; discord_rpc.details = PlayerVehicle.c_str(); - uint16_t playerTrainVelocity = simulation::Train->Dynamic()->GetVelocity(); + const uint16_t playerTrainVelocity = simulation::Train->Dynamic()->GetVelocity(); if (playerTrainVelocity > 1) { // ikonka ze jedziemy i nie spimy @@ -444,7 +444,7 @@ void eu07_application::queue_quit(bool direct) return; } - command_relay relay; + const command_relay relay; relay.post(user_command::quitsimulation, 0.0, 0.0, GLFW_PRESS, 0); } @@ -483,7 +483,7 @@ int eu07_application::run() // // trivia: being client and server is possible - double frameStartTime = Timer::GetTime(); + const double frameStartTime = Timer::GetTime(); if (m_modes[m_modestack.top()]->is_command_processor()) { @@ -512,7 +512,7 @@ int eu07_application::run() auto frame_info = m_network->client->get_next_delta(MAX_NETWORK_PER_FRAME - loop_remaining); // use delta and commands received from master - double delta = std::get<0>(frame_info); + const double delta = std::get<0>(frame_info); Timer::set_delta_override(delta); slave_sync = std::get<1>(frame_info); add_to_dequemap(commands_to_exec, std::get<2>(frame_info)); @@ -542,14 +542,14 @@ int eu07_application::run() // update continuous commands simulation::Commands.update(); - double sync = generate_sync(); + const double sync = generate_sync(); // if we're the server if (m_network && m_network->servers) { // send delta, sync, and commands we just executed to clients - double delta = Timer::GetDeltaTime(); - double render = Timer::GetDeltaRenderTime(); + const double delta = Timer::GetDeltaTime(); + const double render = Timer::GetDeltaRenderTime(); m_network->servers->push_delta(render, delta, sync, commands_to_exec); } @@ -565,7 +565,7 @@ int eu07_application::run() } // set total delta for rendering code - double totalDelta = Timer::GetTime() - frameStartTime; + const double totalDelta = Timer::GetTime() - frameStartTime; Timer::set_delta_override(totalDelta); } } @@ -573,8 +573,8 @@ int eu07_application::run() if (!loop_remaining) { // loop break forced by counter - float received = m_network->client->get_frame_counter(); - float awaiting = m_network->client->get_awaiting_frames(); + const float received = m_network->client->get_frame_counter(); + const float awaiting = m_network->client->get_awaiting_frames(); // TODO: don't meddle with mode progresbar m_modes[m_modestack.top()]->set_progress(100.0f * (received - awaiting) / received); @@ -901,7 +901,7 @@ void eu07_application::on_focus_change(bool focus) { if (Global.bInactivePause && m_network.has_value() && !m_network->client) { // jeśli ma być pauzowanie okna w tle - command_relay relay; + const command_relay relay; relay.post(user_command::focuspauseset, focus ? 1.0 : 0.0, 0.0, GLFW_PRESS, 0); } } @@ -1047,7 +1047,7 @@ void eu07_application::init_console() // as text ("←[32m" etc). Open CONOUT$ directly to get the real screen // buffer handle, then flip VT on it. auto enable_vt = [](const char *devName) { - HANDLE h = ::CreateFileA( + const HANDLE h = ::CreateFileA( devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, @@ -1109,7 +1109,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) { Global.asVersion = VERSION_INFO; - fs::path iniPath = user_config_path("eu07.ini"); + const fs::path iniPath = user_config_path("eu07.ini"); if (!iniPath.empty() && fs::exists(iniPath)) { @@ -1461,15 +1461,15 @@ bool eu07_application::init_network() { // we're simulation master // TODO: sort out this timezone mess - std::time_t utc_now = std::time(nullptr); + const std::time_t utc_now = std::time(nullptr); tm tm_local, tm_utc; - tm *tmp = std::localtime(&utc_now); + const tm *tmp = std::localtime(&utc_now); memcpy(&tm_local, tmp, sizeof(tm)); tmp = std::gmtime(&utc_now); memcpy(&tm_utc, tmp, sizeof(tm)); - int64_t offset = tm_local.tm_hour * 3600 + tm_local.tm_min * 60 + tm_local.tm_sec - (tm_utc.tm_hour * 3600 + tm_utc.tm_min * 60 + tm_utc.tm_sec); + const int64_t offset = tm_local.tm_hour * 3600 + tm_local.tm_min * 60 + tm_local.tm_sec - (tm_utc.tm_hour * 3600 + tm_utc.tm_min * 60 + tm_utc.tm_sec); Global.starting_timestamp = utc_now + offset; Global.ready_to_load = true; diff --git a/application/drivermode.cpp b/application/drivermode.cpp index a002bc0b..bb051ad5 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -74,7 +74,7 @@ bool driver_mode::drivermode_input::init() { // initialize input devices - auto result = keyboard.init() && mouse.init(); + const auto result = keyboard.init() && mouse.init(); if (true == Global.InputGamepad) { gamepad.init(); @@ -419,7 +419,7 @@ bool driver_mode::update() void driver_mode::enter() { - TDynamicObject *nPlayerTrain{(Global.local_start_vehicle != "ghostview" ? simulation::Vehicles.find(Global.local_start_vehicle) : nullptr)}; + const TDynamicObject *nPlayerTrain{(Global.local_start_vehicle != "ghostview" ? simulation::Vehicles.find(Global.local_start_vehicle) : nullptr)}; Camera.Init(Global.FreeCameraInit[0], Global.FreeCameraInitAngle[0], nullptr); Global.pCamera = Camera; @@ -472,7 +472,7 @@ void driver_mode::on_key(int const Key, int const Scancode, int const Action, in Global.altState = Mods & GLFW_MOD_ALT ? true : false; #endif - bool anyModifier = Mods & (GLFW_MOD_SHIFT | GLFW_MOD_CONTROL | GLFW_MOD_ALT); + const bool anyModifier = Mods & (GLFW_MOD_SHIFT | GLFW_MOD_CONTROL | GLFW_MOD_ALT); // give the ui first shot at the input processing... if (!anyModifier && true == m_userinterface->on_key(Key, Action)) diff --git a/application/driveruilayer.cpp b/application/driveruilayer.cpp index 0b8463f8..5e851244 100644 --- a/application/driveruilayer.cpp +++ b/application/driveruilayer.cpp @@ -209,7 +209,7 @@ void driver_ui::update() { auto const pausemask{1 | 2}; - auto ispaused{false == DebugModeFlag && (Global.iPause & pausemask) != 0}; + const auto ispaused{false == DebugModeFlag && (Global.iPause & pausemask) != 0}; if (ispaused != m_paused && false == Global.ControlPicking) { set_cursor(ispaused); diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 03a7692b..97bd91fb 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -473,13 +473,13 @@ timetable_panel::render() { ImGui::PushFont(ui_layer::font_mono); - auto flags = + const auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | ( size.x > 0 ? ImGuiWindowFlags_NoResize : 0 ); // HACK: Make sure the timetable window is of correct width when using a larger font size. - float horizontalScale = Global.ui_fontsize / 13; + const float horizontalScale = Global.ui_fontsize / 13; if( size.x > 0 ) { ImGui::SetNextWindowSize( ImVec2S( size.x * horizontalScale, size.y ) ); } @@ -565,7 +565,7 @@ debug_panel::render() { ImGui::PushFont(ui_layer::font_mono); - auto flags = + const auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | ( size.x > 0 ? ImGuiWindowFlags_NoResize : 0 ); @@ -591,7 +591,7 @@ debug_panel::render() { if( true == render_section( "Vehicle", m_vehiclelines ) ) { if( DebugModeFlag && m_input.mover && m_input.mover->DamageFlag != 0 ) { if( true == ImGui::Button( "Stop and repair consist" ) ) { - command_relay relay; + const command_relay relay; relay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); } } @@ -611,8 +611,8 @@ debug_panel::render() { render_section_developer(); // Developer tools #ifdef WITH_UART if(true == render_section( "UART", m_uartlines)) { - int ports_num = UartStatus.available_ports.size(); - auto avlports = new char*[ports_num]; + const int ports_num = UartStatus.available_ports.size(); + const auto avlports = new char*[ports_num]; for (int i=0; i < ports_num; i++) { avlports[i] = (char *) UartStatus.available_ports[i].c_str(); } @@ -625,7 +625,7 @@ debug_panel::render() { ImGui::Separator(); bool flag = DebugModeFlag; if (ImGui::Checkbox("Debug Mode", &flag)) { - command_relay relay; + const command_relay relay; relay.post(user_command::debugtoggle, 0.0, 0.0, GLFW_RELEASE, 0); } } @@ -647,7 +647,7 @@ debug_panel::render_section_scenario() { auto fogrange = std::log( Global.fFogEnd ); if( ImGui::SliderFloat( ( to_string( std::exp( fogrange ), 0, 5 ) + " m###fogend" ).c_str(), &fogrange, std::log( 10.0f ), std::log( 50000.0f ), "Fog distance" ) ) { - command_relay relay; + const command_relay relay; relay.post( user_command::setweather, std::clamp( std::exp( fogrange ), 10.0f, 50000.0f ), @@ -661,7 +661,7 @@ debug_panel::render_section_scenario() { (to_string(Airtemperature, 1) + " deg C###Airtemperature").c_str(), &Airtemperature, -35.0f, 40.0f, "Air Temperature")) { - command_relay relay; + const command_relay relay; relay.post( user_command::settemperature, std::clamp(Airtemperature, -35.0f, 40.0f), @@ -673,7 +673,7 @@ debug_panel::render_section_scenario() { { if( ImGui::SliderFloat( ( to_string( Global.Overcast, 2, 5 ) + " (" + Global.Weather + ")###overcast" ).c_str(), &Global.Overcast, 0.0f, 2.0f, "Cloud cover" ) ) { - command_relay relay; + const command_relay relay; relay.post( user_command::setweather, Global.fFogEnd, @@ -685,7 +685,7 @@ debug_panel::render_section_scenario() { { if( ImGui::SliderFloat( ( to_string( Global.fMoveLight, 0, 5 ) + " (" + Global.Season + ")###movelight" ).c_str(), &Global.fMoveLight, 0.0f, 364.0f, "Day of year" ) ) { - command_relay relay; + const command_relay relay; relay.post( user_command::setdatetime, std::clamp( Global.fMoveLight, 0.0f, 365.0f ), @@ -713,7 +713,7 @@ debug_panel::render_section_scenario() { + ":" + std::string( std::to_string( int( 100 + simulation::Time.data().wMinute ) ).substr( 1, 2 ) ) ) }; if( ImGui::SliderInt( ( timestring + " (" + Global.Period + ")###simulationtime" ).c_str(), &time, 0, 1439, "Time of day" ) ) { - command_relay relay; + const command_relay relay; relay.post( user_command::setdatetime, Global.fMoveLight, @@ -980,7 +980,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { } if (!std::isnan(last_time)) { - double dt = Timer::GetTime() - last_time; + const double dt = Timer::GetTime() - last_time; AccN_jerk_graph.update((mover.AccN - last_AccN) / dt); AccN_acc_graph.update(mover.AccN); } @@ -1012,7 +1012,7 @@ debug_panel::update_vehicle_coupler( int const Side ) { auto const &mover { *m_input.mover }; std::string const controltype{ ( mover.Couplers[ Side ].control_type.empty() ? "[*]" : "[" + mover.Couplers[ Side ].control_type + "]" ) }; - std::string couplerstatus { STR("none") }; + const std::string couplerstatus { STR("none") }; std::string const adapterstatus { ( mover.Couplers[ Side ].adapter_type == TCouplerType::NoCoupler ? "" : "[A]" ) }; auto const *connected { m_input.vehicle->MoverParameters->Neighbours[ Side ].vehicle }; @@ -1041,7 +1041,7 @@ debug_panel::update_vehicle_brake() const { std::string brakedelay; - std::vector> delays { + const std::vector> delays { { bdelay_G, "G" }, { bdelay_P, "P" }, { bdelay_R, "R" }, @@ -1285,7 +1285,7 @@ debug_panel::update_section_scantable( std::vector &Output ) { #ifdef WITH_UART void debug_panel::update_section_uart( std::vector &Output ) { - uart_status *status = &UartStatus; + const uart_status *status = &UartStatus; Output.emplace_back( ("Port: " + status->port_name).c_str(), @@ -1296,7 +1296,7 @@ debug_panel::update_section_uart( std::vector &Output ) { Global.UITextColor ); if(status->is_connected) { - std::string synctext = status->is_synced ? "SYNCED" : "NOT SYNCED"; + const std::string synctext = status->is_synced ? "SYNCED" : "NOT SYNCED"; Output.emplace_back(("CONNECTED, " + synctext).c_str(), Global.UITextColor); } else { Output.emplace_back("* NOT CONNECTED *", Global.UITextColor); @@ -1595,7 +1595,7 @@ debug_panel::render_section_settings() { if (simulation::Train) { float val = simulation::Train->get_radiovolume(); if( ImGui::SliderFloat( ( std::to_string( static_cast( val * 100 ) ) + "%###volumeradio" ).c_str(), &val, 0.0f, 1.0f, "Vehicle radio volume" ) ) { - command_relay relay; + const command_relay relay; relay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); } } @@ -1624,7 +1624,7 @@ transcripts_panel::render() { if( false == is_open ) { return; } if( true == text_lines.empty() ) { return; } - auto flags = + const auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | ( size.x > 0 ? ImGuiWindowFlags_NoResize : 0 ); diff --git a/application/editormode.cpp b/application/editormode.cpp index e8a33283..b73526e9 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -345,7 +345,7 @@ void editor_mode::add_to_hierarchy(scene::basic_node *node) void editor_mode::remove_from_hierarchy(scene::basic_node *node) { if (!node) return; - auto it = scene::Hierarchy.find(node->uuid.to_string()); + const auto it = scene::Hierarchy.find(node->uuid.to_string()); if (it != scene::Hierarchy.end()) scene::Hierarchy.erase(it); } @@ -353,7 +353,7 @@ void editor_mode::remove_from_hierarchy(scene::basic_node *node) scene::basic_node* editor_mode::find_in_hierarchy(const std::string &uuid_str) { if (uuid_str.empty()) return nullptr; - auto it = scene::Hierarchy.find(uuid_str); + const auto it = scene::Hierarchy.find(uuid_str); return it != scene::Hierarchy.end() ? it->second : nullptr; } @@ -389,7 +389,7 @@ void editor_mode::push_snapshot(scene::basic_node *node, EditorSnapshot::Action snap.position = node->location(); snap.uuid = node->uuid; - if (auto *model = dynamic_cast(node)) + if (const auto *model = dynamic_cast(node)) { snap.rotation = model->Angles(); snap.scale = model->Scale(); @@ -417,7 +417,7 @@ void editor_mode::push_snapshot(scene::basic_node *node, EditorSnapshot::Action glm::dvec3 editor_mode::clamp_mouse_offset_to_max(const glm::dvec3 &offset) { - double len = glm::length(offset); + const double len = glm::length(offset); if (len <= static_cast(kMaxPlacementDistance) || len <= 1e-6) return offset; return glm::normalize(offset) * static_cast(kMaxPlacementDistance); @@ -681,7 +681,7 @@ bool editor_mode::update() { auto const terrains = active_terrains(); bool any_dirty = false; - for (editor_terrain *terrain : terrains) + for (const editor_terrain *terrain : terrains) if (terrain->dirty()) { any_dirty = true; @@ -910,7 +910,7 @@ void editor_mode::render_terrain_ui() editor_terrain *editor_mode::terrain_at(double X, double Z) { - for (auto &terrain : m_terrains) + for (const auto &terrain : m_terrains) if (terrain && terrain->contains(X, Z)) return terrain.get(); double const size = chunk_grid_size(); @@ -1402,7 +1402,7 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in Global.ctrlState = Mods & GLFW_MOD_CONTROL ? true : false; Global.altState = Mods & GLFW_MOD_ALT ? true : false; #endif - bool anyModifier = Mods & (GLFW_MOD_SHIFT | GLFW_MOD_CONTROL | GLFW_MOD_ALT); + const bool anyModifier = Mods & (GLFW_MOD_SHIFT | GLFW_MOD_CONTROL | GLFW_MOD_ALT); // first give UI a chance to handle the key if (!anyModifier && m_userinterface->on_key(Key, Action)) @@ -1473,14 +1473,14 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in case GLFW_KEY_DELETE: if (is_press(Action)) { - auto model = dynamic_cast(m_node); + const auto model = dynamic_cast(m_node); if (model) { // record deletion for undo (serialize full node) std::string as_text; model->export_as_text(as_text); - std::string debug = "Deleting node: " + as_text + "\nSerialized data:\n"; + const std::string debug = "Deleting node: " + as_text + "\nSerialized data:\n"; push_snapshot(model, EditorSnapshot::Action::Delete, as_text); WriteLog(debug, logtype::generic); @@ -1654,7 +1654,7 @@ void editor_mode::render_change_history(){ m_max_history_size = std::max(0, maxsize); if ((int)m_history.size() > m_max_history_size && m_max_history_size >= 0) { - auto remove_count = (int)m_history.size() - m_max_history_size; + const auto remove_count = (int)m_history.size() - m_max_history_size; m_history.erase(m_history.begin(), m_history.begin() + remove_count); // adjust selected index if (m_selected_history_idx >= (int)m_history.size()) @@ -1705,8 +1705,8 @@ void editor_mode::render_change_history(){ { if (m_selected_history_idx >= 0 && m_selected_history_idx < (int)m_history.size()) { - int target = m_selected_history_idx; - int undoCount = (int)m_history.size() - 1 - target; + const int target = m_selected_history_idx; + const int undoCount = (int)m_history.size() - 1 - target; for (int k = 0; k < undoCount; ++k) undo_last(); m_selected_history_idx = -1; diff --git a/application/editoruilayer.cpp b/application/editoruilayer.cpp index d87dd8fa..81f8ba6e 100644 --- a/application/editoruilayer.cpp +++ b/application/editoruilayer.cpp @@ -44,7 +44,7 @@ void editor_ui::update() m_itempropertiespanel.update(m_node); m_functionspanel.update(m_node); - auto ptr = get_active_node_template(true); + const auto ptr = get_active_node_template(true); if (ptr) m_brushobjects.update(*ptr); } diff --git a/application/editoruipanels.cpp b/application/editoruipanels.cpp index f15f791e..7727a24f 100644 --- a/application/editoruipanels.cpp +++ b/application/editoruipanels.cpp @@ -272,7 +272,7 @@ void itemproperties_panel::render() return; } - auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); + const auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); if (size.x > 0) { @@ -383,7 +383,7 @@ brush_object_list::brush_object_list(std::string const &Name, bool const Isopen) bool brush_object_list::VectorGetter(void *data, int idx, const char **out_text) { - auto *vec = static_cast *>(data); + const auto *vec = static_cast *>(data); if (idx < 0 || idx >= vec->size()) return false; @@ -416,7 +416,7 @@ void brush_object_list::render() return; } - auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); + const auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); if (ImGui::Begin("Brush random set", nullptr, flags)) { ImGui::SliderFloat("Spacing", &spacing, 0.1f, 20.0f, "%.1f m"); @@ -513,7 +513,7 @@ void nodebank_panel::render() return; } - auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); + const auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); if (size.x > 0) { @@ -639,7 +639,7 @@ void functions_panel::render() return; } - auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); + const auto flags = ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoCollapse | (size.x > 0 ? ImGuiWindowFlags_NoResize : 0); if (size.x > 0) { diff --git a/application/scenarioloaderuilayer.cpp b/application/scenarioloaderuilayer.cpp index e5c02cb8..b0aa5690 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -23,7 +23,7 @@ size_t utf8_char_count(const std::string& str) size_t count = 0; for (size_t i = 0; i < str.length(); ) { - unsigned char c = static_cast(str[i]); + const unsigned char c = static_cast(str[i]); if ((c & 0x80) == 0x00) { // 1-byte character (ASCII) @@ -108,7 +108,7 @@ std::vector scenarioloader_ui::get_random_trivia() size_t current_chars = 0; for (size_t i = 0; i < str.length() && current_chars < char_count; ) { - unsigned char c = static_cast(str[i]); + const unsigned char c = static_cast(str[i]); if ((c & 0x80) == 0x00) { i += 1; @@ -137,8 +137,8 @@ std::vector scenarioloader_ui::get_random_trivia() // UTF-8 safe find space within character limit auto find_space_before_char_count = [&](const std::string& str, size_t max_chars) -> size_t { - size_t byte_limit = get_byte_pos_for_char_count(str, max_chars); - size_t search_limit = std::min(str.length(), byte_limit); + const size_t byte_limit = get_byte_pos_for_char_count(str, max_chars); + const size_t search_limit = std::min(str.length(), byte_limit); // Search backwards for a space that's not in the middle of a UTF-8 sequence for (int idx = static_cast(search_limit); idx >= 0; idx--) { diff --git a/application/uilayer.cpp b/application/uilayer.cpp index 8dd993ed..f23b9789 100644 --- a/application/uilayer.cpp +++ b/application/uilayer.cpp @@ -501,7 +501,7 @@ void ui_layer::clear_panels() void ui_layer::add_owned_panel(ui_panel *Panel) { - for (auto &panel : m_ownedpanels) + for (const auto &panel : m_ownedpanels) if (panel->name() == Panel->name()) { delete Panel; @@ -516,7 +516,7 @@ void ui_layer::render_panels() { for (auto *panel : m_panels) panel->render(); - for (auto &panel : m_ownedpanels) + for (const auto &panel : m_ownedpanels) panel->render(); if (m_imgui_demo) @@ -540,7 +540,7 @@ void ui_layer::render_menu_contents() bool flag = DebugModeFlag; if (ImGui::MenuItem(STR_C("Debug mode"), nullptr, &flag)) { - command_relay relay; + const command_relay relay; relay.post(user_command::debugtoggle, 0.0, 0.0, GLFW_RELEASE, 0); } ImGui::MenuItem(STR_C("Quit"), "F10", &m_quit_active); @@ -606,21 +606,21 @@ void ui_layer::render_background() if (m_background == 0) return; - ImVec2 display_size = ImGui::GetIO().DisplaySize; + const ImVec2 display_size = ImGui::GetIO().DisplaySize; ITexture &tex = GfxRenderer->Texture(m_background); tex.create(); - float tex_w = (float)tex.get_width(); - float tex_h = (float)tex.get_height(); + const float tex_w = (float)tex.get_width(); + const float tex_h = (float)tex.get_height(); // skalowanie "cover" – wypełnia cały ekran, zachowując proporcje - float scale_factor = display_size.x / display_size.y > tex_w / tex_h ? display_size.x / tex_w : display_size.y / tex_h; + const float scale_factor = display_size.x / display_size.y > tex_w / tex_h ? display_size.x / tex_w : display_size.y / tex_h; - ImVec2 image_size(tex_w * scale_factor, tex_h * scale_factor); + const ImVec2 image_size(tex_w * scale_factor, tex_h * scale_factor); // wyśrodkowanie obrazka - ImVec2 start_position((display_size.x - image_size.x) * 0.5f, (display_size.y - image_size.y) * 0.5f); - ImVec2 end_position(start_position.x + image_size.x, start_position.y + image_size.y); + const ImVec2 start_position((display_size.x - image_size.x) * 0.5f, (display_size.y - image_size.y) * 0.5f); + const ImVec2 end_position(start_position.x + image_size.x, start_position.y + image_size.y); // obrazek jest odwrócony w pionie – odwracamy UV ImGui::GetBackgroundDrawList()->AddImage(reinterpret_cast(tex.get_id()), start_position, end_position, ImVec2(0, 1), ImVec2(1, 0)); diff --git a/audio/audio.cpp b/audio/audio.cpp index 6bb1b4e9..7c558674 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -25,7 +25,7 @@ openal_buffer::openal_buffer( std::string const &Filename ) : SF_INFO si; si.format = 0; - std::string file = Filename; + const std::string file = Filename; WriteLog("sound: loading file: " + file); @@ -36,7 +36,7 @@ openal_buffer::openal_buffer( std::string const &Filename ) : sf_command(sf, SFC_SET_NORM_FLOAT, nullptr, SF_TRUE); - auto fbuf = new float[si.frames * si.channels]; + const auto fbuf = new float[si.frames * si.channels]; if (sf_readf_float(sf, fbuf, si.frames) != si.frames) throw std::runtime_error("sound: incomplete file"); @@ -47,7 +47,7 @@ openal_buffer::openal_buffer( std::string const &Filename ) : if (si.channels != 1) WriteLog("sound: warning: mixing multichannel file to mono"); - auto buf = new int16_t[si.frames]; + const auto buf = new int16_t[si.frames]; for (size_t i = 0; i < si.frames; i++) { float accum = 0; diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index bd0a0e49..4bbf20d3 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -529,7 +529,7 @@ openal_renderer::init_caps() { ::alcGetIntegerv( m_device, ALC_MINOR_VERSION, 1, &versionminor ); auto const oalversion { std::to_string( versionmajor ) + "." + std::to_string( versionminor ) }; - std::string al_renderer((char *)::alcGetString( m_device, ALC_DEVICE_SPECIFIER )); + const std::string al_renderer((char *)::alcGetString( m_device, ALC_DEVICE_SPECIFIER )); crashreport_add_info("openal_renderer", al_renderer); crashreport_add_info("openal_version", oalversion); @@ -539,7 +539,7 @@ openal_renderer::init_caps() { WriteLog( "Supported extensions: " + std::string{ (char *)::alcGetString( m_device, ALC_EXTENSIONS ) } ); - ALCint attr[3] = { ALC_MONO_SOURCES, Global.audio_max_sources, 0 }; // request more sounds + const ALCint attr[3] = { ALC_MONO_SOURCES, Global.audio_max_sources, 0 }; // request more sounds m_context = ::alcCreateContext( m_device, attr ); if( m_context == nullptr ) { diff --git a/audio/sound.cpp b/audio/sound.cpp index 0ff2eff9..7b054b1a 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -85,7 +85,7 @@ sound_source::deserialize( cParser &Input, sound_type const Legacytype, int cons m_soundchunks.back().second.fadeout = std::max( Chunkrange, m_soundchunks.back().second.threshold ); // m_soundchunks.back().second.fadeout = m_soundchunks.back().second.threshold; // test if the chunk table contains any actual samples while at it - for( auto &soundchunk : m_soundchunks ) { + for (const auto &soundchunk : m_soundchunks ) { if( soundchunk.first.buffer != null_handle ) { m_soundchunksempty = false; break; @@ -247,7 +247,7 @@ sound_source::deserialize_mapping( cParser &Input ) { { "external", sound_placement::external }, { "custom", sound_placement::custom }, { "general", sound_placement::general } }; - auto lookup{ placements.find( value ) }; + const auto lookup{ placements.find( value ) }; if( lookup != placements.end() ) { m_placement = lookup->second; } @@ -269,7 +269,7 @@ sound_source::deserialize_mapping( cParser &Input ) { { "amplitudeoffset:", m_amplitudeoffset }, { "range:", m_range } }; - auto lookup { properties.find( key ) }; + const auto lookup { properties.find( key ) }; if( lookup != properties.end() ) { Input.getTokens( 1, false, "\n\r\t ,;" ); Input >> lookup->second; @@ -802,7 +802,7 @@ sound_source::update_crossfade( sound_handle const Chunk ) { // chunks other than the first can have fadein auto const fadeinwidth { chunkdata.threshold - chunkdata.fadein }; if( soundpoint < chunkdata.threshold ) { - float lineargain = + const float lineargain = std::lerp( 0.f, 1.f, std::clamp( @@ -822,7 +822,7 @@ sound_source::update_crossfade( sound_handle const Chunk ) { auto const fadeoutwidth { chunkdata.fadeout - m_soundchunks[ chunkindex + 1 ].second.fadein }; auto const fadeoutstart { chunkdata.fadeout - fadeoutwidth }; if( soundpoint > fadeoutstart ) { - float lineargain = + const float lineargain = std::lerp( 0.f, 1.f, std::clamp( @@ -973,7 +973,7 @@ sound_source::update_soundproofing() { 4 ) : // free roam view listenervehicle->MoverParameters->CabOccupied ) }; // some internal view so we can be sure listener isn't a nullptr // location-based gain factor: - std::uintptr_t soundproofingstamp = + const std::uintptr_t soundproofingstamp = reinterpret_cast( listenervehicle ) + ( listenervehicle ? occupiedcab : diff --git a/environment/moon.cpp b/environment/moon.cpp index 0cd4ce7d..550c56e0 100644 --- a/environment/moon.cpp +++ b/environment/moon.cpp @@ -107,14 +107,14 @@ void cMoon::move() { if( m_observer.minute >= 0 ) { localtime.wMinute = m_observer.minute; } if( m_observer.second >= 0 ) { localtime.wSecond = m_observer.second; } - double localut = + const double localut = localtime.wHour + localtime.wMinute / 60.0 // too low resolution, noticeable skips + localtime.wSecond / 3600.0; // good enough in normal circumstances /* - + localtime.wMilliseconds / 3600000.0; // for really smooth movement -*/ - double daynumber + + localtime.wMilliseconds / 3600000.0; // for really smooth movement + */ + const double daynumber = 367 * localtime.wYear - 7 * ( localtime.wYear + ( localtime.wMonth + 9 ) / 12 ) / 4 + 275 * localtime.wMonth / 9 @@ -128,7 +128,7 @@ void cMoon::move() { // obliquity of the ecliptic m_body.oblecl = clamp_circular( 23.4393 - 3.563e-7 * daynumber ); // moon parameters - double longascnode = clamp_circular( 125.1228 - 0.0529538083 * daynumber ); // N, degrees + const double longascnode = clamp_circular( 125.1228 - 0.0529538083 * daynumber ); // N, degrees double const inclination = 5.1454; // i, degrees double const mndistance = 60.2666; // a, in earth radii // argument of perigee @@ -189,8 +189,8 @@ void cMoon::move() { m_body.declin = radtodeg * std::asin( std::sin (m_body.oblecl * degtorad) * std::sin(m_body.eclong * degtorad) ); // right ascension - double top = std::cos( degtorad * m_body.oblecl ) * std::sin( degtorad * m_body.eclong ); - double bottom = std::cos( degtorad * m_body.eclong ); + const double top = std::cos( degtorad * m_body.oblecl ) * std::sin( degtorad * m_body.eclong ); + const double bottom = std::cos( degtorad * m_body.eclong ); m_body.rascen = clamp_circular( radtodeg * std::atan2( top, bottom ) ); // Greenwich mean sidereal time @@ -213,11 +213,11 @@ void cMoon::move() { double cz; // cosine of the solar zenith angle - double tdatcd = std::cos( degtorad * m_body.declin ); - double tdatch = std::cos( degtorad * m_body.hrang ); - double tdatcl = std::cos( degtorad * m_observer.latitude ); - double tdatsd = std::sin( degtorad * m_body.declin ); - double tdatsl = std::sin( degtorad * m_observer.latitude ); + const double tdatcd = std::cos( degtorad * m_body.declin ); + const double tdatch = std::cos( degtorad * m_body.hrang ); + const double tdatcl = std::cos( degtorad * m_observer.latitude ); + const double tdatsd = std::sin( degtorad * m_body.declin ); + const double tdatsl = std::sin( degtorad * m_observer.latitude ); cz = tdatsd * tdatsl + tdatcd * tdatcl * tdatch; @@ -271,15 +271,15 @@ void cMoon::irradiance() { static double degtorad = 0.0174532925; // converts from degrees to radians m_body.dayang = ( simulation::Time.year_day() - 1 ) * 360.0 / 365.0; - double sd = sin( degtorad * m_body.dayang ); // sine of the day angle - double cd = cos( degtorad * m_body.dayang ); // cosine of the day angle or delination + const double sd = sin( degtorad * m_body.dayang ); // sine of the day angle + const double cd = cos( degtorad * m_body.dayang ); // cosine of the day angle or delination m_body.erv = 1.000110 + 0.034221*cd + 0.001280*sd; - double d2 = 2.0 * m_body.dayang; - double c2 = cos( degtorad * d2 ); - double s2 = sin( degtorad * d2 ); + const double d2 = 2.0 * m_body.dayang; + const double c2 = cos( degtorad * d2 ); + const double s2 = sin( degtorad * d2 ); m_body.erv += 0.000719*c2 + 0.000077*s2; - double solcon = 1367.0; // Solar constant, 1367 W/sq m + const double solcon = 1367.0; // Solar constant, 1367 W/sq m m_body.coszen = cos( degtorad * m_body.zenref ); if( m_body.coszen > 0.0 ) { @@ -294,12 +294,12 @@ void cMoon::irradiance() { void cMoon::phase() { - SYSTEMTIME lt = simulation::Time.data(); + const SYSTEMTIME lt = simulation::Time.data(); if (lt.wMonth == 5 && lt.wDay == 4) //May the forth be with you! m_phase = 50; else { // calculate moon's age in days from new moon - float ip = normalize( ( simulation::Time.julian_day() - 2451550.1f ) / 29.530588853f ); + const float ip = normalize( ( simulation::Time.julian_day() - 2451550.1f ) / 29.530588853f ); m_phase = ip * 29.53f; } } diff --git a/environment/sun.cpp b/environment/sun.cpp index 1ecd94ed..7d46d4dc 100644 --- a/environment/sun.cpp +++ b/environment/sun.cpp @@ -112,14 +112,14 @@ void cSun::move() { if( m_observer.minute >= 0 ) { localtime.wMinute = m_observer.minute; } if( m_observer.second >= 0 ) { localtime.wSecond = m_observer.second; } - double localut = + const double localut = localtime.wHour + localtime.wMinute / 60.0 // too low resolution, noticeable skips + localtime.wSecond / 3600.0; // good enough in normal circumstances /* - + localtime.wMilliseconds / 3600000.0; // for really smooth movement -*/ - double daynumber = + + localtime.wMilliseconds / 3600000.0; // for really smooth movement + */ + const double daynumber = 367 * localtime.wYear - 7 * ( localtime.wYear + ( localtime.wMonth + 9 ) / 12 ) / 4 + 275 * localtime.wMonth / 9 @@ -168,8 +168,8 @@ void cSun::move() { m_body.declin = radtodeg * std::asin( std::sin( m_body.oblecl * degtorad ) * std::sin( m_body.eclong * degtorad ) ); // right ascension - double top = std::cos( degtorad * m_body.oblecl ) * std::sin( degtorad * m_body.eclong ); - double bottom = std::cos( degtorad * m_body.eclong ); + const double top = std::cos( degtorad * m_body.oblecl ) * std::sin( degtorad * m_body.eclong ); + const double bottom = std::cos( degtorad * m_body.eclong ); m_body.rascen = clamp_circular( radtodeg * std::atan2( top, bottom ) ); @@ -187,11 +187,11 @@ void cSun::move() { double cz; // cosine of the solar zenith angle - double tdatcd = std::cos( degtorad * m_body.declin ); - double tdatch = std::cos( degtorad * m_body.hrang ); - double tdatcl = std::cos( degtorad * m_observer.latitude ); - double tdatsd = std::sin( degtorad * m_body.declin ); - double tdatsl = std::sin( degtorad * m_observer.latitude ); + const double tdatcd = std::cos( degtorad * m_body.declin ); + const double tdatch = std::cos( degtorad * m_body.hrang ); + const double tdatcl = std::cos( degtorad * m_observer.latitude ); + const double tdatsd = std::sin( degtorad * m_body.declin ); + const double tdatsl = std::sin( degtorad * m_observer.latitude ); cz = tdatsd * tdatsl + tdatcd * tdatcl * tdatch; @@ -242,15 +242,15 @@ void cSun::refract() { void cSun::irradiance() { m_body.dayang = ( simulation::Time.year_day() - 1 ) * 360.0 / 365.0; - double sd = std::sin( glm::radians( m_body.dayang ) ); // sine of the day angle - double cd = std::cos( glm::radians( m_body.dayang ) ); // cosine of the day angle or delination + const double sd = std::sin( glm::radians( m_body.dayang ) ); // sine of the day angle + const double cd = std::cos( glm::radians( m_body.dayang ) ); // cosine of the day angle or delination m_body.erv = 1.000110 + 0.034221*cd + 0.001280*sd; - double d2 = 2.0 * m_body.dayang; - double c2 = std::cos( glm::radians( d2 ) ); - double s2 = std::sin( glm::radians( d2 ) ); + const double d2 = 2.0 * m_body.dayang; + const double c2 = std::cos( glm::radians( d2 ) ); + const double s2 = std::sin( glm::radians( d2 ) ); m_body.erv += 0.000719*c2 + 0.000077*s2; - double solcon = 1367.0; // Solar constant, 1367 W/sq m + const double solcon = 1367.0; // Solar constant, 1367 W/sq m m_body.coszen = std::cos( glm::radians( m_body.zenref ) ); if( m_body.coszen > 0.0 ) { diff --git a/gl/buffer.cpp b/gl/buffer.cpp index 8b8bd486..0fd37aee 100644 --- a/gl/buffer.cpp +++ b/gl/buffer.cpp @@ -82,7 +82,7 @@ void gl::buffer::download(targets target, void *data, int offset, GLsizeiptr siz } else { - void *glbuf = glMapBufferRange(glenum_target(target), offset, size, GL_MAP_READ_BIT); + const void *glbuf = glMapBufferRange(glenum_target(target), offset, size, GL_MAP_READ_BIT); memcpy(data, glbuf, size); glUnmapBuffer(glenum_target(target)); } diff --git a/gl/fence.cpp b/gl/fence.cpp index b6db88f7..f67030ed 100644 --- a/gl/fence.cpp +++ b/gl/fence.cpp @@ -15,6 +15,6 @@ bool gl::fence::is_signalled() { // glClientWaitSync is faster than glGetSynciv. glGetSynciv probably tries to synchronize cpu and gpu // https://stackoverflow.com/questions/34601376/which-to-use-for-opengl-client-side-waiting-glgetsynciv-vs-glclientwaitsync - GLenum r = glClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, 1); + const GLenum r = glClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, 1); return r == GL_ALREADY_SIGNALED || r == GL_CONDITION_SATISFIED; } diff --git a/gl/framebuffer.cpp b/gl/framebuffer.cpp index af1f63de..098d99b3 100644 --- a/gl/framebuffer.cpp +++ b/gl/framebuffer.cpp @@ -87,7 +87,7 @@ void gl::framebuffer::blit(framebuffer *src, framebuffer *dst, int sx, int sy, i if (mask & GL_COLOR_BUFFER_BIT) { - int attachment_n = attachment - GL_COLOR_ATTACHMENT0; + const int attachment_n = attachment - GL_COLOR_ATTACHMENT0; { GLenum outputs[8] = { GL_NONE }; @@ -111,7 +111,7 @@ void gl::framebuffer::blit(framebuffer *src, framebuffer *dst, int sx, int sy, i void gl::framebuffer::setup_drawing(int attachments) { bind(); - GLenum a[8] = + const GLenum a[8] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, diff --git a/gl/pbo.cpp b/gl/pbo.cpp index 6923e09d..37505916 100644 --- a/gl/pbo.cpp +++ b/gl/pbo.cpp @@ -3,7 +3,7 @@ void gl::pbo::request_read(int x, int y, int lx, int ly, int pixsize, GLenum format, GLenum type) { - int s = lx * ly * pixsize; + const int s = lx * ly * pixsize; if (s != size) allocate(PIXEL_PACK_BUFFER, s, GL_STREAM_DRAW); size = s; @@ -25,7 +25,7 @@ bool gl::pbo::read_data(int lx, int ly, void *data, int pixsize) if (!data_ready) return false; - int s = lx * ly * pixsize; + const int s = lx * ly * pixsize; if (s != size) return false; diff --git a/gl/shader.cpp b/gl/shader.cpp index e2a5a034..3df2433d 100644 --- a/gl/shader.cpp +++ b/gl/shader.cpp @@ -41,7 +41,7 @@ bool has_gl_extension(char const *name) { GLint count = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &count); for (GLint i = 0; i < count; ++i) { - auto ext = reinterpret_cast(glGetStringi(GL_EXTENSIONS, i)); + const auto ext = reinterpret_cast(glGetStringi(GL_EXTENSIONS, i)); if (ext != nullptr && std::strcmp(ext, name) == 0) { return true; } @@ -72,11 +72,11 @@ void gl::shader::expand_includes(std::string &str, const std::string &basedir) { size_t start_pos = 0; - std::string magic = "#include"; + const std::string magic = "#include"; while ((start_pos = str.find(magic, start_pos)) != str.npos) { - size_t fp = str.find('<', start_pos); - size_t fe = str.find('>', start_pos); + const size_t fp = str.find('<', start_pos); + const size_t fe = str.find('>', start_pos); if (fp == str.npos || fe == str.npos) return; @@ -308,7 +308,7 @@ gl::shader::shader(const std::string &filename) { name = filename; - std::pair source = process_source(filename, "shaders/"); + const std::pair source = process_source(filename, "shaders/"); const GLchar *cstr = source.second.c_str(); @@ -341,8 +341,8 @@ void gl::program::init() for (auto it : texture_conf) { - shader::texture_entry &e = it.second; - GLuint loc = glGetUniformLocation(*this, it.first.c_str()); + const shader::texture_entry &e = it.second; + const GLuint loc = glGetUniformLocation(*this, it.first.c_str()); glUniform1i(loc, e.id); } diff --git a/imgui/ImGuizmo.cpp b/imgui/ImGuizmo.cpp index b92d056d..8d4399c6 100644 --- a/imgui/ImGuizmo.cpp +++ b/imgui/ImGuizmo.cpp @@ -153,7 +153,7 @@ namespace ImGuizmo void Normalize(const float* a, float* r) { - float il = 1.f / (sqrtf(Dot(a, a)) + FLT_EPSILON); + const float il = 1.f / (sqrtf(Dot(a, a)) + FLT_EPSILON); r[0] = a[0] * il; r[1] = a[1] * il; r[2] = a[2] * il; @@ -473,7 +473,7 @@ namespace ImGuizmo if (affine) { det = GetDeterminant(); - float s = 1 / det; + const float s = 1 / det; m[0][0] = (srcMatrix.m[1][1] * srcMatrix.m[2][2] - srcMatrix.m[1][2] * srcMatrix.m[2][1]) * s; m[0][1] = (srcMatrix.m[2][1] * srcMatrix.m[0][2] - srcMatrix.m[2][2] * srcMatrix.m[0][1]) * s; m[0][2] = (srcMatrix.m[0][1] * srcMatrix.m[1][2] - srcMatrix.m[0][2] * srcMatrix.m[1][1]) * s; @@ -552,7 +552,7 @@ namespace ImGuizmo det = src[0] * m16[0] + src[1] * m16[1] + src[2] * m16[2] + src[3] * m16[3]; // calculate matrix inverse - float invdet = 1 / det; + const float invdet = 1 / det; for (int j = 0; j < 16; ++j) { m16[j] *= invdet; @@ -564,27 +564,27 @@ namespace ImGuizmo void matrix_t::RotationAxis(const vec_t& axis, float angle) { - float length2 = axis.LengthSq(); + const float length2 = axis.LengthSq(); if (length2 < FLT_EPSILON) { SetToIdentity(); return; } - vec_t n = axis * (1.f / sqrtf(length2)); - float s = sinf(angle); - float c = cosf(angle); - float k = 1.f - c; + const vec_t n = axis * (1.f / sqrtf(length2)); + const float s = sinf(angle); + const float c = cosf(angle); + const float k = 1.f - c; - float xx = n.x * n.x * k + c; - float yy = n.y * n.y * k + c; - float zz = n.z * n.z * k + c; - float xy = n.x * n.y * k; - float yz = n.y * n.z * k; - float zx = n.z * n.x * k; - float xs = n.x * s; - float ys = n.y * s; - float zs = n.z * s; + const float xx = n.x * n.x * k + c; + const float yy = n.y * n.y * k + c; + const float zz = n.z * n.z * k + c; + const float xy = n.x * n.y * k; + const float yz = n.y * n.z * k; + const float zx = n.z * n.x * k; + const float xs = n.x * s; + const float ys = n.y * s; + const float zs = n.z * s; m[0][0] = xx; m[0][1] = xy + zs; @@ -782,7 +782,7 @@ namespace ImGuizmo static void ComputeCameraRay(vec_t& rayOrigin, vec_t& rayDir, ImVec2 position = ImVec2(gContext.mX, gContext.mY), ImVec2 size = ImVec2(gContext.mWidth, gContext.mHeight)) { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); matrix_t mViewProjInverse; mViewProjInverse.Inverse(gContext.mViewMat * gContext.mProjectionMat); @@ -819,7 +819,7 @@ namespace ImGuizmo vec_t clipSpaceAxis = endOfSegment - startOfSegment; clipSpaceAxis.y /= gContext.mDisplayRatio; - float segmentLengthInClipSpace = sqrtf(clipSpaceAxis.x * clipSpaceAxis.x + clipSpaceAxis.y * clipSpaceAxis.y); + const float segmentLengthInClipSpace = sqrtf(clipSpaceAxis.x * clipSpaceAxis.x + clipSpaceAxis.y * clipSpaceAxis.y); return segmentLengthInClipSpace; } @@ -840,19 +840,19 @@ namespace ImGuizmo segB.y /= gContext.mDisplayRatio; vec_t segAOrtho = makeVect(-segA.y, segA.x); segAOrtho.Normalize(); - float dt = segAOrtho.Dot3(segB); - float surface = sqrtf(segA.x * segA.x + segA.y * segA.y) * fabsf(dt); + const float dt = segAOrtho.Dot3(segB); + const float surface = sqrtf(segA.x * segA.x + segA.y * segA.y) * fabsf(dt); return surface; } inline vec_t PointOnSegment(const vec_t& point, const vec_t& vertPos1, const vec_t& vertPos2) { - vec_t c = point - vertPos1; + const vec_t c = point - vertPos1; vec_t V; V.Normalize(vertPos2 - vertPos1); - float d = (vertPos2 - vertPos1).Length(); - float t = V.Dot3(c); + const float d = (vertPos2 - vertPos1).Length(); + const float t = V.Dot3(c); if (t < 0.f) { @@ -869,8 +869,8 @@ namespace ImGuizmo static float IntersectRayPlane(const vec_t& rOrigin, const vec_t& rVector, const vec_t& plan) { - float numer = plan.Dot3(rOrigin) - plan.w; - float denom = plan.Dot3(rVector); + const float numer = plan.Dot3(rOrigin) - plan.w; + const float denom = plan.Dot3(rVector); if (fabsf(denom) < FLT_EPSILON) // normal is orthogonal to vector, cant intersect { @@ -924,7 +924,7 @@ namespace ImGuizmo ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size); ImGui::SetNextWindowPos(ImGui::GetMainViewport()->Pos); #else - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); ImGui::SetNextWindowSize(io.DisplaySize); ImGui::SetNextWindowPos(ImVec2(0, 0)); #endif @@ -1027,10 +1027,10 @@ namespace ImGuizmo vec_t rightViewInverse = viewInverse.v.right; rightViewInverse.TransformVector(gContext.mModelInverse); - float rightLength = GetSegmentLengthClipSpace(makeVect(0.f, 0.f), rightViewInverse); + const float rightLength = GetSegmentLengthClipSpace(makeVect(0.f, 0.f), rightViewInverse); gContext.mScreenFactor = gContext.mGizmoSizeClipSpace / rightLength; - ImVec2 centerSSpace = worldToPos(makeVect(0.f, 0.f), gContext.mMVP); + const ImVec2 centerSSpace = worldToPos(makeVect(0.f, 0.f), gContext.mMVP); gContext.mScreenSquareCenter = centerSSpace; gContext.mScreenSquareMin = ImVec2(centerSSpace.x - 10.f, centerSSpace.y - 10.f); gContext.mScreenSquareMax = ImVec2(centerSSpace.x + 10.f, centerSSpace.y + 10.f); @@ -1100,28 +1100,28 @@ namespace ImGuizmo else { // new method - float lenDir = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis); - float lenDirMinus = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirAxis); + const float lenDir = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis); + const float lenDirMinus = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirAxis); - float lenDirPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneX); - float lenDirMinusPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneX); + const float lenDirPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneX); + const float lenDirMinusPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneX); - float lenDirPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneY); - float lenDirMinusPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneY); + const float lenDirPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneY); + const float lenDirMinusPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneY); // For readability - bool & allowFlip = gContext.mAllowAxisFlip; - float mulAxis = (allowFlip && lenDir < lenDirMinus&& fabsf(lenDir - lenDirMinus) > FLT_EPSILON) ? -1.f : 1.f; - float mulAxisX = (allowFlip && lenDirPlaneX < lenDirMinusPlaneX&& fabsf(lenDirPlaneX - lenDirMinusPlaneX) > FLT_EPSILON) ? -1.f : 1.f; - float mulAxisY = (allowFlip && lenDirPlaneY < lenDirMinusPlaneY&& fabsf(lenDirPlaneY - lenDirMinusPlaneY) > FLT_EPSILON) ? -1.f : 1.f; + const bool & allowFlip = gContext.mAllowAxisFlip; + const float mulAxis = (allowFlip && lenDir < lenDirMinus&& fabsf(lenDir - lenDirMinus) > FLT_EPSILON) ? -1.f : 1.f; + const float mulAxisX = (allowFlip && lenDirPlaneX < lenDirMinusPlaneX&& fabsf(lenDirPlaneX - lenDirMinusPlaneX) > FLT_EPSILON) ? -1.f : 1.f; + const float mulAxisY = (allowFlip && lenDirPlaneY < lenDirMinusPlaneY&& fabsf(lenDirPlaneY - lenDirMinusPlaneY) > FLT_EPSILON) ? -1.f : 1.f; dirAxis *= mulAxis; dirPlaneX *= mulAxisX; dirPlaneY *= mulAxisY; // for axis - float axisLengthInClipSpace = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis * gContext.mScreenFactor); + const float axisLengthInClipSpace = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis * gContext.mScreenFactor); - float paraSurf = GetParallelogram(makeVect(0.f, 0.f, 0.f), dirPlaneX * gContext.mScreenFactor, dirPlaneY * gContext.mScreenFactor); + const float paraSurf = GetParallelogram(makeVect(0.f, 0.f, 0.f), dirPlaneX * gContext.mScreenFactor, dirPlaneY * gContext.mScreenFactor); belowPlaneLimit = (paraSurf > 0.0025f); belowAxisLimit = (axisLengthInClipSpace > 0.02f); @@ -1141,8 +1141,8 @@ namespace ImGuizmo return; } - float modulo = fmodf(*value, snap); - float moduloRatio = fabsf(modulo) / snap; + const float modulo = fmodf(*value, snap); + const float moduloRatio = fabsf(modulo) / snap; if (moduloRatio < snapTension) { *value -= modulo; @@ -1163,12 +1163,12 @@ namespace ImGuizmo static float ComputeAngleOnPlan() { const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan); - vec_t localPos = Normalized(gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position); + const vec_t localPos = Normalized(gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position); vec_t perpendicularVector; perpendicularVector.Cross(gContext.mRotationVectorSource, gContext.mTranslationPlan); perpendicularVector.Normalize(); - float acosAngle = Clamp(Dot(localPos, gContext.mRotationVectorSource), -1.f, 1.f); + const float acosAngle = Clamp(Dot(localPos, gContext.mRotationVectorSource), -1.f, 1.f); float angle = acosf(acosAngle); angle *= (Dot(localPos, perpendicularVector) < 0.f) ? 1.f : -1.f; return angle; @@ -1202,27 +1202,27 @@ namespace ImGuizmo gContext.mRadiusSquareCenter = screenRotateSize * gContext.mHeight; - bool hasRSC = Intersects(op, ROTATE_SCREEN); - int circleMul = hasRSC ? 1 : 2; + const bool hasRSC = Intersects(op, ROTATE_SCREEN); + const int circleMul = hasRSC ? 1 : 2; for (int axis = 0; axis < 3; axis++) { if(!Intersects(op, static_cast(ROTATE_Z >> axis))) { continue; } - auto circlePos = (ImVec2*) alloca(sizeof(ImVec2) * (circleMul * halfCircleSegmentCount + 1)); + const auto circlePos = (ImVec2*) alloca(sizeof(ImVec2) * (circleMul * halfCircleSegmentCount + 1)); - float angleStart = atan2f(cameraToModelNormalized[(4 - axis) % 3], cameraToModelNormalized[(3 - axis) % 3]) + ZPI * 0.5f; + const float angleStart = atan2f(cameraToModelNormalized[(4 - axis) % 3], cameraToModelNormalized[(3 - axis) % 3]) + ZPI * 0.5f; for (int i = 0; i < circleMul * halfCircleSegmentCount + 1; i++) { - float ng = angleStart + circleMul * ZPI * ((float)i / (float)halfCircleSegmentCount); + const float ng = angleStart + circleMul * ZPI * ((float)i / (float)halfCircleSegmentCount); vec_t axisPos = makeVect(cosf(ng), sinf(ng), 0.f); vec_t pos = makeVect(axisPos[axis], axisPos[(axis + 1) % 3], axisPos[(axis + 2) % 3]) * gContext.mScreenFactor; circlePos[i] = worldToPos(pos, gContext.mMVP); } - float radiusAxis = sqrtf((ImLengthSqr(worldToPos(gContext.mModel.v.position, gContext.mViewProjection) - circlePos[0]))); + const float radiusAxis = sqrtf((ImLengthSqr(worldToPos(gContext.mModel.v.position, gContext.mViewProjection) - circlePos[0]))); if (radiusAxis > gContext.mRadiusSquareCenter) { gContext.mRadiusSquareCenter = radiusAxis; @@ -1242,7 +1242,7 @@ namespace ImGuizmo circlePos[0] = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); for (unsigned int i = 1; i < halfCircleSegmentCount; i++) { - float ng = gContext.mRotationAngle * ((float)(i - 1) / (float)(halfCircleSegmentCount - 1)); + const float ng = gContext.mRotationAngle * ((float)(i - 1) / (float)(halfCircleSegmentCount - 1)); matrix_t rotateVectorMatrix; rotateVectorMatrix.RotationAxis(gContext.mTranslationPlan, ng); vec_t pos; @@ -1253,7 +1253,7 @@ namespace ImGuizmo drawList->AddConvexPolyFilled(circlePos, halfCircleSegmentCount, IM_COL32(0xFF, 0x80, 0x10, 0x80)); drawList->AddPolyline(circlePos, halfCircleSegmentCount, IM_COL32(0xFF, 0x80, 0x10, 0xFF), true, 2); - ImVec2 destinationPosOnScreen = circlePos[1]; + const ImVec2 destinationPosOnScreen = circlePos[1]; char tmps[512]; ImFormatString(tmps, sizeof(tmps), rotationInfoMask[type - MT_ROTATE_X], (gContext.mRotationAngle / ZPI) * 180.f, gContext.mRotationAngle); drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps); @@ -1305,8 +1305,8 @@ namespace ImGuizmo // draw axis if (belowAxisLimit) { - bool hasTranslateOnAxis = Contains(op, static_cast(TRANSLATE_X << i)) ; - float markerScale = hasTranslateOnAxis ? 1.4f : 1.0f; + const bool hasTranslateOnAxis = Contains(op, static_cast(TRANSLATE_X << i)) ; + const float markerScale = hasTranslateOnAxis ? 1.4f : 1.0f; ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVP); ImVec2 worldDirSSpaceNoScale = worldToPos(dirAxis * markerScale * gContext.mScreenFactor, gContext.mMVP); ImVec2 worldDirSSpace = worldToPos((dirAxis * markerScale * scaleDisplay[i]) * gContext.mScreenFactor, gContext.mMVP); @@ -1335,8 +1335,8 @@ namespace ImGuizmo if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsScaleType(type)) { - //ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection); - ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); + // ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection); + const ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); /*vec_t dif(destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y); dif.Normalize(); dif *= 5.f; @@ -1345,8 +1345,8 @@ namespace ImGuizmo drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f); */ char tmps[512]; - //vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin; - int componentInfoIndex = (type - MT_SCALE_X) * 3; + // vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin; + const int componentInfoIndex = (type - MT_SCALE_X) * 3; ImFormatString(tmps, sizeof(tmps), scaleInfoMask[type - MT_SCALE_X], scaleDisplay[translationInfoIndex[componentInfoIndex]]); drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps); drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), IM_COL32_WHITE, tmps); @@ -1392,7 +1392,7 @@ namespace ImGuizmo // Arrow head begin ImVec2 dir(origin - worldDirSSpace); - float d = sqrtf(ImLengthSqr(dir)); + const float d = sqrtf(ImLengthSqr(dir)); dir /= d; // Normalize dir *= 6.0f; @@ -1425,8 +1425,8 @@ namespace ImGuizmo if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsTranslateType(type)) { - ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection); - ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); + const ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection); + const ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection); vec_t dif = { destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y, 0.f, 0.f }; dif.Normalize(); dif *= 5.f; @@ -1436,7 +1436,7 @@ namespace ImGuizmo char tmps[512]; vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin; - int componentInfoIndex = (type - MT_MOVE_X) * 3; + const int componentInfoIndex = (type - MT_MOVE_X) * 3; ImFormatString(tmps, sizeof(tmps), translationInfoMask[type - MT_MOVE_X], deltaInfo[translationInfoIndex[componentInfoIndex]], deltaInfo[translationInfoIndex[componentInfoIndex + 1]], deltaInfo[translationInfoIndex[componentInfoIndex + 2]]); drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps); drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), IM_COL32_WHITE, tmps); @@ -1716,7 +1716,7 @@ namespace ImGuizmo static int GetScaleType(OPERATION op) { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); int type = MT_NONE; // screen @@ -1762,11 +1762,11 @@ namespace ImGuizmo static int GetRotateType(OPERATION op) { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); int type = MT_NONE; - vec_t deltaScreen = { io.MousePos.x - gContext.mScreenSquareCenter.x, io.MousePos.y - gContext.mScreenSquareCenter.y, 0.f, 0.f }; - float dist = deltaScreen.Length(); + const vec_t deltaScreen = { io.MousePos.x - gContext.mScreenSquareCenter.x, io.MousePos.y - gContext.mScreenSquareCenter.y, 0.f, 0.f }; + const float dist = deltaScreen.Length(); if (Intersects(op, ROTATE_SCREEN) && dist >= (gContext.mRadiusSquareCenter - 1.0f) && dist < (gContext.mRadiusSquareCenter + 1.0f)) { type = MT_ROTATE_SCREEN; @@ -1820,7 +1820,7 @@ namespace ImGuizmo { return MT_NONE; } - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); int type = MT_NONE; // screen @@ -2440,8 +2440,8 @@ namespace ImGuizmo } } qsort(faces, cubeFaceCount, sizeof(CubeFace), [](void const* _a, void const* _b) { - auto a = (CubeFace*)_a; - auto b = (CubeFace*)_b; + const auto a = (CubeFace*)_a; + const auto b = (CubeFace*)_b; if (a->z < b->z) { return 1; @@ -2460,10 +2460,10 @@ namespace ImGuizmo void DrawGrid(const float* view, const float* projection, const float* matrix, const float gridSize) { - matrix_t viewProjection = *(matrix_t*)view * *(matrix_t*)projection; + const matrix_t viewProjection = *(matrix_t*)view * *(matrix_t*)projection; vec_t frustum[6]; ComputeFrustumPlanes(frustum, viewProjection.m16); - matrix_t res = *(matrix_t*)matrix * viewProjection; + const matrix_t res = *(matrix_t*)matrix * viewProjection; for (float f = -gridSize; f <= gridSize; f += 1.f) { @@ -2474,8 +2474,8 @@ namespace ImGuizmo bool visible = true; for (int i = 0; i < 6; i++) { - float dA = DistanceToPlane(ptA, frustum[i]); - float dB = DistanceToPlane(ptB, frustum[i]); + const float dA = DistanceToPlane(ptA, frustum[i]); + const float dB = DistanceToPlane(ptB, frustum[i]); if (dA < 0.f && dB < 0.f) { visible = false; @@ -2487,14 +2487,14 @@ namespace ImGuizmo } if (dA < 0.f) { - float len = fabsf(dA - dB); - float t = fabsf(dA) / len; + const float len = fabsf(dA - dB); + const float t = fabsf(dA) / len; ptA.Lerp(ptB, t); } if (dB < 0.f) { - float len = fabsf(dB - dA); - float t = fabsf(dB) / len; + const float len = fabsf(dB - dA); + const float t = fabsf(dB) / len; ptB.Lerp(ptA, t); } } diff --git a/imgui/imgui.cpp b/imgui/imgui.cpp index 71613547..28fb8e38 100644 --- a/imgui/imgui.cpp +++ b/imgui/imgui.cpp @@ -1284,12 +1284,12 @@ void ImGuiIO::ClearInputCharacters() ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p) { - ImVec2 ap = p - a; - ImVec2 ab_dir = b - a; - float dot = ap.x * ab_dir.x + ap.y * ab_dir.y; + const ImVec2 ap = p - a; + const ImVec2 ab_dir = b - a; + const float dot = ap.x * ab_dir.x + ap.y * ab_dir.y; if (dot < 0.0f) return a; - float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y; + const float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y; if (dot > ab_len_sqr) return b; return a + ab_dir * dot / ab_len_sqr; @@ -1297,17 +1297,17 @@ ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p) bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) { - bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; - bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; - bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + const bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + const bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + const bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; return ((b1 == b2) && (b2 == b3)); } void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w) { - ImVec2 v0 = b - a; - ImVec2 v1 = c - a; - ImVec2 v2 = p - a; + const ImVec2 v0 = b - a; + const ImVec2 v1 = c - a; + const ImVec2 v2 = p - a; const float denom = v0.x * v1.y - v1.x * v0.y; out_v = (v2.x * v1.y - v1.x * v2.y) / denom; out_w = (v0.x * v2.y - v2.x * v0.y) / denom; @@ -1316,13 +1316,13 @@ void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) { - ImVec2 proj_ab = ImLineClosestPoint(a, b, p); - ImVec2 proj_bc = ImLineClosestPoint(b, c, p); - ImVec2 proj_ca = ImLineClosestPoint(c, a, p); - float dist2_ab = ImLengthSqr(p - proj_ab); - float dist2_bc = ImLengthSqr(p - proj_bc); - float dist2_ca = ImLengthSqr(p - proj_ca); - float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca)); + const ImVec2 proj_ab = ImLineClosestPoint(a, b, p); + const ImVec2 proj_bc = ImLineClosestPoint(b, c, p); + const ImVec2 proj_ca = ImLineClosestPoint(c, a, p); + const float dist2_ab = ImLengthSqr(p - proj_ab); + const float dist2_bc = ImLengthSqr(p - proj_bc); + const float dist2_ca = ImLengthSqr(p - proj_ca); + const float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca)); if (m == dist2_ab) return proj_ab; if (m == dist2_bc) @@ -1356,15 +1356,15 @@ void ImStrncpy(char* dst, const char* src, size_t count) char* ImStrdup(const char* str) { - size_t len = strlen(str); + const size_t len = strlen(str); void* buf = IM_ALLOC(len + 1); return (char*)memcpy(buf, (const void*)str, len + 1); } char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) { - size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1; - size_t src_size = strlen(src) + 1; + const size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1; + const size_t src_size = strlen(src) + 1; if (dst_buf_size < src_size) { IM_FREE(dst); @@ -1377,7 +1377,7 @@ char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) const char* ImStrchrRange(const char* str, const char* str_end, char c) { - auto p = (const char*)memchr(str, (int)c, str_end - str); + const auto p = (const char*)memchr(str, (int)c, str_end - str); return p; } @@ -1392,7 +1392,7 @@ int ImStrlenW(const ImWchar* str) // Find end-of-line. Return pointer will point to either first \n, either str_end. const char* ImStreolRange(const char* str, const char* str_end) { - auto p = (const char*)memchr(str, '\n', str_end - str); + const auto p = (const char*)memchr(str, '\n', str_end - str); return p ? p : str_end; } @@ -1431,7 +1431,7 @@ void ImStrTrimBlanks(char* buf) char* p = buf; while (p[0] == ' ' || p[0] == '\t') // Leading blanks p++; - char* p_start = p; + const char * p_start = p; while (*p != 0) // Find end of string p++; while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks @@ -1542,7 +1542,7 @@ ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed) { while (data_size-- != 0) { - unsigned char c = *data++; + const unsigned char c = *data++; if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; @@ -1550,7 +1550,7 @@ ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed) } else { - while (unsigned char c = *data++) + while (const unsigned char c = *data++) { if (c == '#' && data[0] == '#' && data[1] == '#') crc = seed; @@ -1595,7 +1595,7 @@ void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_ return NULL; } - size_t file_size = (size_t)file_size_signed; + const size_t file_size = (size_t)file_size_signed; void* file_data = IM_ALLOC(file_size + padding_bytes); if (file_data == NULL) { @@ -1686,7 +1686,7 @@ int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { ImWchar* buf_out = buf; - ImWchar* buf_end = buf + buf_size; + const ImWchar * buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; @@ -1777,7 +1777,7 @@ int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWch const char* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { - unsigned int c = (unsigned int)(*in_text++); + const unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else @@ -1792,7 +1792,7 @@ int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_e int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { - unsigned int c = (unsigned int)(*in_text++); + const unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) bytes_count++; else @@ -1808,7 +1808,7 @@ int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_e ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) { - float s = 1.0f/255.0f; + const float s = 1.0f/255.0f; return ImVec4( ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, @@ -1860,11 +1860,11 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& } h = ImFmod(h, 1.0f) / (60.0f/360.0f); - int i = (int)h; - float f = h - (float)i; - float p = v * (1.0f - s); - float q = v * (1.0f - s * f); - float t = v * (1.0f - s * (1.0f - f)); + const int i = (int)h; + const float f = h - (float)i; + const float p = v * (1.0f - s); + const float q = v * (1.0f - s * f); + const float t = v * (1.0f - s * (1.0f - f)); switch (i) { @@ -1879,7 +1879,7 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) { - ImGuiStyle& style = GImGui->Style; + const ImGuiStyle & style = GImGui->Style; ImVec4 c = style.Colors[idx]; c.w *= style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); @@ -1887,7 +1887,7 @@ ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) ImU32 ImGui::GetColorU32(const ImVec4& col) { - ImGuiStyle& style = GImGui->Style; + const ImGuiStyle & style = GImGui->Style; ImVec4 c = col; c.w *= style.Alpha; return ColorConvertFloat4ToU32(c); @@ -1895,13 +1895,13 @@ ImU32 ImGui::GetColorU32(const ImVec4& col) const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx) { - ImGuiStyle& style = GImGui->Style; + const ImGuiStyle & style = GImGui->Style; return style.Colors[idx]; } ImU32 ImGui::GetColorU32(ImU32 col) { - float style_alpha = GImGui->Style.Alpha; + const float style_alpha = GImGui->Style.Alpha; if (style_alpha >= 1.0f) return col; ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; @@ -1918,11 +1918,11 @@ ImU32 ImGui::GetColorU32(ImU32 col) static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector& data, ImGuiID key) { ImGuiStorage::ImGuiStoragePair* first = data.Data; - ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size; + const ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size; size_t count = (size_t)(last - first); while (count > 0) { - size_t count2 = count >> 1; + const size_t count2 = count >> 1; ImGuiStorage::ImGuiStoragePair* mid = first + count2; if (mid->key < key) { @@ -1956,7 +1956,7 @@ void ImGuiStorage::BuildSortByKey() int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { - ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); + const ImGuiStoragePair * it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; @@ -1969,7 +1969,7 @@ bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { - ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); + const ImGuiStoragePair * it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; @@ -1977,7 +1977,7 @@ float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { - ImGuiStoragePair* it = LowerBound(const_cast&>(Data), key); + const ImGuiStoragePair * it = LowerBound(const_cast&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; @@ -2081,7 +2081,7 @@ bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); - bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + const bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); if (value_changed) Build(); return value_changed; @@ -2108,7 +2108,7 @@ void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector= Buf.Capacity) { - int new_capacity = Buf.Capacity * 2; + const int new_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); } @@ -2208,7 +2208,7 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) va_list args_copy; va_copy(args_copy, args); - int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. + const int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. if (len <= 0) { va_end(args_copy); @@ -2220,7 +2220,7 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { - int new_capacity = Buf.Capacity * 2; + const int new_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); } @@ -2240,8 +2240,8 @@ void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (g.LogEnabled) { // If logging is active, do not perform any clipping @@ -2281,7 +2281,7 @@ static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. // The clipper should probably have a 4th step to display the last item in a regular manner. - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos.y = pos_y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y); @@ -2296,8 +2296,8 @@ static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. void ImGuiListClipper::Begin(int count, float items_height) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; StartPosY = window->DC.CursorPos.y; ItemsHeight = items_height; @@ -2326,8 +2326,8 @@ void ImGuiListClipper::End() bool ImGuiListClipper::Step() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (ItemsCount == 0 || window->SkipItems) { @@ -2345,7 +2345,7 @@ bool ImGuiListClipper::Step() if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. { if (ItemsCount == 1) { ItemsCount = -1; return false; } - float items_height = window->DC.CursorPos.y - StartPosY; + const float items_height = window->DC.CursorPos.y - StartPosY; IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically Begin(ItemsCount - 1, items_height); DisplayStart++; @@ -2385,8 +2385,8 @@ const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; // Hide anything after a '##' string const char* text_display_end; @@ -2411,8 +2411,8 @@ void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (!text_end) text_end = text + strlen(text); // FIXME-OPT @@ -2446,7 +2446,7 @@ void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, co // Render if (need_clipping) { - ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + const ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); } else @@ -2463,8 +2463,8 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons if (text_len == 0) return; - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect); if (g.LogEnabled) LogRenderedText(&pos_min, text, text_display_end); @@ -2476,7 +2476,7 @@ void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, cons // This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move. void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (text_end_full == NULL) text_end_full = FindRenderedTextEnd(text); const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f); @@ -2554,8 +2554,8 @@ void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, con // Render a rectangle shaped with optional rounding and borders void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); const float border_size = g.Style.FrameBorderSize; if (border && border_size > 0.0f) @@ -2567,8 +2567,8 @@ void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; const float border_size = g.Style.FrameBorderSize; if (border_size > 0.0f) { @@ -2582,7 +2582,7 @@ void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir d { const float h = draw_list->_Data->FontSize * 1.00f; float r = h * 0.40f * scale; - ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); + const ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); ImVec2 a, b, c; switch (dir) @@ -2616,16 +2616,16 @@ void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; - float thickness = ImMax(sz / 5.0f, 1.0f); + const float thickness = ImMax(sz / 5.0f, 1.0f); sz -= thickness*0.5f; pos += ImVec2(thickness*0.25f, thickness*0.25f); - float third = sz / 3.0f; - float bx = pos.x + third; - float by = pos.y + sz - third*0.5f; + const float third = sz / 3.0f; + const float bx = pos.x + third; + const float by = pos.y + sz - third*0.5f; window->DrawList->PathLineTo(ImVec2(bx - third, by - third)); window->DrawList->PathLineTo(ImVec2(bx, by)); window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2)); @@ -2634,16 +2634,16 @@ void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz) void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (id != g.NavId) return; if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw)) return; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; if (window->DC.NavHideHighlightOneFrame) return; - float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; + const float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; ImRect display_rect = bb; display_rect.ClipWith(window->ClipRect); if (flags & ImGuiNavHighlightFlags_TypeDefault) @@ -2651,7 +2651,7 @@ void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFl const float THICKNESS = 2.0f; const float DISTANCE = 3.0f + THICKNESS * 0.5f; display_rect.Expand(ImVec2(DISTANCE,DISTANCE)); - bool fully_visible = window->ClipRect.Contains(display_rect); + const bool fully_visible = window->ClipRect.Contains(display_rect); if (!fully_visible) window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); @@ -2742,52 +2742,52 @@ ImGuiWindow::~ImGuiWindow() ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { - ImGuiID seed = IDStack.back(); - ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); + const ImGuiID seed = IDStack.back(); + const ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { - ImGuiID seed = IDStack.back(); - ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); + const ImGuiID seed = IDStack.back(); + const ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(int n) { - ImGuiID seed = IDStack.back(); - ImGuiID id = ImHashData(&n, sizeof(n), seed); + const ImGuiID seed = IDStack.back(); + const ImGuiID id = ImHashData(&n, sizeof(n), seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) { - ImGuiID seed = IDStack.back(); + const ImGuiID seed = IDStack.back(); return ImHashStr(str, str_end ? (str_end - str) : 0, seed); } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr) { - ImGuiID seed = IDStack.back(); + const ImGuiID seed = IDStack.back(); return ImHashData(&ptr, sizeof(void*), seed); } ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n) { - ImGuiID seed = IDStack.back(); + const ImGuiID seed = IDStack.back(); return ImHashData(&n, sizeof(n), seed); } // This is only used in rare/specific situations to manufacture an ID out of nowhere. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) { - ImGuiID seed = IDStack.back(); + const ImGuiID seed = IDStack.back(); const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) }; - ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed); + const ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed); ImGui::KeepAliveID(id); return id; } @@ -2916,7 +2916,7 @@ void ImGui::SetHoveredID(ImGuiID id) ImGuiID ImGui::GetHoveredID() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame; } @@ -2946,9 +2946,9 @@ static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFla { // An active popup disable hovering on other windows (apart from its own children) // FIXME-OPT: This could be cached/stored within the window. - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.NavWindow) - if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow) + if (const ImGuiWindow * focused_root_window = g.NavWindow->RootWindow) if (focused_root_window->WasActive && focused_root_window != window->RootWindow) { // For the purpose of those flags we differentiate "standard popup" from "modal popup" @@ -2965,7 +2965,7 @@ static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFla // Advance cursor given item size for layout. void ImGui::ItemSize(const ImVec2& size, float text_offset_y) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return; @@ -3058,7 +3058,7 @@ bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavDisableMouseHover && !g.NavDisableHighlight) return IsItemFocused(); @@ -3100,7 +3100,7 @@ bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap) return false; @@ -3133,8 +3133,8 @@ bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (!bb.Overlaps(window->ClipRect)) if (id == 0 || id != g.ActiveId) if (clip_even_when_logged || !g.LogEnabled) @@ -3191,7 +3191,7 @@ float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) if (wrap_pos_x < 0.0f) return 0.0f; - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; if (wrap_pos_x == 0.0f) wrap_pos_x = window->WorkRect.Max.x; else if (wrap_pos_x > 0.0f) @@ -3219,13 +3219,13 @@ void ImGui::MemFree(void* ptr) const char* ImGui::GetClipboardText() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.IO.SetClipboardTextFn) g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text); } @@ -3278,7 +3278,7 @@ void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas) { - auto ctx = IM_NEW(ImGuiContext)(shared_font_atlas); + const auto ctx = IM_NEW(ImGuiContext)(shared_font_atlas); if (GImGui == NULL) SetCurrentContext(ctx); Initialize(ctx); @@ -3371,7 +3371,7 @@ void ImGui::UpdateMouseMovingWindowNewFrame() ImGuiWindow* moving_window = g.MovingWindow->RootWindow; if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos)) { - ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; + const ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y) { MarkIniSettingsDirty(moving_window); @@ -3439,7 +3439,7 @@ void ImGui::UpdateMouseMovingWindowEndFrame() hovered_window_above_modal = true; for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--) { - ImGuiWindow* window = g.Windows[i]; + const ImGuiWindow * window = g.Windows[i]; if (window == modal) break; if (window == g.HoveredWindow) @@ -3575,8 +3575,8 @@ void ImGui::UpdateMouseWheel() window = window->ParentWindow; if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) { - float max_step = window->InnerRect.GetHeight() * 0.67f; - float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step)); + const float max_step = window->InnerRect.GetHeight() * 0.67f; + const float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step)); SetScrollY(window, window->Scroll.y - wheel_y * scroll_step); } } @@ -3590,8 +3590,8 @@ void ImGui::UpdateMouseWheel() window = window->ParentWindow; if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)) { - float max_step = window->InnerRect.GetWidth() * 0.67f; - float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step)); + const float max_step = window->InnerRect.GetWidth() * 0.67f; + const float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step)); SetScrollX(window, window->Scroll.x - wheel_x * scroll_step); } } @@ -4012,9 +4012,9 @@ static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs) { const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs; const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs; - if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) + if (const int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) return d; - if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) + if (const int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; return (a->BeginOrderWithinParent - b->BeginOrderWithinParent); } @@ -4024,7 +4024,7 @@ static void AddWindowToSortBuffer(ImVector* out_sorted_windows, Im out_sorted_windows->push_back(window); if (window->Active) { - int count = window->DC.ChildWindows.Size; + const int count = window->DC.ChildWindows.Size; if (count > 1) ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); for (int i = 0; i < count; i++) @@ -4042,7 +4042,7 @@ static void AddDrawListToDrawData(ImVector* out_list, ImDrawList* d return; // Remove trailing command if unused - ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); + const ImDrawCmd & last_cmd = draw_list->CmdBuffer.back(); if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) { draw_list->CmdBuffer.pop_back(); @@ -4121,7 +4121,7 @@ void ImDrawDataBuilder::FlattenIntoSingleLayer() static void SetupDrawData(ImVector* draw_lists, ImDrawData* draw_data) { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); draw_data->Valid = true; draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL; draw_data->CmdListsCount = draw_lists->Size; @@ -4196,8 +4196,8 @@ void ImGui::EndFrame() // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) if (g.DragDropActive) { - bool is_delivered = g.DragDropPayload.Delivery; - bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); + const bool is_delivered = g.DragDropPayload.Delivery; + const bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); if (is_delivered || is_elapsed) ClearDragDrop(); } @@ -4295,7 +4295,7 @@ void ImGui::Render() // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) @@ -4303,7 +4303,7 @@ ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_tex else text_display_end = text_end; - ImFont* font = g.Font; + const ImFont * font = g.Font; const float font_size = g.FontSize; if (text == text_display_end) return ImVec2(0.0f, font_size); @@ -4327,8 +4327,8 @@ static void FindHoveredWindow() if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) hovered_window = g.MovingWindow; - ImVec2 padding_regular = g.Style.TouchExtraPadding; - ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular; + const ImVec2 padding_regular = g.Style.TouchExtraPadding; + const ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular; for (int i = g.Windows.Size - 1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; @@ -4363,7 +4363,7 @@ static void FindHoveredWindow() // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; // Clip ImRect rect_clipped(r_min, r_max); @@ -4380,7 +4380,7 @@ bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool c int ImGui::GetKeyIndex(ImGuiKey imgui_key) { IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.IO.KeyMap[imgui_key]; } @@ -4389,7 +4389,7 @@ bool ImGui::IsKeyDown(int user_key_index) { if (user_key_index < 0) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); return g.IO.KeysDown[user_key_index]; } @@ -4406,7 +4406,7 @@ int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_ int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (key_index < 0) return 0; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); @@ -4416,7 +4416,7 @@ int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_r bool ImGui::IsKeyPressed(int user_key_index, bool repeat) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); @@ -4430,7 +4430,7 @@ bool ImGui::IsKeyPressed(int user_key_index, bool repeat) bool ImGui::IsKeyReleased(int user_key_index) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index]; @@ -4438,14 +4438,14 @@ bool ImGui::IsKeyReleased(int user_key_index) bool ImGui::IsMouseDown(int button) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDown[button]; } bool ImGui::IsAnyMouseDown() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++) if (g.IO.MouseDown[n]) return true; @@ -4454,7 +4454,7 @@ bool ImGui::IsAnyMouseDown() bool ImGui::IsMouseClicked(int button, bool repeat) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) @@ -4463,7 +4463,7 @@ bool ImGui::IsMouseClicked(int button, bool repeat) if (repeat && t > g.IO.KeyRepeatDelay) { // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold. - int amount = CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.5f); + const int amount = CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.5f); if (amount > 0) return true; } @@ -4473,14 +4473,14 @@ bool ImGui::IsMouseClicked(int button, bool repeat) bool ImGui::IsMouseReleased(int button) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseReleased[button]; } bool ImGui::IsMouseDoubleClicked(int button) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } @@ -4488,7 +4488,7 @@ bool ImGui::IsMouseDoubleClicked(int button) // [Internal] This doesn't test if the button is pressed bool ImGui::IsMouseDragPastThreshold(int button, float lock_threshold) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; @@ -4497,7 +4497,7 @@ bool ImGui::IsMouseDragPastThreshold(int button, float lock_threshold) bool ImGui::IsMouseDragging(int button, float lock_threshold) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) return false; @@ -4525,7 +4525,7 @@ bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions). IM_ASSERT(GImGui != NULL); const float MOUSE_INVALID = -256000.0f; - ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos; + const ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos; return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID; } @@ -4534,7 +4534,7 @@ bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) // NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; @@ -4575,10 +4575,10 @@ void ImGui::CaptureMouseFromApp(bool capture) bool ImGui::IsItemActive() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.ActiveId) { - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; return g.ActiveId == window->DC.LastItemId; } return false; @@ -4586,10 +4586,10 @@ bool ImGui::IsItemActive() bool ImGui::IsItemActivated() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.ActiveId) { - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId) return true; } @@ -4598,8 +4598,8 @@ bool ImGui::IsItemActivated() bool ImGui::IsItemDeactivated() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated) return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0; return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId); @@ -4607,14 +4607,14 @@ bool ImGui::IsItemDeactivated() bool ImGui::IsItemDeactivatedAfterEdit() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore)); } bool ImGui::IsItemFocused() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId) return false; @@ -4628,37 +4628,37 @@ bool ImGui::IsItemClicked(int mouse_button) bool ImGui::IsItemToggledSelection() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false; } bool ImGui::IsAnyItemHovered() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0; } bool ImGui::IsAnyItemActive() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.ActiveId != 0; } bool ImGui::IsAnyItemFocused() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.NavId != 0 && !g.NavDisableHighlight; } bool ImGui::IsItemVisible() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(window->DC.LastItemRect); } bool ImGui::IsItemEdited() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0; } @@ -4674,25 +4674,25 @@ void ImGui::SetItemAllowOverlap() ImVec2 ImGui::GetItemRectMin() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } static ImRect GetViewportRect() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } @@ -4724,7 +4724,7 @@ static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size const float backup_border_size = g.Style.ChildBorderSize; if (!border) g.Style.ChildBorderSize = 0.0f; - bool ret = Begin(title, NULL, flags); + const bool ret = Begin(title, NULL, flags); g.Style.ChildBorderSize = backup_border_size; ImGuiWindow* child_window = g.CurrentWindow; @@ -4761,8 +4761,8 @@ bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWin void ImGui::EndChild() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss if (window->BeginCount > 1) @@ -4778,8 +4778,8 @@ void ImGui::EndChild() sz.y = ImMax(4.0f, sz.y); End(); - ImGuiWindow* parent_window = g.CurrentWindow; - ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz); + const ImGuiWindow * parent_window = g.CurrentWindow; + const ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz); ItemSize(sz); if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened)) { @@ -4801,13 +4801,13 @@ void ImGui::EndChild() // Helper to create a child window / scrolling region that looks like a normal widget frame. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]); PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); - bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); + const bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); PopStyleVar(3); PopStyleColor(); return ret; @@ -4822,15 +4822,21 @@ void ImGui::EndChildFrame() static void CheckStacksSize(ImGuiWindow* window, bool write) { // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; short* p_backup = &window->DC.StackSizesBackup[0]; - { int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() - { int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() - { int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() + { + const int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() + { + const int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() + { + const int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them. - { int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() - { int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() - { int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() + { + const int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() + { + const int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() + { + const int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } @@ -4843,13 +4849,13 @@ static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, b ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id); } ImGuiWindow* ImGui::FindWindowByName(const char* name) { - ImGuiID id = ImHashStr(name); + const ImGuiID id = ImHashStr(name); return FindWindowByID(id); } @@ -4859,7 +4865,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); // Create window the first time - auto window = IM_NEW(ImGuiWindow)(&g, name); + const auto window = IM_NEW(ImGuiWindow)(&g, name); window->Flags = flags; g.WindowsById.SetVoidPtr(window->ID, window); @@ -4868,7 +4874,7 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. if (!(flags & ImGuiWindowFlags_NoSavedSettings)) - if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID)) + if (const ImGuiWindowSettings * settings = ImGui::FindWindowSettings(window->ID)) { // Retrieve settings from .ini file window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); @@ -4905,11 +4911,11 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) { // Using -1,-1 on either X/Y axis to preserve the current size. - ImRect cr = g.NextWindowData.SizeConstraintRect; + const ImRect cr = g.NextWindowData.SizeConstraintRect; new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; if (g.NextWindowData.SizeCallback) @@ -4952,10 +4958,10 @@ static ImVec2 CalcWindowContentSize(ImGuiWindow* window) static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents) { ImGuiContext& g = *GImGui; - ImGuiStyle& style = g.Style; - auto size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight()); - ImVec2 size_pad = window->WindowPadding * 2.0f; - ImVec2 size_desired = size_contents + size_pad + size_decorations; + const ImGuiStyle & style = g.Style; + const auto size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight()); + const ImVec2 size_pad = window->WindowPadding * 2.0f; + const ImVec2 size_desired = size_contents + size_pad + size_decorations; if (window->Flags & ImGuiWindowFlags_Tooltip) { // Tooltip always resize @@ -4973,9 +4979,9 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont // When the window cannot fit all contents (either because of constraints, either because screen is too small), // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. - ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit); - bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar); - bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar); + const ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit); + const bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - size_decorations.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar); + const bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - size_decorations.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar); if (will_have_scrollbar_x) size_auto_fit.y += style.ScrollbarSize; if (will_have_scrollbar_y) @@ -4986,9 +4992,9 @@ static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_cont ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) { - ImVec2 size_contents = CalcWindowContentSize(window); - ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents); - ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit); + const ImVec2 size_contents = CalcWindowContentSize(window); + const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents); + const ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit); return size_final; } @@ -5003,10 +5009,10 @@ static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags) static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) { - ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left - ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right - ImVec2 size_expected = pos_max - pos_min; - ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected); + const ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left + const ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right + const ImVec2 size_expected = pos_max - pos_min; + const ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected); *out_pos = pos_min; if (corner_norm.x == 0.0f) out_pos->x -= (size_constrained.x - size_expected.x); @@ -5047,7 +5053,7 @@ static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) { ImGuiContext& g = *GImGui; - ImGuiWindowFlags flags = window->Flags; + const ImGuiWindowFlags flags = window->Flags; if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) return false; @@ -5168,20 +5174,20 @@ static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_au static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding) { - ImGuiContext& g = *GImGui; - ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size; + const ImGuiContext & g = *GImGui; + const ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size; window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { - ImGuiContext& g = *GImGui; - float rounding = window->WindowRounding; - float border_size = window->WindowBorderSize; + const ImGuiContext & g = *GImGui; + const float rounding = window->WindowRounding; + const float border_size = window->WindowBorderSize; if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground)) window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); - int border_held = window->ResizeBorderHeld; + const int border_held = window->ResizeBorderHeld; if (border_held != -1) { struct ImGuiResizeBorderDef @@ -5198,14 +5204,14 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left }; const ImGuiResizeBorderDef& def = resize_border_def[border_held]; - ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); + const ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle); window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f); window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual } if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) { - float y = window->Pos.y + window->TitleBarHeight() - 1; + const float y = window->Pos.y + window->TitleBarHeight() - 1; window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize); } } @@ -5213,8 +5219,8 @@ static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size) { ImGuiContext& g = *GImGui; - ImGuiStyle& style = g.Style; - ImGuiWindowFlags flags = window->Flags; + const ImGuiStyle & style = g.Style; + const ImGuiWindowFlags flags = window->Flags; // Draw window + handle manual resize // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame. @@ -5223,9 +5229,9 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar if (window->Collapsed) { // Title bar only - float backup_border_size = style.FrameBorderSize; + const float backup_border_size = style.FrameBorderSize; g.Style.FrameBorderSize = window->WindowBorderSize; - ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); + const ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); g.Style.FrameBorderSize = backup_border_size; } @@ -5246,7 +5252,7 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { - ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); + const ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top); } @@ -5289,8 +5295,8 @@ void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) { ImGuiContext& g = *GImGui; - ImGuiStyle& style = g.Style; - ImGuiWindowFlags flags = window->Flags; + const ImGuiStyle & style = g.Style; + const ImGuiWindowFlags flags = window->Flags; const bool has_close_button = (p_open != NULL); const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None); @@ -5305,7 +5311,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl // FIXME: Would be nice to generalize the subtleties expressed here into reusable code. float pad_l = style.FramePadding.x; float pad_r = style.FramePadding.x; - float button_sz = g.FontSize; + const float button_sz = g.FontSize; ImVec2 close_button_pos; ImVec2 collapse_button_pos; if (has_close_button) @@ -5340,7 +5346,7 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. - auto UNSAVED_DOCUMENT_MARKER = "*"; + const auto UNSAVED_DOCUMENT_MARKER = "*"; const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f; const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); @@ -5352,20 +5358,20 @@ void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& titl pad_r += g.Style.ItemInnerSpacing.x; if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f) { - float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center - float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x); + const float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center + const float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x); pad_l = ImMax(pad_l, pad_extend * centerness); pad_r = ImMax(pad_r, pad_extend * centerness); } - ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y); - ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y); + const ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y); + const ImRect clip_r(layout_r.Min.x, layout_r.Min.y, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y); //if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG] RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r); if (flags & ImGuiWindowFlags_UnsavedDocument) { - ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f); - auto off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f)); + const ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f); + const auto off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f)); RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r); } } @@ -6057,7 +6063,7 @@ void ImGui::BringWindowToFocusFront(ImGuiWindow* window) void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; - ImGuiWindow* current_front_window = g.Windows.back(); + const ImGuiWindow * current_front_window = g.Windows.back(); if (current_front_window == window || current_front_window->RootWindow == window) return; for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window @@ -6129,7 +6135,7 @@ void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWind int start_idx = g.WindowsFocusOrder.Size - 1; if (under_this_window != NULL) { - int under_this_window_idx = FindWindowFocusIndex(under_this_window); + const int under_this_window_idx = FindWindowFocusIndex(under_this_window); if (under_this_window_idx != -1) start_idx = under_this_window_idx - 1; } @@ -6189,8 +6195,8 @@ void ImGui::PopItemWidth() // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() float ImGui::CalcItemWidth() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; float w; if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth) w = g.NextItemData.Width; @@ -6198,7 +6204,7 @@ float ImGui::CalcItemWidth() w = window->DC.ItemWidth; if (w < 0.0f) { - float region_max_x = GetContentRegionMaxAbs().x; + const float region_max_x = GetContentRegionMaxAbs().x; w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); } w = (float)(int)w; @@ -6211,7 +6217,7 @@ float ImGui::CalcItemWidth() // The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; ImVec2 region_max; if (size.x < 0.0f || size.y < 0.0f) @@ -6239,7 +6245,7 @@ void ImGui::SetCurrentFont(ImFont* font) g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; - ImFontAtlas* atlas = g.Font->ContainerAtlas; + const ImFontAtlas * atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; @@ -6341,7 +6347,7 @@ void ImGui::PopStyleColor(int count) ImGuiContext& g = *GImGui; while (count > 0) { - ImGuiColorMod& backup = g.ColorModifiers.back(); + const ImGuiColorMod & backup = g.ColorModifiers.back(); g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorModifiers.pop_back(); count--; @@ -6396,7 +6402,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) { ImGuiContext& g = *GImGui; - auto pvar = (float*)var_info->GetVarPtr(&g.Style); + const auto pvar = (float*)var_info->GetVarPtr(&g.Style); g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; @@ -6410,7 +6416,7 @@ void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) { ImGuiContext& g = *GImGui; - auto pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); + const auto pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; @@ -6424,7 +6430,7 @@ void ImGui::PopStyleVar(int count) while (count > 0) { // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it. - ImGuiStyleMod& backup = g.StyleModifiers.back(); + const ImGuiStyleMod & backup = g.StyleModifiers.back(); const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); void* data = info->GetVarPtr(&g.Style); if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } @@ -6508,7 +6514,7 @@ bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent) bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) { IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (flags & ImGuiHoveredFlags_AnyWindow) { @@ -6548,7 +6554,7 @@ bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (flags & ImGuiFocusedFlags_AnyWindow) return g.NavWindow != NULL; @@ -6577,20 +6583,20 @@ bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) float ImGui::GetWindowWidth() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->Size.x; } float ImGui::GetWindowHeight() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->Size.y; } ImVec2 ImGui::GetWindowPos() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; return window->Pos; } @@ -6607,7 +6613,7 @@ void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) // Set const ImVec2 old_pos = window->Pos; window->Pos = ImFloor(pos); - ImVec2 offset = window->Pos - old_pos; + const ImVec2 offset = window->Pos - old_pos; window->DC.CursorPos += offset; // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor window->DC.CursorMaxPos += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. window->DC.CursorStartPos += offset; @@ -6627,7 +6633,7 @@ void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) ImVec2 ImGui::GetWindowSize() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->Size; } @@ -6692,13 +6698,13 @@ void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) bool ImGui::IsWindowCollapsed() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->Collapsed; } bool ImGui::IsWindowAppearing() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->Appearing; } @@ -6788,8 +6794,8 @@ void ImGui::SetNextWindowBgAlpha(float alpha) // FIXME: This is in window space (not screen space!). We should try to obsolete all those functions. ImVec2 ImGui::GetContentRegionMax() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max - window->Pos; if (window->DC.CurrentColumns) mx.x = window->WorkRect.Max.x - window->Pos.x; @@ -6799,8 +6805,8 @@ ImVec2 ImGui::GetContentRegionMax() // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. ImVec2 ImGui::GetContentRegionMaxAbs() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.CurrentColumns) mx.x = window->WorkRect.Max.x; @@ -6809,56 +6815,56 @@ ImVec2 ImGui::GetContentRegionMaxAbs() ImVec2 ImGui::GetContentRegionAvail() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return GetContentRegionMaxAbs() - window->DC.CursorPos; } // In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->ContentsRegionRect.Min - window->Pos; } ImVec2 ImGui::GetWindowContentRegionMax() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->ContentsRegionRect.Max - window->Pos; } float ImGui::GetWindowContentRegionWidth() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->ContentsRegionRect.GetWidth(); } float ImGui::GetTextLineHeight() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } float ImGui::GetFrameHeight() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f; } float ImGui::GetFrameHeightWithSpacing() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; } ImDrawList* ImGui::GetWindowDrawList() { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); return window->DrawList; } @@ -6889,19 +6895,19 @@ void ImGui::SetWindowFontScale(float scale) // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } @@ -6928,13 +6934,13 @@ void ImGui::SetCursorPosY(float y) ImVec2 ImGui::GetCursorStartPos() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.CursorStartPos - window->Pos; } ImVec2 ImGui::GetCursorScreenPos() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.CursorPos; } @@ -6964,7 +6970,7 @@ void ImGui::SetKeyboardFocusHere(int offset) void ImGui::SetItemDefaultFocus() { ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; if (!window->Appearing) return; if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent) @@ -6986,7 +6992,7 @@ void ImGui::SetStateStorage(ImGuiStorage* tree) ImGuiStorage* ImGui::GetStateStorage() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->DC.StateStorage; } @@ -7047,13 +7053,13 @@ ImGuiID ImGui::GetID(const void* ptr_id) bool ImGui::IsRectVisible(const ImVec2& size) { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } @@ -7089,9 +7095,9 @@ void ImGui::EndGroup() ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls - ImGuiGroupData& group_data = window->DC.GroupStack.back(); + const ImGuiGroupData & group_data = window->DC.GroupStack.back(); - ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos)); + const ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos)); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); @@ -7148,7 +7154,7 @@ void ImGui::SameLine(float offset_from_start_x, float spacing_w) if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (offset_from_start_x != 0.0f) { if (spacing_w < 0.0f) spacing_w = 0.0f; @@ -7167,7 +7173,7 @@ void ImGui::SameLine(float offset_from_start_x, float spacing_w) void ImGui::Indent(float indent_w) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; @@ -7175,7 +7181,7 @@ void ImGui::Indent(float indent_w) void ImGui::Unindent(float indent_w) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; @@ -7188,11 +7194,11 @@ void ImGui::Unindent(float indent_w) static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImVec2 scroll = window->Scroll; if (window->ScrollTarget.x < FLT_MAX) { - float cr_x = window->ScrollTargetCenterRatio.x; + const float cr_x = window->ScrollTargetCenterRatio.x; float target_x = window->ScrollTarget.x; if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x) target_x = 0.0f; @@ -7202,9 +7208,10 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s } if (window->ScrollTarget.y < FLT_MAX) { - // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. - float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); - float cr_y = window->ScrollTargetCenterRatio.y; + // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the + // padding. + const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); + const float cr_y = window->ScrollTargetCenterRatio.y; float target_y = window->ScrollTarget.y; if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) target_y = 0.0f; @@ -7224,8 +7231,8 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool s // Scroll to keep newly navigated item fully into view ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect) { - ImGuiContext& g = *GImGui; - ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); + const ImGuiContext & g = *GImGui; + const ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] ImVec2 delta_scroll; @@ -7240,7 +7247,7 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_ else if (item_rect.Max.y >= window_rect.Max.y) SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f); - ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false); + const ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window, false); delta_scroll = next_scroll - window->Scroll; } @@ -7253,25 +7260,25 @@ ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_ float ImGui::GetScrollX() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->Scroll.x; } float ImGui::GetScrollY() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->Scroll.y; } float ImGui::GetScrollMaxX() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->ScrollMax.x; } float ImGui::GetScrollMaxY() { - ImGuiWindow* window = GImGui->CurrentWindow; + const ImGuiWindow * window = GImGui->CurrentWindow; return window->ScrollMax.y; } @@ -7322,23 +7329,23 @@ void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio); } void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio); } // center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item. void ImGui::SetScrollHereX(float center_x_ratio) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space - float last_item_width = window->DC.LastItemRect.GetWidth(); + const float last_item_width = window->DC.LastItemRect.GetWidth(); target_x += (last_item_width * center_x_ratio) + (g.Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. SetScrollFromPosX(target_x, center_x_ratio); } @@ -7346,8 +7353,8 @@ void ImGui::SetScrollHereX(float center_x_ratio) // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. void ImGui::SetScrollHereY(float center_y_ratio) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (g.Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. SetScrollFromPosY(target_y, center_y_ratio); @@ -7359,14 +7366,14 @@ void ImGui::SetScrollHereY(float center_y_ratio) void ImGui::BeginTooltip() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.DragDropWithinSourceOrTarget) { // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor) // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor. // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do. - //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; - ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale); + // ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; + const ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale); SetNextWindowPos(tooltip_pos); SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f); //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :( @@ -7393,7 +7400,7 @@ void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_ window->HiddenFramesCanSkipItems = 1; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount); } - ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; + const ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; Begin(window_name, NULL, flags | extra_flags); } @@ -7405,7 +7412,7 @@ void ImGui::EndTooltip() void ImGui::SetTooltipV(const char* fmt, va_list args) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.DragDropWithinSourceOrTarget) BeginTooltip(); else @@ -7440,7 +7447,7 @@ bool ImGui::IsPopupOpen(const char* str_id) ImGuiWindow* ImGui::GetTopMostPopupModal() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) if (popup->Flags & ImGuiWindowFlags_Modal) @@ -7450,7 +7457,7 @@ ImGuiWindow* ImGui::GetTopMostPopupModal() void ImGui::OpenPopup(const char* str_id) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; OpenPopupEx(g.CurrentWindow->GetID(str_id)); } @@ -7462,7 +7469,7 @@ void ImGui::OpenPopupEx(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; - int current_stack_size = g.BeginPopupStack.Size; + const int current_stack_size = g.BeginPopupStack.Size; ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; @@ -7505,7 +7512,7 @@ bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button) ImGuiWindow* window = GImGui->CurrentWindow; if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { - ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + const ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) OpenPopupEx(id); return true; @@ -7527,7 +7534,7 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++) { - ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep]; + const ImGuiPopupData & popup = g.OpenPopupStack[popup_count_to_keep]; if (!popup.Window) continue; IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); @@ -7537,7 +7544,7 @@ void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow) bool popup_or_descendent_is_ref_window = false; for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++) - if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window) + if (const ImGuiWindow * popup_window = g.OpenPopupStack[m].Window) if (popup_window->RootWindow == ref_window->RootWindow) popup_or_descendent_is_ref_window = true; if (!popup_or_descendent_is_ref_window) @@ -7586,8 +7593,8 @@ void ImGui::CloseCurrentPopup() // Closing a menu closes its top-most parent popup (unless a modal) while (popup_idx > 0) { - ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window; - ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window; + const ImGuiWindow * popup_window = g.OpenPopupStack[popup_idx].Window; + const ImGuiWindow * parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window; bool close_parent = false; if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu)) if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal)) @@ -7621,7 +7628,7 @@ bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) else ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame - bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup); + const bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup); if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) EndPopup(); @@ -7672,7 +7679,7 @@ bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags fla void ImGui::EndPopup() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls IM_ASSERT(g.BeginPopupStack.Size > 0); @@ -7690,7 +7697,7 @@ bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) ImGuiWindow* window = GImGui->CurrentWindow; if (window->SkipItems) return false; - ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + const ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id); @@ -7701,7 +7708,7 @@ bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool a { if (!str_id) str_id = "window_context"; - ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + const ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(id); @@ -7712,7 +7719,7 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) { if (!str_id) str_id = "void_context"; - ImGuiID id = GImGui->CurrentWindow->GetID(str_id); + const ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); @@ -7722,7 +7729,7 @@ bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) // r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy) { - ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size); + const ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size); //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); @@ -7754,8 +7761,8 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; - float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); - float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); + const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); + const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); if (avail_w < size.x || avail_h < size.y) continue; ImVec2 pos; @@ -7776,7 +7783,7 @@ ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& s ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window) { IM_UNUSED(window); - ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding; + const ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding; ImRect r_screen = GetViewportRect(); r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f)); return r_screen; @@ -7786,14 +7793,14 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) { ImGuiContext& g = *GImGui; - ImRect r_outer = GetWindowAllowedExtentRect(window); + const ImRect r_outer = GetWindowAllowedExtentRect(window); if (window->Flags & ImGuiWindowFlags_ChildMenu) { // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. IM_ASSERT(g.CurrentWindow == window); - ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2]; - float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). + const ImGuiWindow * parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2]; + const float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). ImRect r_avoid; if (parent_window->DC.MenuBarAppending) r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); @@ -7803,14 +7810,14 @@ ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) } if (window->Flags & ImGuiWindowFlags_Popup) { - auto r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1); + const auto r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1); return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); } if (window->Flags & ImGuiWindowFlags_Tooltip) { // Position tooltip (always follows mouse) - float sc = g.Style.MouseCursorScale; - ImVec2 ref_pos = NavCalcPreferredRefPos(); + const float sc = g.Style.MouseCursorScale; + const ImVec2 ref_pos = NavCalcPreferredRefPos(); ImRect r_avoid; if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)) r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8); @@ -7887,15 +7894,15 @@ static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) // Compute distance between boxes // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); - float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items + const float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items if (dby != 0.0f && dbx != 0.0f) dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); - float dist_box = ImFabs(dbx) + ImFabs(dby); + const float dist_box = ImFabs(dbx) + ImFabs(dby); // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) - float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x); - float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y); - float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee) + const float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x); + const float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y); + const float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee) // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance ImGuiDir quadrant; @@ -8029,7 +8036,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con g.NavMoveDir = g.NavMoveDirLast; bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest; #else - bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); + const bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); #endif if (new_best) { @@ -8065,7 +8072,7 @@ static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, con bool ImGui::NavMoveRequestButNoResultYet() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0; } @@ -8090,7 +8097,7 @@ void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const Im void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0) return; IM_ASSERT(move_flags != 0); // No points calling this with no wrapping @@ -8187,7 +8194,7 @@ void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) static ImVec2 ImGui::NavCalcPreferredRefPos() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow) { // Mouse (we need a fallback in case the mouse becomes invalid after being used) @@ -8199,15 +8206,15 @@ static ImVec2 ImGui::NavCalcPreferredRefPos() { // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item. const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer]; - ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight())); - ImRect visible_rect = GetViewportRect(); + const ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight())); + const ImRect visible_rect = GetViewportRect(); return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta. } } float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (mode == ImGuiInputReadMode_Down) return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user) @@ -8252,8 +8259,8 @@ static void ImGui::NavUpdate() #endif // Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard) - bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; - bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; + const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; + const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; if (nav_gamepad_active) if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f) g.NavInputSource = ImGuiInputSource_NavGamepad; @@ -8353,7 +8360,7 @@ static void ImGui::NavUpdate() else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow) { // Exit child window - ImGuiWindow* child_window = g.NavWindow; + const ImGuiWindow * child_window = g.NavWindow; ImGuiWindow* parent_window = g.NavWindow->ParentWindow; IM_ASSERT(child_window->ChildId != 0); FocusWindow(parent_window); @@ -8386,8 +8393,8 @@ static void ImGui::NavUpdate() g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0; if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) { - bool activate_down = IsNavInputDown(ImGuiNavInput_Activate); - bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed); + const bool activate_down = IsNavInputDown(ImGuiNavInput_Activate); + const bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed); if (g.ActiveId == 0 && activate_pressed) g.NavActivateId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down) @@ -8468,7 +8475,7 @@ static void ImGui::NavUpdate() // *Normal* Manual scroll with NavScrollXXX keys // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. - ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); + const ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); if (scroll_dir.x != 0.0f && window->ScrollbarX) { SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); @@ -8493,7 +8500,7 @@ static void ImGui::NavUpdate() ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1)); if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { - float pad = window->CalcFontSize() * 0.5f; + const float pad = window->CalcFontSize() * 0.5f; window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel); g.NavId = 0; @@ -8502,7 +8509,7 @@ static void ImGui::NavUpdate() } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) - ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); + const ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y); g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x); @@ -8555,13 +8562,13 @@ static void ImGui::NavUpdateMoveResult() ImVec2 delta_scroll; if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge) { - float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f; + const float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f; delta_scroll.y = result->Window->Scroll.y - scroll_target; SetScrollY(result->Window, scroll_target); } else { - auto rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); + const auto rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs); } @@ -8697,7 +8704,7 @@ static void ImGui::NavUpdateWindowing() ImGuiWindow* apply_focus_window = NULL; bool apply_toggle_layer = false; - ImGuiWindow* modal_window = GetTopMostPopupModal(); + const ImGuiWindow * modal_window = GetTopMostPopupModal(); if (modal_window != NULL) { g.NavWindowingTarget = NULL; @@ -8713,8 +8720,8 @@ static void ImGui::NavUpdateWindowing() } // Start CTRL-TAB or Square+L/R window selection - bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); - bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard); + const bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); + const bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard); if (start_windowing_with_gamepad || start_windowing_with_keyboard) if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) { @@ -8900,7 +8907,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) bool source_drag_active = false; ImGuiID source_id = 0; ImGuiID source_parent_id = 0; - int mouse_button = 0; + const int mouse_button = 0; if (!(flags & ImGuiDragDropFlags_SourceExtern)) { source_id = window->DC.LastItemId; @@ -8928,7 +8935,7 @@ bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect); - bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id); + const bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id); if (is_hovered && g.IO.MouseClicked[mouse_button]) { SetActiveID(source_id, window); @@ -9055,7 +9062,7 @@ bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) if (!g.DragDropActive) return false; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) return false; IM_ASSERT(id != 0); @@ -9103,14 +9110,14 @@ bool ImGui::BeginDragDropTarget() bool ImGui::IsDragDropPayloadBeingAccepted() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.DragDropActive && g.DragDropAcceptIdPrev != 0; } const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags) { ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; ImGuiPayload& payload = g.DragDropPayload; IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? @@ -9121,7 +9128,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function! const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId); ImRect r = g.DragDropTargetRect; - float r_surface = r.GetWidth() * r.GetHeight(); + const float r_surface = r.GetWidth() * r.GetHeight(); if (r_surface < g.DragDropAcceptIdCurrRectSurface) { g.DragDropAcceptFlags = flags; @@ -9136,7 +9143,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop { // FIXME-DRAG: Settle on a proper default visuals for drop target. r.Expand(3.5f); - bool push_clip_rect = !window->ClipRect.Contains(r); + const bool push_clip_rect = !window->ClipRect.Contains(r); if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1)); window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f); if (push_clip_rect) window->DrawList->PopClipRect(); @@ -9152,7 +9159,7 @@ const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDrop const ImGuiPayload* ImGui::GetDragDropPayload() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.DragDropActive ? &g.DragDropPayload : NULL; } @@ -9194,7 +9201,7 @@ void ImGui::LogText(const char* fmt, ...) void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) { ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; if (!text_end) text_end = FindRenderedTextEnd(text, text_end); @@ -9245,7 +9252,7 @@ void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth) { ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; IM_ASSERT(g.LogEnabled == false); IM_ASSERT(g.LogFile == NULL); IM_ASSERT(g.LogBuffer.empty()); @@ -9294,7 +9301,7 @@ void ImGui::LogToFile(int auto_open_depth, const char* filename) // Start logging/capturing text output to clipboard void ImGui::LogToClipboard(int auto_open_depth) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.LogEnabled) return; LogBegin(ImGuiLogType_Clipboard, auto_open_depth); @@ -9302,7 +9309,7 @@ void ImGui::LogToClipboard(int auto_open_depth) void ImGui::LogToBuffer(int auto_open_depth) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.LogEnabled) return; LogBegin(ImGuiLogType_Buffer, auto_open_depth); @@ -9419,7 +9426,7 @@ ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) { size_t file_data_size = 0; - auto file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); + const auto file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); if (!file_data) return; LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); @@ -9447,8 +9454,8 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. if (ini_size == 0) ini_size = strlen(ini_data); - auto buf = (char*)IM_ALLOC(ini_size + 1); - char* buf_end = buf + ini_size; + const auto buf = (char*)IM_ALLOC(ini_size + 1); + const char * buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); buf[ini_size] = 0; @@ -9473,7 +9480,7 @@ void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) line_end[-1] = 0; const char* name_end = line_end - 1; const char* type_start = line + 1; - auto type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); + const auto type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; if (!type_end || !name_start) { @@ -9541,7 +9548,7 @@ static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler* static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) { - auto settings = (ImGuiWindowSettings*)entry; + const auto settings = (ImGuiWindowSettings*)entry; int x, y; int i; if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) settings->Pos = ImVec2ih((short)x, (short)y); @@ -9630,15 +9637,15 @@ static const char* GetClipboardTextFn_DefaultImpl(void*) buf_local.clear(); if (!::OpenClipboard(NULL)) return NULL; - HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); + const HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) { ::CloseClipboard(); return NULL; } - if (auto wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle)) + if (const auto wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle)) { - int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; + const int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; buf_local.resize(buf_len); ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); } @@ -9652,13 +9659,13 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) if (!::OpenClipboard(NULL)) return; const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; - HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); + const HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); if (wbuf_handle == NULL) { ::CloseClipboard(); return; } - auto wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle); + const auto wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle); ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); ::GlobalUnlock(wbuf_handle); ::EmptyClipboard(); @@ -9751,9 +9758,9 @@ static void SetClipboardTextFn_DefaultImpl(void*, const char* text) static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { // Notify OS Input Method Editor of text input position - ImGuiIO& io = ImGui::GetIO(); - if (auto hwnd = (HWND)io.ImeWindowHandle) - if (HIMC himc = ::ImmGetContext(hwnd)) + const ImGuiIO & io = ImGui::GetIO(); + if (const auto hwnd = (HWND)io.ImeWindowHandle) + if (const HIMC himc = ::ImmGetContext(hwnd)) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = x; @@ -9793,7 +9800,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) // Basic info ImGuiContext& g = *GImGui; - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); @@ -9816,7 +9823,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) else if (rect_type == WRT_InnerRect) { return window->InnerRect; } else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; } else if (rect_type == WRT_WorkRect) { return window->WorkRect; } - else if (rect_type == WRT_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } + else if (rect_type == WRT_Contents) { + const ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } else if (rect_type == WRT_ContentsRegionRect) { return window->ContentsRegionRect; } IM_ASSERT(0); return ImRect(); @@ -9824,7 +9832,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label) { - bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); + const bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); @@ -9852,11 +9860,11 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); continue; } - ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + const ImDrawIdx * idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "Draw %4d triangles, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); - bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); + const bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered()) { ImRect clip_rect = pcmd->ClipRect; @@ -9879,8 +9887,8 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImVec2 triangles_pos[3]; for (int n = 0; n < 3; n++, idx_i++) { - int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i; - ImDrawVert& v = draw_list->VtxBuffer[vtx_i]; + const int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i; + const ImDrawVert & v = draw_list->VtxBuffer[vtx_i]; triangles_pos[n] = v.pos; buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "elem" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); @@ -9888,7 +9896,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) ImGui::Selectable(buf, false); if (fg_draw_list && ImGui::IsItemHovered()) { - ImDrawListFlags backup_flags = fg_draw_list->Flags; + const ImDrawListFlags backup_flags = fg_draw_list->Flags; fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles. fg_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f); fg_draw_list->Flags = backup_flags; @@ -9927,7 +9935,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) } if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, (window->Active || window->WasActive), window)) return; - ImGuiWindowFlags flags = window->Flags; + const ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->DrawList, "DrawList"); ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y); ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, @@ -9991,7 +9999,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) { for (int i = 0; i < g.OpenPopupStack.Size; i++) { - ImGuiWindow* window = g.OpenPopupStack[i].Window; + const ImGuiWindow * window = g.OpenPopupStack[i].Window; ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); } ImGui::TreePop(); @@ -10082,7 +10090,7 @@ void ImGui::ShowMetricsWindow(bool* p_open) { char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); - float font_size = ImGui::GetFontSize(); + const float font_size = ImGui::GetFontSize(); draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf); } diff --git a/imgui/imgui.h b/imgui/imgui.h index 00a1f5cb..5b07d517 100644 --- a/imgui/imgui.h +++ b/imgui/imgui.h @@ -1261,9 +1261,12 @@ struct ImVector inline const T& front() const { IM_ASSERT(Size > 0); return Data[0]; } inline T& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } inline const T& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } - inline void swap(ImVector& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + inline void swap(ImVector& rhs) { + const int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; + const int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } - inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } + inline int _grow_capacity(int sz) const { + const int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void resize(int new_size, const T& v) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; } @@ -1580,7 +1583,8 @@ namespace ImGui IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // Use SetNextWindowSize(size, ImGuiCond_FirstUseEver) + SetNextWindowBgAlpha() instead. static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } - static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); } + static inline void SetNextWindowPosCenter(ImGuiCond c=0) { + const ImGuiIO & io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); } } typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETED in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; @@ -1596,7 +1600,8 @@ struct ImGuiOnceUponAFrame { ImGuiOnceUponAFrame() { RefFrame = -1; } mutable int RefFrame; - operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } + operator bool() const { + const int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" @@ -1755,8 +1760,10 @@ struct ImColor ImVec4 Value; ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } - ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } - ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } + ImColor(int r, int g, int b, int a = 255) { + const float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } + ImColor(ImU32 rgba) { + const float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } @@ -2045,9 +2052,14 @@ struct ImFontGlyphRangesBuilder ImVector UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) ImFontGlyphRangesBuilder() { Clear(); } - inline void Clear() { int size_in_bytes = 0x10000 / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } - inline bool GetBit(int n) const { int off = (n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array - inline void SetBit(int n) { int off = (n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array + inline void Clear() { + const int size_in_bytes = 0x10000 / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); } + inline bool GetBit(int n) const { + const int off = (n >> 5); + const ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; } // Get bit n in the array + inline void SetBit(int n) { + const int off = (n >> 5); + const ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; } // Set bit n in the array inline void AddChar(ImWchar c) { SetBit(c); } // Add character IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext diff --git a/imgui/imgui_demo.cpp b/imgui/imgui_demo.cpp index d56af070..c3357fa4 100644 --- a/imgui/imgui_demo.cpp +++ b/imgui/imgui_demo.cpp @@ -152,7 +152,7 @@ static void HelpMarker(const char* desc) // Helper to display basic user controls. void ImGui::ShowUserGuide() { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); ImGui::BulletText("Double-click on title bar to collapse window."); ImGui::BulletText("Click and drag on lower right corner to resize window\n(double-click to auto fit window to its contents)."); ImGui::BulletText("Click and drag on any empty space to move window."); @@ -1003,7 +1003,7 @@ static void ShowDemoWindowWidgets() { if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) { - auto my_str = (ImVector*)data->UserData; + const auto my_str = (ImVector*)data->UserData; IM_ASSERT(my_str->begin() == data->Buf); my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1 data->Buf = my_str->begin(); @@ -1694,7 +1694,7 @@ static void ShowDemoWindowLayout() // Child 1: no border, enable horizontal scrollbar { - ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0); + const ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar | (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0); ImGui::BeginChild("Child1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags); for (int i = 0; i < 100; i++) { @@ -1711,7 +1711,7 @@ static void ShowDemoWindowLayout() // Child 2: rounded border { - ImGuiWindowFlags window_flags = (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar); + const ImGuiWindowFlags window_flags = (disable_mouse_wheel ? ImGuiWindowFlags_NoScrollWithMouse : 0) | (disable_menu ? 0 : ImGuiWindowFlags_MenuBar); ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); ImGui::BeginChild("Child2", ImVec2(0, 260), true, window_flags); if (!disable_menu && ImGui::BeginMenuBar()) @@ -1750,8 +1750,8 @@ static void ShowDemoWindowLayout() for (int n = 0; n < 50; n++) ImGui::Text("Some test %d", n); ImGui::EndChild(); - ImVec2 child_rect_min = ImGui::GetItemRectMin(); - ImVec2 child_rect_max = ImGui::GetItemRectMax(); + const ImVec2 child_rect_min = ImGui::GetItemRectMin(); + const ImVec2 child_rect_max = ImGui::GetItemRectMax(); ImGui::PopStyleColor(); ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y); } @@ -1860,22 +1860,22 @@ static void ShowDemoWindowLayout() ImGui::PopItemWidth(); // Dummy - ImVec2 button_sz(40, 40); + const ImVec2 button_sz(40, 40); ImGui::Button("A", button_sz); ImGui::SameLine(); ImGui::Dummy(button_sz); ImGui::SameLine(); ImGui::Button("B", button_sz); // Manually wrapping (we should eventually provide this as an automatic layout feature, but for now you can do it manually) ImGui::Text("Manually wrapping:"); - ImGuiStyle& style = ImGui::GetStyle(); - int buttons_count = 20; - float window_visible_x2 = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x; + const ImGuiStyle & style = ImGui::GetStyle(); + const int buttons_count = 20; + const float window_visible_x2 = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x; for (int n = 0; n < buttons_count; n++) { ImGui::PushID(n); ImGui::Button("Box", button_sz); - float last_button_x2 = ImGui::GetItemRectMax().x; - float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; // Expected position if next button was on same line + const float last_button_x2 = ImGui::GetItemRectMax().x; + const float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; // Expected position if next button was on same line if (n + 1 < buttons_count && next_button_x2 < window_visible_x2) ImGui::SameLine(); ImGui::PopID(); @@ -1888,7 +1888,7 @@ static void ShowDemoWindowLayout() { if (ImGui::TreeNode("Basic")) { - ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; + const ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None; if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags)) { if (ImGui::BeginTabItem("Avocado")) @@ -1976,7 +1976,7 @@ static void ShowDemoWindowLayout() ImGui::SetTooltip("First group hovered"); } // Capture the group size and create widgets using the same size - ImVec2 size = ImGui::GetItemRectSize(); + const ImVec2 size = ImGui::GetItemRectSize(); const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); @@ -2038,7 +2038,7 @@ static void ShowDemoWindowLayout() if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data ImGui::AlignTextToFramePadding(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit). - bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. + const bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data @@ -2076,15 +2076,15 @@ static void ShowDemoWindowLayout() if (scroll_to_off || scroll_to_pos) track = false; - ImGuiStyle& style = ImGui::GetStyle(); - float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; + const ImGuiStyle & style = ImGui::GetStyle(); + const float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5; for (int i = 0; i < 5; i++) { if (i > 0) ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); - ImGuiWindowFlags child_flags = ImGuiWindowFlags_MenuBar; + const ImGuiWindowFlags child_flags = ImGuiWindowFlags_MenuBar; ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(child_w, 200.0f), true, child_flags); if (scroll_to_off) ImGui::SetScrollY(scroll_to_off_px); @@ -2102,8 +2102,8 @@ static void ShowDemoWindowLayout() ImGui::Text("Line %d", line); } } - float scroll_y = ImGui::GetScrollY(); - float scroll_max_y = ImGui::GetScrollMaxY(); + const float scroll_y = ImGui::GetScrollY(); + const float scroll_max_y = ImGui::GetScrollMaxY(); ImGui::EndChild(); ImGui::Text("%.0f/%.0f", scroll_y, scroll_max_y); ImGui::EndGroup(); @@ -2123,7 +2123,7 @@ static void ShowDemoWindowLayout() { // Display random stuff (for the sake of this trivial demo we are using basic Button+SameLine. If you want to create your own time line for a real application you may be better off // manipulating the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets yourself. You may also want to use the lower-level ImDrawList API) - int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); + const int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); for (int n = 0; n < num_buttons; n++) { if (n > 0) ImGui::SameLine(); @@ -2131,7 +2131,7 @@ static void ShowDemoWindowLayout() char num_buf[16]; sprintf(num_buf, "%d", n); const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : num_buf; - float hue = n*0.05f; + const float hue = n*0.05f; ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f)); @@ -2140,8 +2140,8 @@ static void ShowDemoWindowLayout() ImGui::PopID(); } } - float scroll_x = ImGui::GetScrollX(); - float scroll_max_x = ImGui::GetScrollMaxX(); + const float scroll_x = ImGui::GetScrollX(); + const float scroll_max_x = ImGui::GetScrollMaxX(); ImGui::EndChild(); ImGui::PopStyleVar(2); float scroll_x_delta = 0.0f; @@ -2191,7 +2191,7 @@ static void ShowDemoWindowLayout() ImGui::SameLine(); ImGui::SetNextItemWidth(100); ImGui::DragFloat("##csx", &contents_size_x); - ImVec2 p = ImGui::GetCursorScreenPos(); + const ImVec2 p = ImGui::GetCursorScreenPos(); ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE); ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE); ImGui::Dummy(ImVec2(0, 10)); @@ -2255,8 +2255,8 @@ static void ShowDemoWindowLayout() ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost."); ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f"); ImGui::TextWrapped("(Click and drag)"); - ImVec2 pos = ImGui::GetCursorScreenPos(); - ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); + const ImVec2 pos = ImGui::GetCursorScreenPos(); + const ImVec4 clip_rect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); ImGui::InvisibleButton("##dummy", size); if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; } ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x + size.x, pos.y + size.y), IM_COL32(90, 90, 120, 255)); @@ -2543,7 +2543,7 @@ static void ShowDemoWindowColumns() sprintf(label, "%04d", i); if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns)) selected = i; - bool hovered = ImGui::IsItemHovered(); + const bool hovered = ImGui::IsItemHovered(); ImGui::NextColumn(); ImGui::Text(names[i]); ImGui::NextColumn(); ImGui::Text(paths[i]); ImGui::NextColumn(); @@ -2657,7 +2657,7 @@ static void ShowDemoWindowColumns() ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f)); ImGui::BeginChild("##ScrollingRegion", ImVec2(0, ImGui::GetFontSize() * 20), false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::Columns(10); - int ITEMS_COUNT = 2000; + const int ITEMS_COUNT = 2000; ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list while (clipper.Step()) { @@ -2678,7 +2678,7 @@ static void ShowDemoWindowColumns() ImGui::Columns(2, "tree", true); for (int x = 0; x < 3; x++) { - bool open1 = ImGui::TreeNode((void*)(intptr_t)x, "Node%d", x); + const bool open1 = ImGui::TreeNode((void*)(intptr_t)x, "Node%d", x); ImGui::NextColumn(); ImGui::Text("Node contents"); ImGui::NextColumn(); @@ -2686,7 +2686,7 @@ static void ShowDemoWindowColumns() { for (int y = 0; y < 3; y++) { - bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y); + const bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y); ImGui::NextColumn(); ImGui::Text("Node contents"); if (open2) @@ -2758,7 +2758,8 @@ static void ShowDemoWindowMisc() ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); } ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); - ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. + ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { + const ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public. ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); } ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); } @@ -2792,9 +2793,9 @@ static void ShowDemoWindowMisc() if (ImGui::TreeNode("Focus from code")) { - bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); - bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); - bool focus_3 = ImGui::Button("Focus on 3"); + const bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + const bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + const bool focus_3 = ImGui::Button("Focus on 3"); int has_focus = 0; static char buf[128] = "click on a button to set focus"; @@ -2843,9 +2844,9 @@ static void ShowDemoWindowMisc() // Drag operations gets "unlocked" when the mouse has moved past a certain threshold (the default threshold is stored in io.MouseDragThreshold) // You can request a lower or higher threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta() - ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); - ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); - ImVec2 mouse_delta = io.MouseDelta; + const ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + const ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + const ImVec2 mouse_delta = io.MouseDelta; ImGui::Text("GetMouseDragDelta(0):\n w/ default threshold: (%.1f, %.1f),\n w/ zero threshold: (%.1f, %.1f)\nMouseDelta: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y, value_raw.x, value_raw.y, mouse_delta.x, mouse_delta.y); ImGui::TreePop(); } @@ -2892,10 +2893,10 @@ void ImGui::ShowAboutWindow(bool* p_open) ImGui::Checkbox("Config/Build Information", &show_config_info); if (show_config_info) { - ImGuiIO& io = ImGui::GetIO(); - ImGuiStyle& style = ImGui::GetStyle(); + const ImGuiIO & io = ImGui::GetIO(); + const ImGuiStyle & style = ImGui::GetStyle(); - bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); + const bool copy_to_clipboard = ImGui::Button("Copy to clipboard"); ImGui::BeginChildFrame(ImGui::GetID("cfginfos"), ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18), ImGuiWindowFlags_NoMove); if (copy_to_clipboard) ImGui::LogToClipboard(); @@ -3022,7 +3023,7 @@ bool ImGui::ShowStyleSelector(const char* label) void ImGui::ShowFontSelector(const char* label) { ImGuiIO& io = ImGui::GetIO(); - ImFont* font_current = ImGui::GetFont(); + const ImFont * font_current = ImGui::GetFont(); if (ImGui::BeginCombo(label, font_current->GetDebugName())) { for (int n = 0; n < io.Fonts->Fonts.Size; n++) @@ -3188,7 +3189,7 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImFont* font = atlas->Fonts[i]; ImGui::PushID(font); - bool font_details_opened = ImGui::TreeNode(font, "Font %d: \"%s\"\n%.2f px, %d glyphs, %d file(s)", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); + const bool font_details_opened = ImGui::TreeNode(font, "Font %d: \"%s\"\n%.2f px, %d glyphs, %d file(s)", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount); ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; } if (font_details_opened) { @@ -3215,9 +3216,9 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) count += font->FindGlyphNoFallback((ImWchar)(base + n)) ? 1 : 0; if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph")) { - float cell_size = font->FontSize * 1; - float cell_spacing = style.ItemSpacing.y; - ImVec2 base_pos = ImGui::GetCursorScreenPos(); + const float cell_size = font->FontSize * 1; + const float cell_spacing = style.ItemSpacing.y; + const ImVec2 base_pos = ImGui::GetCursorScreenPos(); ImDrawList* draw_list = ImGui::GetWindowDrawList(); for (int n = 0; n < 256; n++) { @@ -3250,8 +3251,8 @@ void ImGui::ShowStyleEditor(ImGuiStyle* ref) } if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) { - auto tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - auto border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); + const auto tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + const auto border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0, 0), ImVec2(1, 1), tint_col, border_col); ImGui::TreePop(); } @@ -3361,7 +3362,7 @@ static void ShowExampleMenuFile() } if (ImGui::BeginMenu("Colors")) { - float sz = ImGui::GetTextLineHeight(); + const float sz = ImGui::GetTextLineHeight(); for (int i = 0; i < ImGuiCol_COUNT; i++) { const char* name = ImGui::GetStyleColorName((ImGuiCol)i); @@ -3421,7 +3422,8 @@ struct ExampleAppConsole // Portable helpers static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } - static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)str, len); } + static char* Strdup(const char *str) { + const size_t len = strlen(str) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)str, len); } static void Strtrim(char* str) { char* str_end = str + strlen(str); while (str_end > str && str_end[-1] == ' ') str_end--; *str_end = 0; } void ClearLog() @@ -3472,7 +3474,7 @@ struct ExampleAppConsole if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); if (ImGui::SmallButton("Add Dummy Error")) { AddLog("[error] something went wrong"); } ImGui::SameLine(); if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); - bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::SameLine(); + const bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::SameLine(); if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true; //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } @@ -3587,7 +3589,7 @@ struct ExampleAppConsole } else if (Stricmp(command_line, "HISTORY") == 0) { - int first = History.Size - 10; + const int first = History.Size - 10; for (int i = first > 0 ? first : 0; i < History.Size; i++) AddLog("%3d: %s\n", i, History[i]); } @@ -3602,7 +3604,7 @@ struct ExampleAppConsole static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks { - auto console = (ExampleAppConsole*)data->UserData; + const auto console = (ExampleAppConsole*)data->UserData; return console->TextEditCallback(data); } @@ -3750,7 +3752,7 @@ struct ExampleAppLog va_start(args, fmt); Buf.appendfv(fmt, args); va_end(args); - for (int new_size = Buf.size(); old_size < new_size; old_size++) + for (const int new_size = Buf.size(); old_size < new_size; old_size++) if (Buf[old_size] == '\n') LineOffsets.push_back(old_size + 1); if (AutoScroll) @@ -3778,9 +3780,9 @@ struct ExampleAppLog if (ImGui::Button("Options")) ImGui::OpenPopup("Options"); ImGui::SameLine(); - bool clear = ImGui::Button("Clear"); + const bool clear = ImGui::Button("Clear"); ImGui::SameLine(); - bool copy = ImGui::Button("Copy"); + const bool copy = ImGui::Button("Copy"); ImGui::SameLine(); Filter.Draw("Filter", -100.0f); @@ -3958,7 +3960,7 @@ static void ShowExampleAppPropertyEditor(bool* p_open) { ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. ImGui::AlignTextToFramePadding(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high. - bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + const bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); ImGui::NextColumn(); ImGui::AlignTextToFramePadding(); ImGui::Text("my sailor is rich"); @@ -4093,7 +4095,8 @@ static void ShowExampleAppConstrainedResize(bool* p_open) struct CustomConstraints // Helper functions to demonstrate programmatic constraints { static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); } - static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } + static void Step(ImGuiSizeCallbackData* data) { + const float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } }; static bool auto_resize = false; @@ -4107,7 +4110,7 @@ static void ShowExampleAppConstrainedResize(bool* p_open) if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)(intptr_t)100); // Fixed Step - ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0; + const ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0; if (ImGui::Begin("Example: Constrained Resize", p_open, flags)) { const char* desc[] = @@ -4143,11 +4146,11 @@ static void ShowExampleAppSimpleOverlay(bool* p_open) { const float DISTANCE = 10.0f; static int corner = 0; - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); if (corner != -1) { - auto window_pos = ImVec2((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE); - auto window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); + const auto window_pos = ImVec2((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE); + const auto window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f); ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot); } ImGui::SetNextWindowBgAlpha(0.35f); // Forward background @@ -4238,14 +4241,14 @@ static void ShowExampleAppCustomRendering(bool* p_open) const ImVec2 p = ImGui::GetCursorScreenPos(); const ImU32 col = ImColor(colf); float x = p.x + 4.0f, y = p.y + 4.0f; - float spacing = 10.0f; - ImDrawCornerFlags corners_none = 0; - ImDrawCornerFlags corners_all = ImDrawCornerFlags_All; - ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight; + const float spacing = 10.0f; + const ImDrawCornerFlags corners_none = 0; + const ImDrawCornerFlags corners_all = ImDrawCornerFlags_All; + const ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight; for (int n = 0; n < 2; n++) { // First line uses a thickness of 1.0f, second line uses the configurable thickness - float th = (n == 0) ? 1.0f : thickness; + const float th = (n == 0) ? 1.0f : thickness; draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 6, th); x += sz + spacing; // Hexagon draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, 20, th); x += sz + spacing; // Circle draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, corners_none, th); x += sz + spacing; // Square @@ -4286,7 +4289,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() // But you can also draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). - ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + const ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; @@ -4295,7 +4298,7 @@ static void ShowExampleAppCustomRendering(bool* p_open) bool adding_preview = false; ImGui::InvisibleButton("canvas", canvas_size); - auto mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); + const auto mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); if (adding_line) { adding_preview = true; @@ -4332,9 +4335,9 @@ static void ShowExampleAppCustomRendering(bool* p_open) static bool draw_fg = true; ImGui::Checkbox("Draw in Background draw list", &draw_bg); ImGui::Checkbox("Draw in Foreground draw list", &draw_fg); - ImVec2 window_pos = ImGui::GetWindowPos(); - ImVec2 window_size = ImGui::GetWindowSize(); - auto window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); + const ImVec2 window_pos = ImGui::GetWindowPos(); + const ImVec2 window_size = ImGui::GetWindowSize(); + const auto window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f); if (draw_bg) ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 32, 10+4); if (draw_fg) @@ -4501,7 +4504,7 @@ void ShowExampleAppDocuments(bool* p_open) // Submit Tab Bar and Tabs { - ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0); + const ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0); if (ImGui::BeginTabBar("##tabs", tab_bar_flags)) { if (opt_reorderable) @@ -4518,8 +4521,8 @@ void ShowExampleAppDocuments(bool* p_open) if (!doc->Open) continue; - ImGuiTabItemFlags tab_flags = (doc->Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0); - bool visible = ImGui::BeginTabItem(doc->Name, &doc->Open, tab_flags); + const ImGuiTabItemFlags tab_flags = (doc->Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0); + const bool visible = ImGui::BeginTabItem(doc->Name, &doc->Open, tab_flags); // Cancel attempt to close when unsaved add to save queue so we can display a popup. if (!doc->Open && doc->Dirty) diff --git a/imgui/imgui_draw.cpp b/imgui/imgui_draw.cpp index 27a04e8a..a3d5c2b3 100644 --- a/imgui/imgui_draw.cpp +++ b/imgui/imgui_draw.cpp @@ -391,7 +391,7 @@ void ImDrawList::ClearFreeMemory() ImDrawList* ImDrawList::CloneOutput() const { - auto dst = IM_NEW(ImDrawList(_Data)); + const auto dst = IM_NEW(ImDrawList(_Data)); dst->CmdBuffer = CmdBuffer; dst->IdxBuffer = IdxBuffer; dst->VtxBuffer = VtxBuffer; @@ -443,7 +443,7 @@ void ImDrawList::UpdateClipRect() } // Try to merge with previous command if it matches, else use current command - ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + const ImDrawCmd * prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) CmdBuffer.pop_back(); else @@ -462,7 +462,7 @@ void ImDrawList::UpdateTextureID() } // Try to merge with previous command if it matches, else use current command - ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + const ImDrawCmd * prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; if (curr_cmd->ElemCount == 0 && prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) CmdBuffer.pop_back(); else @@ -478,7 +478,7 @@ void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_ ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); if (intersect_with_current_clip_rect && _ClipRectStack.Size) { - ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + const ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; if (cr.x < current.x) cr.x = current.x; if (cr.y < current.y) cr.y = current.y; if (cr.z > current.z) cr.z = current.z; @@ -530,11 +530,11 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; draw_cmd.ElemCount += idx_count; - int vtx_buffer_old_size = VtxBuffer.Size; + const int vtx_buffer_old_size = VtxBuffer.Size; VtxBuffer.resize(vtx_buffer_old_size + vtx_count); _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size; - int idx_buffer_old_size = IdxBuffer.Size; + const int idx_buffer_old_size = IdxBuffer.Size; IdxBuffer.resize(idx_buffer_old_size + idx_count); _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size; } @@ -543,7 +543,7 @@ void ImDrawList::PrimReserve(int idx_count, int vtx_count) void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) { ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel); - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; @@ -558,7 +558,7 @@ void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) { ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; @@ -572,7 +572,7 @@ void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) { - ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + const ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; @@ -614,7 +614,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 PrimReserve(idx_count, vtx_count); // Temporary buffer - auto temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630 + const auto temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); //-V630 ImVec2* temp_points = temp_normals + points_count; for (int i1 = 0; i1 < count; i1++) @@ -644,7 +644,7 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; - unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + const unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; @@ -699,16 +699,16 @@ void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 for (int i1 = 0; i1 < count; i1++) { const int i2 = (i1+1) == points_count ? 0 : i1+1; - unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + const unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; // Average normals float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f; float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f; IM_FIXNORMAL2F(dm_x, dm_y); - float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE); - float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE); - float dm_in_x = dm_x * half_inner_thickness; - float dm_in_y = dm_y * half_inner_thickness; + const float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE); + const float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE); + const float dm_in_x = dm_x * half_inner_thickness; + const float dm_in_y = dm_y * half_inner_thickness; // Add temporary vertexes ImVec2* out_vtx = &temp_points[i2*4]; @@ -796,8 +796,8 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun PrimReserve(idx_count, vtx_count); // Add indexes for fill - unsigned int vtx_inner_idx = _VtxCurrentIdx; - unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + const unsigned int vtx_inner_idx = _VtxCurrentIdx; + const unsigned int vtx_outer_idx = _VtxCurrentIdx+1; for (int i = 2; i < points_count; i++) { _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); @@ -805,7 +805,7 @@ void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_coun } // Compute normals - auto temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630 + const auto temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630 for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) { const ImVec2& p0 = points[i0]; @@ -895,8 +895,8 @@ void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, floa static void PathBezierToCasteljau(ImVector* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) { - float dx = x4 - x1; - float dy = y4 - y1; + const float dx = x4 - x1; + const float dy = y4 - y1; float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; @@ -921,7 +921,7 @@ static void PathBezierToCasteljau(ImVector* path, float x1, float y1, fl void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) { - ImVec2 p1 = _Path.back(); + const ImVec2 p1 = _Path.back(); if (num_segments == 0) { // Auto-tessellated @@ -929,15 +929,15 @@ void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImV } else { - float t_step = 1.0f / (float)num_segments; + const float t_step = 1.0f / (float)num_segments; for (int i_step = 1; i_step <= num_segments; i_step++) { - float t = t_step * i_step; - float u = 1.0f - t; - float w1 = u*u*u; - float w2 = 3*u*u*t; - float w3 = 3*u*t*t; - float w4 = t*t*t; + const float t = t_step * i_step; + const float u = 1.0f - t; + const float w1 = u*u*u; + const float w2 = 3*u*u*t; + const float w3 = 3*u*t*t; + const float w4 = t*t*t; _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); } } @@ -1181,10 +1181,10 @@ void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_mi if (push_texture_id) PushTextureID(user_texture_id); - int vert_start_idx = VtxBuffer.Size; + const int vert_start_idx = VtxBuffer.Size; PathRect(p_min, p_max, rounding, rounding_corners); PathFillConvex(col); - int vert_end_idx = VtxBuffer.Size; + const int vert_end_idx = VtxBuffer.Size; ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true); if (push_texture_id) @@ -1215,7 +1215,7 @@ void ImDrawListSplitter::ClearFreeMemory() void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count) { IM_ASSERT(_Current == 0 && _Count <= 1); - int old_channels_count = _Channels.Size; + const int old_channels_count = _Channels.Size; if (old_channels_count < channels_count) _Channels.resize(channels_count); _Count = channels_count; @@ -1295,9 +1295,9 @@ void ImDrawListSplitter::Merge(ImDrawList* draw_list) ImDrawIdx* idx_write = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size - new_idx_buffer_count; for (int i = 1; i < _Count; i++) { - ImDrawChannel& ch = _Channels[i]; - if (int sz = ch._CmdBuffer.Size) { memcpy(cmd_write, ch._CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } - if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } + const ImDrawChannel & ch = _Channels[i]; + if (const int sz = ch._CmdBuffer.Size) { memcpy(cmd_write, ch._CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (const int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; } } draw_list->_IdxWritePtr = idx_write; draw_list->UpdateClipRect(); // We call this instead of AddDrawCmd(), so that empty channels won't produce an extra draw call. @@ -1365,17 +1365,17 @@ void ImDrawData::ScaleClipRects(const ImVec2& fb_scale) // Generic linear color gradient, write to RGB fields, leave A untouched. void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1) { - ImVec2 gradient_extent = gradient_p1 - gradient_p0; - float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); + const ImVec2 gradient_extent = gradient_p1 - gradient_p0; + const float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent); ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; - ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + const ImDrawVert * vert_end = draw_list->VtxBuffer.Data + vert_end_idx; for (ImDrawVert* vert = vert_start; vert < vert_end; vert++) { - float d = ImDot(vert->pos - gradient_p0, gradient_extent); - float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); - int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t); - int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t); - int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t); + const float d = ImDot(vert->pos - gradient_p0, gradient_extent); + const float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f); + const int r = ImLerp((int)(col0 >> IM_COL32_R_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_R_SHIFT) & 0xFF, t); + const int g = ImLerp((int)(col0 >> IM_COL32_G_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_G_SHIFT) & 0xFF, t); + const int b = ImLerp((int)(col0 >> IM_COL32_B_SHIFT) & 0xFF, (int)(col1 >> IM_COL32_B_SHIFT) & 0xFF, t); vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK); } } @@ -1390,7 +1390,7 @@ void ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int ve size.y != 0.0f ? (uv_size.y / size.y) : 0.0f); ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx; - ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx; + const ImDrawVert * vert_end = draw_list->VtxBuffer.Data + vert_end_idx; if (clamp) { const ImVec2 min = ImMin(uv_a, uv_b); @@ -1637,7 +1637,7 @@ static void Decode85(const unsigned char* src, unsigned char* dst) { while (*src) { - unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + const unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness. src += 5; dst += 4; @@ -1704,7 +1704,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float si ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) { const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data); - auto buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size); + const auto buf_decompressed_data = (unsigned char *)IM_ALLOC(buf_decompressed_size); stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); @@ -1715,7 +1715,7 @@ ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_d ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) { - int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + const int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size); Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); @@ -1768,10 +1768,10 @@ bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* ou return false; IM_ASSERT(CustomRectIds[0] != -1); - ImFontAtlasCustomRect& r = CustomRects[CustomRectIds[0]]; + const ImFontAtlasCustomRect & r = CustomRects[CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r.X, (float)r.Y); - ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; + const ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1]; *out_size = size; *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2]; out_uv_border[0] = (pos) * TexUvScale; @@ -1792,7 +1792,7 @@ void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], fl { for (unsigned int i = 0; i < 256; i++) { - unsigned int value = (unsigned int)(i * in_brighten_factor); + const unsigned int value = (unsigned int)(i * in_brighten_factor); out_table[i] = value > 255 ? 255 : (value & 0xFF); } } @@ -1836,7 +1836,7 @@ static void UnpackBoolVectorToFlatIndexList(const ImBoolVector* in, ImVectorStorage.begin(); const int* it_end = in->Storage.end(); for (const int* it = it_begin; it < it_end; it++) - if (int entries_32 = *it) + if (const int entries_32 = *it) for (int bit_n = 0; bit_n < 32; bit_n++) if (entries_32 & (1u << bit_n)) out->push_back((int)((it - it_begin) << 5) + bit_n); @@ -2124,7 +2124,7 @@ void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* f void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque) { - auto pack_context = (stbrp_context*)stbrp_context_opaque; + const auto pack_context = (stbrp_context*)stbrp_context_opaque; IM_ASSERT(pack_context != NULL); ImVector& user_rects = atlas->CustomRects; @@ -2153,7 +2153,7 @@ static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas) { IM_ASSERT(atlas->CustomRectIds[0] >= 0); IM_ASSERT(atlas->TexPixelsAlpha8 != NULL); - ImFontAtlasCustomRect& r = atlas->CustomRects[atlas->CustomRectIds[0]]; + const ImFontAtlasCustomRect & r = atlas->CustomRects[atlas->CustomRectIds[0]]; IM_ASSERT(r.ID == FONT_ATLAS_DEFAULT_TEX_DATA_ID); IM_ASSERT(r.IsPacked()); @@ -2449,7 +2449,7 @@ void ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end) while (text_end ? (text < text_end) : *text) { unsigned int c = 0; - int c_len = ImTextCharFromUtf8(&c, text, text_end); + const int c_len = ImTextCharFromUtf8(&c, text, text_end); text += c_len; if (c_len == 0) break; @@ -2467,7 +2467,7 @@ void ImFontGlyphRangesBuilder::AddRanges(const ImWchar* ranges) void ImFontGlyphRangesBuilder::BuildRanges(ImVector* out_ranges) { - int max_codepoint = 0x10000; + const int max_codepoint = 0x10000; for (int n = 0; n < max_codepoint; n++) if (GetBit(n)) { @@ -2532,7 +2532,7 @@ void ImFont::BuildLookupTable() GrowIndex(max_codepoint + 1); for (int i = 0; i < Glyphs.Size; i++) { - int codepoint = (int)Glyphs[i].Codepoint; + const int codepoint = (int)Glyphs[i].Codepoint; IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX; IndexLookup[codepoint] = (ImWchar)i; } @@ -2601,7 +2601,7 @@ void ImFont::AddGlyph(ImWchar codepoint, float x0, float y0, float x1, float y1, void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) { IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. - int index_size = IndexLookup.Size; + const int index_size = IndexLookup.Size; if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists return; @@ -2832,7 +2832,7 @@ void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col return; if (const ImFontGlyph* glyph = FindGlyph(c)) { - float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + const float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; pos.x = (float)(int)pos.x + DisplayOffset.x; pos.y = (float)(int)pos.y + DisplayOffset.y; draw_list->PrimReserve(6, 4); @@ -3088,8 +3088,8 @@ void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, Im if (x_start_norm > x_end_norm) ImSwap(x_start_norm, x_end_norm); - auto p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y); - auto p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y); + const auto p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y); + const auto p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y); if (rounding == 0.0f) { draw_list->AddRectFilled(p0, p1, col, 0.0f); diff --git a/imgui/imgui_impl_glfw.cpp b/imgui/imgui_impl_glfw.cpp index a9e72c6c..6d378de5 100644 --- a/imgui/imgui_impl_glfw.cpp +++ b/imgui/imgui_impl_glfw.cpp @@ -249,11 +249,11 @@ static void ImGui_ImplGlfw_UpdateMousePosAndButtons() static void ImGui_ImplGlfw_UpdateMouseCursor() { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(g_Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) return; - ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); + const ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor @@ -320,7 +320,7 @@ void ImGui_ImplGlfw_NewFrame() io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h); // Setup time step - double current_time = glfwGetTime(); + const double current_time = glfwGetTime(); io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); g_Time = current_time; diff --git a/imgui/imgui_impl_opengl2.cpp b/imgui/imgui_impl_opengl2.cpp index 8bb303ac..261bcb96 100644 --- a/imgui/imgui_impl_opengl2.cpp +++ b/imgui/imgui_impl_opengl2.cpp @@ -99,8 +99,8 @@ static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_wid void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); - int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + const int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + const int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width == 0 || fb_height == 0) return; @@ -115,8 +115,8 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height); // Will project scissor/clipping rectangles into framebuffer space - ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports - ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + const ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + const ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) @@ -181,7 +181,7 @@ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplOpenGL2_CreateFontsTexture() { // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. @@ -209,7 +209,7 @@ void ImGui_ImplOpenGL2_DestroyFontsTexture() { if (g_FontTexture) { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); glDeleteTextures(1, &g_FontTexture); io.Fonts->TexID = 0; g_FontTexture = 0; diff --git a/imgui/imgui_impl_opengl3.cpp b/imgui/imgui_impl_opengl3.cpp index d328db49..c3bf8ea0 100644 --- a/imgui/imgui_impl_opengl3.cpp +++ b/imgui/imgui_impl_opengl3.cpp @@ -145,10 +145,10 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid // Setup viewport, orthographic projection matrix // 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. glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); - float L = draw_data->DisplayPos.x; - float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; - float T = draw_data->DisplayPos.y; - float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; + const float L = draw_data->DisplayPos.x; + const float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x; + const float T = draw_data->DisplayPos.y; + const float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y; const float ortho_projection[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, @@ -182,8 +182,8 @@ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_wid void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) - int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); - int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); + const int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x); + const int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y); if (fb_width <= 0 || fb_height <= 0) return; @@ -214,11 +214,11 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha); GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb); GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha); - GLboolean last_enable_blend = glIsEnabled(GL_BLEND); - GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); - GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); - GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); - bool clip_origin_lower_left = true; + const GLboolean last_enable_blend = glIsEnabled(GL_BLEND); + const GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); + const GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); + const GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); + const bool clip_origin_lower_left = true; // Setup desired GL state // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts) @@ -230,8 +230,8 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); // Will project scissor/clipping rectangles into framebuffer space - ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports - ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) + const ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports + const ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2) // Render command lists for (int n = 0; n < draw_data->CmdListsCount; n++) @@ -320,7 +320,7 @@ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data) bool ImGui_ImplOpenGL3_CreateFontsTexture() { // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. @@ -350,7 +350,7 @@ void ImGui_ImplOpenGL3_DestroyFontsTexture() { if (g_FontTexture) { - ImGuiIO& io = ImGui::GetIO(); + const ImGuiIO & io = ImGui::GetIO(); glDeleteTextures(1, &g_FontTexture); io.Fonts->TexID = 0; g_FontTexture = 0; @@ -408,7 +408,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() int glsl_version = 130; sscanf(g_GlslVersionString, "#version %d", &glsl_version); - auto vertex_shader_glsl_120 = + const auto vertex_shader_glsl_120 = "uniform mat4 ProjMtx;\n" "attribute vec2 Position;\n" "attribute vec2 UV;\n" @@ -422,7 +422,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; - auto vertex_shader_glsl_130 = + const auto vertex_shader_glsl_130 = "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" @@ -436,7 +436,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; - auto vertex_shader_glsl_300_es = + const auto vertex_shader_glsl_300_es = "precision mediump float;\n" "layout (location = 0) in vec2 Position;\n" "layout (location = 1) in vec2 UV;\n" @@ -451,7 +451,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; - auto vertex_shader_glsl_410_core = + const auto vertex_shader_glsl_410_core = "layout (location = 0) in vec2 Position;\n" "layout (location = 1) in vec2 UV;\n" "layout (location = 2) in vec4 Color;\n" @@ -465,7 +465,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; - auto fragment_shader_glsl_120 = + const auto fragment_shader_glsl_120 = "#ifdef GL_ES\n" " precision mediump float;\n" "#endif\n" @@ -477,7 +477,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" "}\n"; - auto fragment_shader_glsl_130 = + const auto fragment_shader_glsl_130 = "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" @@ -487,7 +487,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " Out_Color = FBOUT(Frag_Color * texture(Texture, Frag_UV.st));\n" "}\n"; - auto fragment_shader_glsl_300_es = + const auto fragment_shader_glsl_300_es = "precision mediump float;\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" @@ -498,7 +498,7 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() " Out_Color = FBOUT(Frag_Color * texture(Texture, Frag_UV.st));\n" "}\n"; - auto fragment_shader_glsl_410_core = + const auto fragment_shader_glsl_410_core = "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "uniform sampler2D Texture;\n" @@ -539,8 +539,8 @@ bool ImGui_ImplOpenGL3_CreateDeviceObjects() glCompileShader(g_VertHandle); CheckShader(g_VertHandle, "vertex shader"); - auto fbout_copy = "vec4 FBOUT(vec4 x) { return x; }\n"; - auto fbout_gamma = "vec4 FBOUT(vec4 x) { return vec4(pow(x.rgb, vec3(1.0 / 2.2)), x.a); }\n"; + const auto fbout_copy = "vec4 FBOUT(vec4 x) { return x; }\n"; + const auto fbout_gamma = "vec4 FBOUT(vec4 x) { return vec4(pow(x.rgb, vec3(1.0 / 2.2)), x.a); }\n"; const GLchar* fragment_shader_with_version[3] = { g_GlslVersionString, Global.gfx_shadergamma ? fbout_gamma : fbout_copy, fragment_shader }; g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); diff --git a/imgui/imgui_internal.h b/imgui/imgui_internal.h index 6d393103..76cc14a2 100644 --- a/imgui/imgui_internal.h +++ b/imgui/imgui_internal.h @@ -260,7 +260,8 @@ static inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t) static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } -static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; } +static inline float ImInvLength(const ImVec2& lhs, float fail_value) { + const float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / ImSqrt(d); return fail_value; } static inline float ImFloor(float f) { return (float)(int)f; } static inline ImVec2 ImFloor(const ImVec2& v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } static inline int ImModPositive(int a, int b) { return (a + b) % b; } @@ -277,8 +278,12 @@ struct ImBoolVector ImBoolVector() { } void Resize(int sz) { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); } void Clear() { Storage.clear(); } - bool GetBit(int n) const { int off = (n >> 5); int mask = 1 << (n & 31); return (Storage[off] & mask) != 0; } - void SetBit(int n, bool v) { int off = (n >> 5); int mask = 1 << (n & 31); if (v) Storage[off] |= mask; else Storage[off] &= ~mask; } + bool GetBit(int n) const { + const int off = (n >> 5); + const int mask = 1 << (n & 31); return (Storage[off] & mask) != 0; } + void SetBit(int n, bool v) { + const int off = (n >> 5); + const int mask = 1 << (n & 31); if (v) Storage[off] |= mask; else Storage[off] &= ~mask; } }; // Helper: ImPool<>. Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer, @@ -1375,11 +1380,15 @@ public: // We don't use g.FontSize because the window may be != g.CurrentWidow. ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } - float CalcFontSize() const { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } - float TitleBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; } + float CalcFontSize() const { + const ImGuiContext & g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; } + float TitleBarHeight() const { + const ImGuiContext & g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; } ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } - float MenuBarHeight() const { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; } - ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } + float MenuBarHeight() const { + const ImGuiContext & g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; } + ImRect MenuBarRect() const { + const float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } }; // Backup and restore just enough data to be able to use IsItemHovered() on item A after another B in the same window has overwritten the data. @@ -1391,7 +1400,8 @@ struct ImGuiItemHoveredDataBackup ImRect LastItemDisplayRect; ImGuiItemHoveredDataBackup() { Backup(); } - void Backup() { ImGuiWindow* window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; } + void Backup() { + const ImGuiWindow * window = GImGui->CurrentWindow; LastItemId = window->DC.LastItemId; LastItemStatusFlags = window->DC.LastItemStatusFlags; LastItemRect = window->DC.LastItemRect; LastItemDisplayRect = window->DC.LastItemDisplayRect; } void Restore() const { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.LastItemId = LastItemId; window->DC.LastItemStatusFlags = LastItemStatusFlags; window->DC.LastItemRect = LastItemRect; window->DC.LastItemDisplayRect = LastItemDisplayRect; } }; @@ -1476,8 +1486,10 @@ namespace ImGui // If this ever crash because g.CurrentWindow is NULL it means that either // - ImGui::NewFrame() has never been called, which is illegal. // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. - inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } - inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindowRead() { + const ImGuiContext & g = *GImGui; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindow() { + const ImGuiContext & g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; } IMGUI_API ImGuiWindow* FindWindowByID(ImGuiID id); IMGUI_API ImGuiWindow* FindWindowByName(const char* name); IMGUI_API void FocusWindow(ImGuiWindow* window); @@ -1497,7 +1509,8 @@ namespace ImGui IMGUI_API void GcAwakeTransientWindowBuffers(ImGuiWindow* window); IMGUI_API void SetCurrentFont(ImFont* font); - inline ImFont* GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } + inline ImFont* GetDefaultFont() { + const ImGuiContext & g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; } inline ImDrawList* GetForegroundDrawList(ImGuiWindow*) { ImGuiContext& g = *GImGui; return &g.ForegroundDrawList; } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. // Init @@ -1526,9 +1539,12 @@ namespace ImGui IMGUI_API ImVec2 ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect); // Basic Accessors - inline ImGuiID GetItemID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.LastItemId; } - inline ImGuiID GetActiveID() { ImGuiContext& g = *GImGui; return g.ActiveId; } - inline ImGuiID GetFocusID() { ImGuiContext& g = *GImGui; return g.NavId; } + inline ImGuiID GetItemID() { + const ImGuiContext & g = *GImGui; return g.CurrentWindow->DC.LastItemId; } + inline ImGuiID GetActiveID() { + const ImGuiContext & g = *GImGui; return g.ActiveId; } + inline ImGuiID GetFocusID() { + const ImGuiContext & g = *GImGui; return g.NavId; } IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); IMGUI_API void SetFocusID(ImGuiID id, ImGuiWindow* window); IMGUI_API void ClearActiveID(); @@ -1642,8 +1658,10 @@ namespace ImGui #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // 2019/06/07: Updating prototypes of some of the internal functions. Leaving those for reference for a short while. - inline void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale=1.0f) { ImGuiWindow* window = GetCurrentWindow(); RenderArrow(window->DrawList, pos, GetColorU32(ImGuiCol_Text), dir, scale); } - inline void RenderBullet(ImVec2 pos) { ImGuiWindow* window = GetCurrentWindow(); RenderBullet(window->DrawList, pos, GetColorU32(ImGuiCol_Text)); } + inline void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale=1.0f) { + const ImGuiWindow * window = GetCurrentWindow(); RenderArrow(window->DrawList, pos, GetColorU32(ImGuiCol_Text), dir, scale); } + inline void RenderBullet(ImVec2 pos) { + const ImGuiWindow * window = GetCurrentWindow(); RenderBullet(window->DrawList, pos, GetColorU32(ImGuiCol_Text)); } #endif // Widgets @@ -1683,7 +1701,8 @@ namespace ImGui // InputText IMGUI_API bool InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format); - inline bool TempInputTextIsActive(ImGuiID id) { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputTextId == id); } + inline bool TempInputTextIsActive(ImGuiID id) { + const ImGuiContext & g = *GImGui; return (g.ActiveId == id && g.TempInputTextId == id); } // Color IMGUI_API void ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags); diff --git a/imgui/imgui_widgets.cpp b/imgui/imgui_widgets.cpp index 4c6c5f62..ba127d5e 100644 --- a/imgui/imgui_widgets.cpp +++ b/imgui/imgui_widgets.cpp @@ -135,11 +135,11 @@ static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) @@ -163,7 +163,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) ImVec2 pos = text_pos; if (!g.LogEnabled) { - int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height); + const int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; @@ -217,7 +217,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) } text_size.y = (pos - text_pos).y; - ImRect bb(text_pos, text_pos + text_size); + const ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); ItemAdd(bb, 0); } @@ -226,7 +226,7 @@ void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); - ImRect bb(text_pos, text_pos + text_size); + const ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); if (!ItemAdd(bb, 0)) return; @@ -251,7 +251,7 @@ void ImGui::Text(const char* fmt, ...) void ImGui::TextV(const char* fmt, va_list args) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; @@ -300,8 +300,8 @@ void ImGui::TextWrapped(const char* fmt, ...) void ImGui::TextWrappedV(const char* fmt, va_list args) { - ImGuiWindow* window = GetCurrentWindow(); - bool need_backup = (window->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set + const ImGuiWindow * window = GetCurrentWindow(); + const bool need_backup = (window->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set if (need_backup) PushTextWrapPos(0.0f); TextV(fmt, args); @@ -320,7 +320,7 @@ void ImGui::LabelText(const char* label, const char* fmt, ...) // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; @@ -354,7 +354,7 @@ void ImGui::BulletText(const char* fmt, ...) // Text with a little bullet aligned to the typical tree node. void ImGui::BulletTextV(const char* fmt, va_list args) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; @@ -372,7 +372,7 @@ void ImGui::BulletTextV(const char* fmt, va_list args) return; // Render - ImU32 text_col = GetColorU32(ImGuiCol_Text); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col); RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); } @@ -552,8 +552,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool if (g.NavActivateDownId == id) { - bool nav_activated_by_code = (g.NavActivateId == id); - bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed); + const bool nav_activated_by_code = (g.NavActivateId == id); + const bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed); if (nav_activated_by_code || nav_activated_by_inputs) pressed = true; if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id) @@ -584,8 +584,8 @@ bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool { if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) && !g.DragDropActive) { - bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[0]; - bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay; // Repeat mode trumps + const bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[0]; + const bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay; // Repeat mode trumps if (!is_double_click_release && !is_repeating_already) pressed = true; } @@ -613,7 +613,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -621,7 +621,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y; - ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + const ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); const ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); @@ -631,7 +631,7 @@ bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); @@ -656,9 +656,9 @@ bool ImGui::Button(const char* label, const ImVec2& size_arg) bool ImGui::SmallButton(const char* label) { ImGuiContext& g = *GImGui; - float backup_padding_y = g.Style.FramePadding.y; + const float backup_padding_y = g.Style.FramePadding.y; g.Style.FramePadding.y = 0.0f; - bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine); + const bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine); g.Style.FramePadding.y = backup_padding_y; return pressed; } @@ -675,14 +675,14 @@ bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f); const ImGuiID id = window->GetID(str_id); - ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); + const ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(size); if (!ItemAdd(bb, id)) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held); return pressed; } @@ -693,7 +693,7 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiID id = window->GetID(str_id); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); const float default_size = GetFrameHeight(); @@ -705,7 +705,7 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu flags |= ImGuiButtonFlags_Repeat; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); @@ -719,34 +719,34 @@ bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiBu bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) { - float sz = GetFrameHeight(); + const float sz = GetFrameHeight(); return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), 0); } // Button to close a window bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; // We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window. // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible). const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); - bool is_clipped = !ItemAdd(bb, id); + const bool is_clipped = !ItemAdd(bb, id); bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held); if (is_clipped) return pressed; // Render - ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); + const ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered); ImVec2 center = bb.GetCenter(); if (hovered) window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col, 12); - float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; - ImU32 cross_col = GetColorU32(ImGuiCol_Text); + const float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f; + const ImU32 cross_col = GetColorU32(ImGuiCol_Text); center -= ImVec2(0.5f, 0.5f); window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f); window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f); @@ -756,18 +756,18 @@ bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size) bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); + const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); ItemAdd(bb, id); bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); // Render - ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); - ImU32 text_col = GetColorU32(ImGuiCol_Text); - ImVec2 center = bb.GetCenter(); + const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); + const ImVec2 center = bb.GetCenter(); if (hovered || held) window->DrawList->AddCircleFilled(center/*+ ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, bg_col, 12); RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); @@ -793,7 +793,7 @@ ImGuiID ImGui::GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis) bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float size_avail_v, float size_contents_v, ImDrawCornerFlags rounding_corners) { ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiWindow * window = g.CurrentWindow; if (window->SkipItems) return false; @@ -831,13 +831,13 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa bool hovered = false; ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus); - float scroll_max = ImMax(1.0f, size_contents_v - size_avail_v); + const float scroll_max = ImMax(1.0f, size_contents_v - size_avail_v); float scroll_ratio = ImSaturate(*p_scroll_v / scroll_max); float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; if (held && allow_interaction && grab_h_norm < 1.0f) { - float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; - float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + const float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; + const float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; // Click position in scrollbar normalized space (0.0f->1.0f) const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); @@ -883,7 +883,7 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, floa void ImGui::Scrollbar(ImGuiAxis axis) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = GetScrollbarID(window, axis); @@ -915,7 +915,7 @@ void ImGui::Scrollbar(ImGuiAxis axis) void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; @@ -947,7 +947,7 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; // Default to using texture ID as ID. User can still push string/integer prefixes. @@ -964,7 +964,7 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); @@ -983,7 +983,7 @@ bool ImGui::Checkbox(const char* label, bool* v) if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -996,7 +996,7 @@ bool ImGui::Checkbox(const char* label, bool* v) return false; bool hovered, held; - bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + const bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) { *v = !(*v); @@ -1006,11 +1006,11 @@ bool ImGui::Checkbox(const char* label, bool* v) const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); RenderNavHighlight(total_bb, id); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); - ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); + const ImU32 check_col = GetColorU32(ImGuiCol_CheckMark); if (window->DC.ItemFlags & ImGuiItemFlags_MixedValue) { // Undocumented tristate/mixed/indeterminate checkbox (#2644) - ImVec2 pad(ImMax(1.0f, (float)(int)(square_sz / 3.6f)), ImMax(1.0f, (float)(int)(square_sz / 3.6f))); + const ImVec2 pad(ImMax(1.0f, (float)(int)(square_sz / 3.6f)), ImMax(1.0f, (float)(int)(square_sz / 3.6f))); window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding); } else if (*v) @@ -1031,7 +1031,7 @@ bool ImGui::Checkbox(const char* label, bool* v) bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { bool v = ((*flags & flags_value) == flags_value); - bool pressed = Checkbox(label, &v); + const bool pressed = Checkbox(label, &v); if (pressed) { if (v) @@ -1049,7 +1049,7 @@ bool ImGui::RadioButton(const char* label, bool active) if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -1068,7 +1068,7 @@ bool ImGui::RadioButton(const char* label, bool active) const float radius = (square_sz - 1.0f) * 0.5f; bool hovered, held; - bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); + const bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) MarkItemEdited(id); @@ -1106,15 +1106,15 @@ bool ImGui::RadioButton(const char* label, int* v, int v_button) // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; - ImVec2 pos = window->DC.CursorPos; - ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f); + const ImVec2 pos = window->DC.CursorPos; + const ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f); ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, 0)) @@ -1135,18 +1135,18 @@ void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* over overlay = overlay_buf; } - ImVec2 overlay_size = CalcTextSize(overlay, NULL); + const ImVec2 overlay_size = CalcTextSize(overlay, NULL); if (overlay_size.x > 0.0f) RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); } void ImGui::Bullet() { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); @@ -1158,7 +1158,7 @@ void ImGui::Bullet() } // Render and stay on same line - ImU32 text_col = GetColorU32(ImGuiCol_Text); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col); SameLine(0, style.FramePadding.x * 2.0f); } @@ -1178,7 +1178,7 @@ void ImGui::Bullet() void ImGui::Spacing() { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; ItemSize(ImVec2(0,0)); @@ -1186,7 +1186,7 @@ void ImGui::Spacing() void ImGui::Dummy(const ImVec2& size) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; @@ -1201,7 +1201,7 @@ void ImGui::NewLine() if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; window->DC.LayoutType = ImGuiLayoutType_Vertical; if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. @@ -1217,7 +1217,7 @@ void ImGui::AlignTextToFramePadding() if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2); window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y); } @@ -1225,20 +1225,20 @@ void ImGui::AlignTextToFramePadding() // Horizontal/vertical separating line void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected - float thickness_draw = 1.0f; - float thickness_layout = 0.0f; + const float thickness_draw = 1.0f; + const float thickness_layout = 0.0f; if (flags & ImGuiSeparatorFlags_Vertical) { // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout. - float y1 = window->DC.CursorPos.y; - float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y; + const float y1 = window->DC.CursorPos.y; + const float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y; const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness_draw, y2)); ItemSize(ImVec2(thickness_layout, 0.0f)); if (!ItemAdd(bb, 0)) @@ -1253,7 +1253,7 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) { // Horizontal Separator float x1 = window->Pos.x; - float x2 = window->Pos.x + window->Size.x; + const float x2 = window->Pos.x + window->Size.x; if (!window->DC.GroupStack.empty()) x1 += window->DC.Indent.x; @@ -1289,8 +1289,8 @@ void ImGui::SeparatorEx(ImGuiSeparatorFlags flags) void ImGui::Separator() { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (window->SkipItems) return; @@ -1303,12 +1303,12 @@ void ImGui::Separator() // Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus; - bool item_add = ItemAdd(bb, id); + const bool item_add = ItemAdd(bb, id); window->DC.ItemFlags = item_flags_backup; if (!item_add) return false; @@ -1326,12 +1326,12 @@ bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float ImRect bb_render = bb; if (held) { - ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min; + const ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min; float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x; // Minimum pane size - float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1); - float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2); + const float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1); + const float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2); if (mouse_delta < -size_1_maximum_delta) mouse_delta = -size_1_maximum_delta; if (mouse_delta > size_2_maximum_delta) @@ -1360,9 +1360,9 @@ bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs) { - auto a = (const ImGuiShrinkWidthItem*)lhs; - auto b = (const ImGuiShrinkWidthItem*)rhs; - if (int d = (int)(b->Width - a->Width)) + const auto a = (const ImGuiShrinkWidthItem*)lhs; + const auto b = (const ImGuiShrinkWidthItem*)rhs; + if (const int d = (int)(b->Width - a->Width)) return d; return (b->Index - a->Index); } @@ -1381,8 +1381,8 @@ void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_exc { while (count_same_width < count && items[0].Width <= items[count_same_width].Width) count_same_width++; - float max_width_to_remove_per_item = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); - float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); + const float max_width_to_remove_per_item = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f); + const float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item); for (int item_n = 0; item_n < count_same_width; item_n++) items[item_n].Width -= width_to_remove_per_item; width_excess -= width_to_remove_per_item * count_same_width; @@ -1393,7 +1393,7 @@ void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_exc width_excess = 0.0f; for (int n = 0; n < count; n++) { - float width_rounded = ImFloor(items[n].Width); + const float width_rounded = ImFloor(items[n].Width); width_excess += items[n].Width - width_rounded; items[n].Width = width_rounded; } @@ -1413,7 +1413,7 @@ void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_exc static float CalcMaxPopupHeightFromItemCount(int items_count) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (items_count <= 0) return FLT_MAX; return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2); @@ -1423,7 +1423,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF { // Always consume the SetNextWindowSizeConstraint() call in our early return paths ImGuiContext& g = *GImGui; - bool has_window_size_constraint = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) != 0; + const bool has_window_size_constraint = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) != 0; g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; ImGuiWindow* window = GetCurrentWindow(); @@ -1446,7 +1446,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF return false; bool hovered, held; - bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); + const bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); bool popup_open = IsPopupOpen(id); const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); @@ -1456,8 +1456,8 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(value_x2, frame_bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Left); if (!(flags & ImGuiComboFlags_NoArrowButton)) { - ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); - ImU32 text_col = GetColorU32(ImGuiCol_Text); + const ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 text_col = GetColorU32(ImGuiCol_Text); window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); if (value_x2 + arrow_size - style.FramePadding.x <= frame_bb.Max.x) RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f); @@ -1503,18 +1503,18 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF if (ImGuiWindow* popup_window = FindWindowByName(name)) if (popup_window->WasActive) { - ImVec2 size_expected = CalcWindowExpectedSize(popup_window); + const ImVec2 size_expected = CalcWindowExpectedSize(popup_window); if (flags & ImGuiComboFlags_PopupAlignLeft) popup_window->AutoPosLastDirection = ImGuiDir_Left; - ImRect r_outer = GetWindowAllowedExtentRect(popup_window); - ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox); + const ImRect r_outer = GetWindowAllowedExtentRect(popup_window); + const ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox); SetNextWindowPos(pos); } // Horizontally align ourselves with the framed text - ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; + const ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(style.FramePadding.x, style.WindowPadding.y)); - bool ret = Begin(name, NULL, window_flags); + const bool ret = Begin(name, NULL, window_flags); PopStyleVar(); if (!ret) { @@ -1533,7 +1533,7 @@ void ImGui::EndCombo() // Getter for the old Combo() API: const char*[] static bool Items_ArrayGetter(void* data, int idx, const char** out_text) { - auto items = (const char* const*)data; + const auto items = (const char* const*)data; if (out_text) *out_text = items[idx]; return true; @@ -1543,7 +1543,7 @@ static bool Items_ArrayGetter(void* data, int idx, const char** out_text) static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) { // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. - auto items_separated_by_zeros = (const char*)data; + const auto items_separated_by_zeros = (const char*)data; int items_count = 0; const char* p = items_separated_by_zeros; while (*p) @@ -1563,7 +1563,7 @@ static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) // Old API, prefer using BeginCombo() nowadays if you can. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; // Call the getter to obtain the preview string which is a parameter to BeginCombo() const char* preview_value = NULL; @@ -1618,7 +1618,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa p += strlen(p) + 1; items_count++; } - bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); + const bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); return value_changed; } @@ -1794,7 +1794,7 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b int arg1i = 0; if (data_type == ImGuiDataType_S32) { - auto v = (int*)data_ptr; + const auto v = (int*)data_ptr; int arg0i = *v; float arg1f = 0.0f; if (op && sscanf(initial_value_buf, format, &arg0i) < 1) @@ -1809,7 +1809,7 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b { // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in format = "%f"; - auto v = (float*)data_ptr; + const auto v = (float*)data_ptr; float arg0f = *v, arg1f = 0.0f; if (op && sscanf(initial_value_buf, format, &arg0f) < 1) return false; @@ -1823,7 +1823,7 @@ bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_b else if (data_type == ImGuiDataType_Double) { format = "%lf"; // scanf differentiate float/double unlike printf which forces everything to double because of ellipsis - auto v = (double*)data_ptr; + const auto v = (double*)data_ptr; double arg0f = *v, arg1f = 0.0; if (op && sscanf(initial_value_buf, format, &arg0f) < 1) return false; @@ -1947,7 +1947,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { - int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; + const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis]; v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision)); } @@ -1958,10 +1958,11 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const adjust_delta = -adjust_delta; // Clear current value on activation - // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. - bool is_just_activated = g.ActiveIdIsJustActivated; - bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); - bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0)); + // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right + // side, keep the 300. + const bool is_just_activated = g.ActiveIdIsJustActivated; + const bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); + const bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0)); if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power) { g.DragCurrentAccum = 0.0f; @@ -2029,7 +2030,7 @@ bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragFlags flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.ActiveId == id) { if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0]) @@ -2042,10 +2043,14 @@ bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_s switch (data_type) { - case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS8*) v_min : IM_S8_MIN, v_max ? *(const ImS8*)v_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)v = (ImS8)v32; return r; } - case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU8*) v_min : IM_U8_MIN, v_max ? *(const ImU8*)v_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)v = (ImU8)v32; return r; } - case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS16*)v_min : IM_S16_MIN, v_max ? *(const ImS16*)v_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)v = (ImS16)v32; return r; } - case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU16*)v_min : IM_U16_MIN, v_max ? *(const ImU16*)v_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)v = (ImU16)v32; return r; } + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; + const bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS8*) v_min : IM_S8_MIN, v_max ? *(const ImS8*)v_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; + const bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU8*) v_min : IM_U8_MIN, v_max ? *(const ImU8*)v_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; + const bool r = DragBehaviorT(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS16*)v_min : IM_S16_MIN, v_max ? *(const ImS16*)v_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; + const bool r = DragBehaviorT(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU16*)v_min : IM_U16_MIN, v_max ? *(const ImU16*)v_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)v = (ImU16)v32; return r; } case ImGuiDataType_S32: return DragBehaviorT(data_type, (ImS32*)v, v_speed, v_min ? *(const ImS32* )v_min : IM_S32_MIN, v_max ? *(const ImS32* )v_max : IM_S32_MAX, format, power, flags); case ImGuiDataType_U32: return DragBehaviorT(data_type, (ImU32*)v, v_speed, v_min ? *(const ImU32* )v_min : IM_U32_MIN, v_max ? *(const ImU32* )v_max : IM_U32_MAX, format, power, flags); case ImGuiDataType_S64: return DragBehaviorT(data_type, (ImS64*)v, v_speed, v_min ? *(const ImS64* )v_min : IM_S64_MIN, v_max ? *(const ImS64* )v_max : IM_S64_MAX, format, power, flags); @@ -2087,7 +2092,7 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa // Tabbing or CTRL-clicking on Drag turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - bool temp_input_is_active = TempInputTextIsActive(id); + const bool temp_input_is_active = TempInputTextIsActive(id); bool temp_input_start = false; if (!temp_input_is_active) { @@ -2134,16 +2139,16 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, floa bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min, const void* v_max, const char* format, float power) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components, CalcItemWidth()); - size_t type_size = GDataTypeInfo[data_type].Size; + const size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { PushID(i); @@ -2189,11 +2194,11 @@ bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); @@ -2234,11 +2239,11 @@ bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2, CalcItemWidth()); @@ -2482,10 +2487,14 @@ bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type { switch (data_type) { - case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)v_min, *(const ImS8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)v = (ImS8)v32; return r; } - case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)v_min, *(const ImU8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)v = (ImU8)v32; return r; } - case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)v_min, *(const ImS16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)v = (ImS16)v32; return r; } - case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)v_min, *(const ImU16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)v = (ImU16)v32; return r; } + case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; + const bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)v_min, *(const ImS8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)v = (ImS8)v32; return r; } + case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; + const bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)v_min, *(const ImU8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)v = (ImU8)v32; return r; } + case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; + const bool r = SliderBehaviorT(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)v_min, *(const ImS16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)v = (ImS16)v32; return r; } + case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; + const bool r = SliderBehaviorT(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)v_min, *(const ImU16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)v = (ImU16)v32; return r; } case ImGuiDataType_S32: IM_ASSERT(*(const ImS32*)v_min >= IM_S32_MIN/2 && *(const ImS32*)v_max <= IM_S32_MAX/2); return SliderBehaviorT(bb, id, data_type, (ImS32*)v, *(const ImS32*)v_min, *(const ImS32*)v_max, format, power, flags, out_grab_bb); @@ -2537,7 +2546,7 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co // Tabbing or CTRL-clicking on Slider turns it into an input box const bool hovered = ItemHoverable(frame_bb, id); - bool temp_input_is_active = TempInputTextIsActive(id); + const bool temp_input_is_active = TempInputTextIsActive(id); bool temp_input_start = false; if (!temp_input_is_active) { @@ -2589,16 +2598,16 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, co // Add multiple sliders on 1 line for compact edition of multiple components bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components, CalcItemWidth()); - size_t type_size = GDataTypeInfo[data_type].Size; + const size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { PushID(i); @@ -2647,7 +2656,7 @@ bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, fl if (format == NULL) format = "%.0f deg"; float v_deg = (*v_rad) * 360.0f / (2*IM_PI); - bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); + const bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); *v_rad = v_deg * (2*IM_PI) / 360.0f; return value_changed; } @@ -2765,7 +2774,7 @@ bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, // We don't use strchr() because our strings are usually very short and often start with '%' const char* ImParseFormatFindStart(const char* fmt) { - while (char c = fmt[0]) + while (const char c = fmt[0]) { if (c == '%' && fmt[1] != '%') return fmt; @@ -2873,7 +2882,7 @@ bool ImGui::TempInputTextScalar(const ImRect& bb, ImGuiID id, const char* label, bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_ptr, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return false; @@ -2945,16 +2954,16 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_p bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components, CalcItemWidth()); - size_t type_size = GDataTypeInfo[data_type].Size; + const size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { PushID(i); @@ -3092,7 +3101,7 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** { int line_count = 0; const char* s = text_begin; - while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding + while (const char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding if (c == '\n') line_count++; s--; @@ -3104,8 +3113,8 @@ static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) { - ImGuiContext& g = *GImGui; - ImFont* font = g.Font; + const ImGuiContext & g = *GImGui; + const ImFont * font = g.Font; const float line_height = g.FontSize; const float scale = line_height / font->FontSize; @@ -3115,7 +3124,7 @@ static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* t const ImWchar* s = text_begin; while (s < text_end) { - unsigned int c = (unsigned int)(*s++); + const unsigned int c = (unsigned int)(*s++); if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); @@ -3153,7 +3162,9 @@ namespace ImStb static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->TextW[idx]; } -static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *GImGui; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { + const ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; + const ImGuiContext & g = *GImGui; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) @@ -3176,7 +3187,8 @@ static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; } static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } #else -static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; + const int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } #endif #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL @@ -3191,7 +3203,7 @@ static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) // Offset remaining text (FIXME-OPT: Use memmove) const ImWchar* src = obj->TextW.Data + pos + n; - while (ImWchar c = *src++) + while (const ImWchar c = *src++) *dst++ = c; *dst = '\0'; } @@ -3269,7 +3281,7 @@ void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) IM_ASSERT(pos + bytes_count <= BufTextLen); char* dst = Buf + pos; const char* src = Buf + pos + bytes_count; - while (char c = *src++) + while (const char c = *src++) *dst++ = c; *dst = '\0'; @@ -3296,7 +3308,7 @@ void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, cons ImGuiInputTextState* edit_state = &g.InputTextState; IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); IM_ASSERT(Buf == edit_state->TextA.Data); - int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; + const int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; edit_state->TextA.reserve(new_buf_size + 1); Buf = edit_state->TextA.Data; BufSize = edit_state->BufCapacityA = new_buf_size; @@ -4276,7 +4288,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { value_changed = true; - char* p = buf; + const char * p = buf; while (*p == '#' || ImCharIsBlankA(*p)) p++; i[0] = i[1] = i[2] = i[3] = 0; @@ -4289,7 +4301,7 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag OpenPopupOnItemClick("context"); } - ImGuiWindow* picker_active_window = NULL; + const ImGuiWindow * picker_active_window = NULL; if (!(flags & ImGuiColorEditFlags_NoSmallPreview)) { const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x; @@ -4317,8 +4329,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag TextEx(label, label_display_end); Spacing(); } - ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; - ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; + const ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; + const ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); EndPopup(); @@ -4399,10 +4411,10 @@ bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags fl static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b) { - float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f; - int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t); - int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t); - int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t); + const float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f; + const int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t); + const int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t); + const int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t); return IM_COL32(r, g, b, 0xFF); } @@ -4411,11 +4423,11 @@ static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b) // I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether. void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) { - ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col)); - ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col)); + const ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col)); + const ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col)); window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags); int yi = 0; @@ -4446,7 +4458,7 @@ void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU // Helper for ColorPicker4() static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha) { - ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha); + const ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha); ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8)); ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8)); ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8)); @@ -4831,9 +4843,9 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiID id = window->GetID(desc_id); - float default_size = GetFrameHeight(); + const float default_size = GetFrameHeight(); if (size.x == 0.0f) size.x = default_size; if (size.y == 0.0f) @@ -4844,7 +4856,7 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held); if (flags & ImGuiColorEditFlags_NoAlpha) flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf); @@ -4853,22 +4865,22 @@ bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFl if (flags & ImGuiColorEditFlags_InputHSV) ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z); - ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f); - float grid_step = ImMin(size.x, size.y) / 2.99f; - float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); + const ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f); + const float grid_step = ImMin(size.x, size.y) / 2.99f; + const float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); ImRect bb_inner = bb; - float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. + const float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. bb_inner.Expand(off); if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) { - float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f); + const float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f); RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight); window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft); } else { // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha - ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha; + const ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha; if (col_source.w < 1.0f) RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); else @@ -4923,7 +4935,7 @@ void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; BeginTooltipEx(0, true); const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; @@ -4933,8 +4945,8 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags Separator(); } - ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); - ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); + const ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); + const ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); SameLine(); @@ -4957,8 +4969,8 @@ void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) { - bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__DisplayMask); - bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask); + const bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__DisplayMask); + const bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask); if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) return; ImGuiContext& g = *GImGui; @@ -5005,14 +5017,14 @@ void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags) { - bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask); - bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar); + const bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask); + const bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar); if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context")) return; ImGuiContext& g = *GImGui; if (allow_opt_picker) { - ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function + const ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function PushItemWidth(picker_size.x); for (int picker_type = 0; picker_type < 2; picker_type++) { @@ -5060,7 +5072,7 @@ bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); - bool is_open = TreeNodeExV(str_id, 0, fmt, args); + const bool is_open = TreeNodeExV(str_id, 0, fmt, args); va_end(args); return is_open; } @@ -5069,7 +5081,7 @@ bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); - bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); + const bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); va_end(args); return is_open; } @@ -5105,7 +5117,7 @@ bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* { va_list args; va_start(args, fmt); - bool is_open = TreeNodeExV(str_id, flags, fmt, args); + const bool is_open = TreeNodeExV(str_id, flags, fmt, args); va_end(args); return is_open; } @@ -5114,7 +5126,7 @@ bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* { va_list args; va_start(args, fmt); - bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + const bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); va_end(args); return is_open; } @@ -5147,8 +5159,8 @@ bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) return true; // We only write to the tree storage if the user clicks (or explicitly use the SetNextItemOpen function) - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; bool is_open; @@ -5193,7 +5205,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (window->SkipItems) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); @@ -5236,7 +5248,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) window->DC.TreeMayJumpToParentOnPopMask |= (1 << window->DC.TreeDepth); - bool item_add = ItemAdd(interact_bb, id); + const bool item_add = ItemAdd(interact_bb, id); window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; window->DC.LastItemDisplayRect = frame_bb; @@ -5261,11 +5273,11 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l if (!is_leaf) button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; - bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; + const bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; const bool was_selected = selected; bool hovered, held; - bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + const bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); bool toggled = false; if (!is_leaf) { @@ -5306,7 +5318,7 @@ bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* l // Render const ImU32 text_col = GetColorU32(ImGuiCol_Text); - ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin; + const ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin; if (display_frame) { // Framed type @@ -5385,12 +5397,12 @@ void ImGui::TreePushOverrideID(ImGuiID id) void ImGui::TreePop() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; Unindent(); window->DC.TreeDepth--; - ImU32 tree_depth_mask = (1 << window->DC.TreeDepth); + const ImU32 tree_depth_mask = (1 << window->DC.TreeDepth); // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled) if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) @@ -5408,7 +5420,7 @@ void ImGui::TreePop() // Horizontal distance preceding label when using TreeNode() or Bullet() float ImGui::GetTreeNodeToLabelSpacing() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.FontSize + (g.Style.FramePadding.x * 2.0f); } @@ -5443,19 +5455,19 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags if (p_open && !*p_open) return false; - ImGuiID id = window->GetID(label); + const ImGuiID id = window->GetID(label); flags |= ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton : 0); - bool is_open = TreeNodeBehavior(id, flags, label); + const bool is_open = TreeNodeBehavior(id, flags, label); if (p_open) { // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. - ImGuiContext& g = *GImGui; - ImGuiItemHoveredDataBackup last_item_backup; - float button_size = g.FontSize; - float button_x = ImMax(window->DC.LastItemRect.Min.x, window->DC.LastItemRect.Max.x - g.Style.FramePadding.x * 2.0f - button_size); - float button_y = window->DC.LastItemRect.Min.y; + const ImGuiContext & g = *GImGui; + const ImGuiItemHoveredDataBackup last_item_backup; + const float button_size = g.FontSize; + const float button_x = ImMax(window->DC.LastItemRect.Min.x, window->DC.LastItemRect.Max.x - g.Style.FramePadding.x * 2.0f - button_size); + const float button_y = window->DC.LastItemRect.Min.y; if (CloseButton(window->GetID((void*)((intptr_t)id + 1)), ImVec2(button_x, button_y))) *p_open = false; last_item_backup.Restore(); @@ -5484,19 +5496,19 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped. PushColumnsBackground(); - ImGuiID id = window->GetID(label); - ImVec2 label_size = CalcTextSize(label, NULL, true); - ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + const ImGuiID id = window->GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); ImVec2 pos = window->DC.CursorPos; pos.y += window->DC.CurrLineTextBaseOffset; - ImRect bb_inner(pos, pos + size); + const ImRect bb_inner(pos, pos + size); ItemSize(size); // Fill horizontal space. - ImVec2 window_padding = window->WindowPadding; - float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; - float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - pos.x); - ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); + const ImVec2 window_padding = window->WindowPadding; + const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; + const float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - pos.x); + const ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); ImRect bb(pos, pos + size_draw); if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) bb.Max.x += window_padding.x; @@ -5514,7 +5526,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl bool item_add; if (flags & ImGuiSelectableFlags_Disabled) { - ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; + const ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus; item_add = ItemAdd(bb, id); window->DC.ItemFlags = backup_item_flags; @@ -5544,7 +5556,7 @@ bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags fl const bool was_selected = selected; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover))) @@ -5629,10 +5641,10 @@ bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. - ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); - auto frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); - ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); - ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + const ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + const auto frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy. g.NextItemData.ClearFlags(); @@ -5661,7 +5673,7 @@ bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_item if (height_in_items < 0) height_in_items = ImMin(items_count, 7); const ImGuiStyle& style = GetStyle(); - float height_in_items_f = (height_in_items < items_count) ? (height_in_items + 0.25f) : (height_in_items + 0.00f); + const float height_in_items_f = (height_in_items < items_count) ? (height_in_items + 0.25f) : (height_in_items + 0.00f); // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). ImVec2 size; @@ -5699,7 +5711,7 @@ bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(v return false; // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; bool value_changed = false; ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. while (clipper.Step()) @@ -5741,7 +5753,7 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge if (window->SkipItems) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); @@ -5783,8 +5795,8 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1; if (values_count >= values_count_min) { - int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); - int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + const int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + const int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); // Tooltip on hover int v_hovered = -1; @@ -5806,10 +5818,10 @@ void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_ge const float t_step = 1.0f / (float)res_w; const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); - float v0 = values_getter(data, (0 + values_offset) % values_count); + const float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; auto tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle - float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands + const float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); @@ -5859,7 +5871,7 @@ struct ImGuiPlotArrayGetterData static float Plot_ArrayGetter(void* data, int idx) { - auto plot_data = (ImGuiPlotArrayGetterData*)data; + const auto plot_data = (ImGuiPlotArrayGetterData*)data; const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); return v; } @@ -5986,8 +5998,8 @@ bool ImGui::BeginMainMenuBar() SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.NextWindowData.MenuBarOffsetMinVal.y + g.FontBaseSize + g.Style.FramePadding.y)); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); - ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar; - bool is_open = Begin("##MainMenuBar", NULL, window_flags) && BeginMenuBar(); + const ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar; + const bool is_open = Begin("##MainMenuBar", NULL, window_flags) && BeginMenuBar(); PopStyleVar(2); g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); if (!is_open) @@ -6004,7 +6016,7 @@ void ImGui::EndMainMenuBar() // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window // FIXME: With this strategy we won't be able to restore a NULL focus. - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0 && !g.NavAnyRequest) FocusTopMostWindowUnderOne(g.NavWindow, NULL); @@ -6029,7 +6041,7 @@ bool ImGui::BeginMenuBar() // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. - ImRect bar_rect = window->MenuBarRect(); + const ImRect bar_rect = window->MenuBarRect(); ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f)); clip_rect.ClipWith(window->OuterRectClipped); PushClipRect(clip_rect.Min, clip_rect.Max, false); @@ -6053,7 +6065,7 @@ void ImGui::EndMenuBar() // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) { - ImGuiWindow* nav_earliest_child = g.NavWindow; + const ImGuiWindow * nav_earliest_child = g.NavWindow; while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu)) nav_earliest_child = nav_earliest_child->ParentWindow; if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None) @@ -6094,11 +6106,11 @@ bool ImGui::BeginMenu(const char* label, bool enabled) const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImVec2 label_size = CalcTextSize(label, NULL, true); bool pressed; bool menu_is_open = IsPopupOpen(id); - bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].OpenParentId == window->IDStack.back()); + const bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].OpenParentId == window->IDStack.back()); ImGuiWindow* backed_nav_window = g.NavWindow; if (menuset_is_open) g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent) @@ -6115,7 +6127,7 @@ bool ImGui::BeginMenu(const char* label, bool enabled) popup_pos = ImVec2(pos.x - 1.0f - (float)(int)(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight()); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); - float w = label_size.x; + const float w = label_size.x; pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); PopStyleVar(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). @@ -6124,10 +6136,10 @@ bool ImGui::BeginMenu(const char* label, bool enabled) { // Menu inside a menu popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); - float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame - float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + const float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame + const float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); - ImU32 text_col = GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled); + const ImU32 text_col = GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled); RenderArrow(window->DrawList, pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), text_col, ImGuiDir_Right); } @@ -6143,15 +6155,15 @@ bool ImGui::BeginMenu(const char* label, bool enabled) // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. bool moving_toward_other_child_menu = false; - ImGuiWindow* child_menu_window = (g.BeginPopupStack.Size < g.OpenPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window) ? g.OpenPopupStack[g.BeginPopupStack.Size].Window : NULL; + const ImGuiWindow * child_menu_window = (g.BeginPopupStack.Size < g.OpenPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window) ? g.OpenPopupStack[g.BeginPopupStack.Size].Window : NULL; if (g.HoveredWindow == window && child_menu_window != NULL && !(window->Flags & ImGuiWindowFlags_MenuBar)) { // FIXME-DPI: Values should be derived from a master "scale" factor. - ImRect next_window_rect = child_menu_window->Rect(); + const ImRect next_window_rect = child_menu_window->Rect(); ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; ImVec2 tb = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); ImVec2 tc = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); - float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. + const float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. ta.x += (window->Pos.x < child_menu_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); @@ -6232,8 +6244,8 @@ void ImGui::EndMenu() // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu). // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs. // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction. - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical) { ClosePopupToLevel(g.BeginPopupStack.Size, true); @@ -6250,19 +6262,19 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, boo return false; ImGuiContext& g = *GImGui; - ImGuiStyle& style = g.Style; - ImVec2 pos = window->DC.CursorPos; - ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImGuiStyle & style = g.Style; + const ImVec2 pos = window->DC.CursorPos; + const ImVec2 label_size = CalcTextSize(label, NULL, true); // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73), // but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only. - ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | ImGuiSelectableFlags_SetNavIdOnHover | (enabled ? 0 : ImGuiSelectableFlags_Disabled); + const ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | ImGuiSelectableFlags_SetNavIdOnHover | (enabled ? 0 : ImGuiSelectableFlags_Disabled); bool pressed; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful // Note that in this situation we render neither the shortcut neither the selected tick mark - float w = label_size.x; + const float w = label_size.x; window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y)); pressed = Selectable(label, false, flags, ImVec2(w, 0.0f)); @@ -6271,9 +6283,9 @@ bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, boo } else { - ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); - float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame - float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + const ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); + const float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame + const float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f)); if (shortcut_size.x > 0.0f) { @@ -6350,8 +6362,8 @@ ImGuiTabBar::ImGuiTabBar() static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const void* rhs) { - auto a = (const ImGuiTabItem*)lhs; - auto b = (const ImGuiTabItem*)rhs; + const auto a = (const ImGuiTabItem*)lhs; + const auto b = (const ImGuiTabItem*)rhs; return (int)(a->Offset - b->Offset); } @@ -6363,7 +6375,7 @@ static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref) static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; if (g.TabBars.Contains(tab_bar)) return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar)); return ImGuiPtrOrIndex(tab_bar); @@ -6376,9 +6388,9 @@ bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) if (window->SkipItems) return false; - ImGuiID id = window->GetID(str_id); + const ImGuiID id = window->GetID(str_id); ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); - auto tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); + const auto tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); tab_bar->ID = id; return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused); } @@ -6476,7 +6488,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) int tab_dst_n = 0; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { - ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; + const ImGuiTabItem * tab = &tab_bar->Tabs[tab_src_n]; if (tab->LastFrameVisible < tab_bar->PrevFrameVisible) { if (tab->ID == tab_bar->SelectedTabId) @@ -6504,12 +6516,12 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) { if (ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId)) { - //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools - int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir; + // IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools + const int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir; if (tab2_order >= 0 && tab2_order < tab_bar->Tabs.Size) { ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order]; - ImGuiTabItem item_tmp = *tab1; + const ImGuiTabItem item_tmp = *tab1; *tab1 = *tab2; *tab2 = item_tmp; if (tab2->ID == tab_bar->SelectedTabId) @@ -6525,13 +6537,13 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!) const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; if (tab_list_popup_button) - if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! + if (const ImGuiTabItem * tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; // Compute ideal widths g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size); float width_total_contents = 0.0f; - ImGuiTabItem* most_recently_selected_tab = NULL; + const ImGuiTabItem * most_recently_selected_tab = NULL; bool found_selected_tab_id = false; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { @@ -6560,7 +6572,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Compute width const float initial_offset_x = 0.0f; // g.Style.ItemInnerSpacing.x; const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - initial_offset_x, 0.0f); - float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f; + const float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f; if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown)) { // If we don't have enough room, resize down the largest tabs first @@ -6598,7 +6610,7 @@ static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) - if (ImGuiTabItem* tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x! + if (const ImGuiTabItem * tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; // If we have lost the selected tab, select the next most recently active one @@ -6641,7 +6653,7 @@ static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label) { if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) { - ImGuiID id = ImHashStr(label); + const ImGuiID id = ImHashStr(label); KeepAliveID(id); return id; } @@ -6654,7 +6666,7 @@ static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label) static float ImGui::TabBarCalcMaxTabWidth() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; return g.FontSize * 20.0f; } @@ -6670,7 +6682,7 @@ ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id) // The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) { - if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) + if (const ImGuiTabItem * tab = TabBarFindTabByID(tab_bar, tab_id)) tab_bar->Tabs.erase(tab); if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; } if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } @@ -6702,11 +6714,11 @@ static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling) static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { - ImGuiContext& g = *GImGui; - float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) - int order = tab_bar->GetTabOrder(tab); - float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f); - float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); + const ImGuiContext & g = *GImGui; + const float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) + const int order = tab_bar->GetTabOrder(tab); + const float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f); + const float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= tab_bar->BarRect.GetWidth())) { @@ -6740,7 +6752,7 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) //window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255)); const ImRect avail_bar_rect = tab_bar->BarRect; - bool want_clip_rect = !avail_bar_rect.Contains(ImRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(scrolling_buttons_width, 0.0f))); + const bool want_clip_rect = !avail_bar_rect.Contains(ImRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(scrolling_buttons_width, 0.0f))); if (want_clip_rect) PushClipRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max + ImVec2(g.Style.ItemInnerSpacing.x, 0.0f), true); @@ -6770,10 +6782,10 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) PopClipRect(); if (select_dir != 0) - if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) + if (const ImGuiTabItem * tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) { - int selected_order = tab_bar->GetTabOrder(tab_item); - int target_order = selected_order + select_dir; + const int selected_order = tab_bar->GetTabOrder(tab_item); + const int target_order = selected_order + select_dir; tab_to_select = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible } window->DC.CursorPos = backup_cursor_pos; @@ -6784,7 +6796,7 @@ static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // We use g.Style.FramePadding.y to match the square ArrowButton size @@ -6797,7 +6809,7 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) arrow_col.w *= 0.5f; PushStyleColor(ImGuiCol_Text, arrow_col); PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); - bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview); + const bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview); PopStyleColor(2); ImGuiTabItem* tab_to_select = NULL; @@ -6834,8 +6846,8 @@ static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; if (window->SkipItems) return false; @@ -6845,10 +6857,10 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f IM_ASSERT(tab_bar && "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; // FIXME-ERRORHANDLING } - bool ret = TabItemEx(tab_bar, label, p_open, flags); + const bool ret = TabItemEx(tab_bar, label, p_open, flags); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) { - ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; + const ImGuiTabItem * tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) } return ret; @@ -6856,7 +6868,7 @@ bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags f void ImGui::EndTabItem() { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return; @@ -6868,7 +6880,7 @@ void ImGui::EndTabItem() return; } IM_ASSERT(tab_bar->LastTabItemIdx >= 0); - ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; + const ImGuiTabItem * tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) window->IDStack.pop_back(); } @@ -6879,7 +6891,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (tab_bar->WantLayout) TabBarLayout(tab_bar); - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; @@ -6968,15 +6980,15 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Layout size.x = tab->Width; window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2((float)(int)tab->Offset - tab_bar->ScrollingAnim, 0.0f); - ImVec2 pos = window->DC.CursorPos; + const ImVec2 pos = window->DC.CursorPos; ImRect bb(pos, pos + size); // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) - bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x) || (bb.Max.x > tab_bar->BarRect.Max.x); + const bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x) || (bb.Max.x > tab_bar->BarRect.Max.x); if (want_clip_rect) PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x, bb.Max.y), true); - ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; + const ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos; ItemSize(bb.GetSize(), style.FramePadding.y); window->DC.CursorMaxPos = backup_cursor_max_pos; @@ -6993,7 +7005,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, if (g.DragDropActive) button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); + const bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); if (pressed) tab_bar->NextSelectedTabId = id; hovered |= (g.HoveredId == id); @@ -7047,7 +7059,7 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // Render tab label, process close button const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; - bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id); + const bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id); if (just_closed && p_open != NULL) { *p_open = false; @@ -7072,21 +7084,21 @@ bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, // To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem() void ImGui::SetTabItemClosed(const char* label) { - ImGuiContext& g = *GImGui; - bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode); + const ImGuiContext & g = *GImGui; + const bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode); if (is_within_manual_tab_bar) { ImGuiTabBar* tab_bar = g.CurrentTabBar; IM_ASSERT(tab_bar->WantLayout); // Needs to be called AFTER BeginTabBar() and BEFORE the first call to BeginTabItem() - ImGuiID tab_id = TabBarCalcTabID(tab_bar, label); + const ImGuiID tab_id = TabBarCalcTabID(tab_bar, label); TabBarRemoveTab(tab_bar, tab_id); } } ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button) { - ImGuiContext& g = *GImGui; - ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImGuiContext & g = *GImGui; + const ImVec2 label_size = CalcTextSize(label, NULL, true); auto size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f); if (has_close_button) size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle. @@ -7098,7 +7110,7 @@ ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button) void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col) { // While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it. - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const float width = bb.GetWidth(); IM_UNUSED(flags); IM_ASSERT(width > 0.0f); @@ -7124,21 +7136,21 @@ void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabI // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id) { - ImGuiContext& g = *GImGui; - ImVec2 label_size = CalcTextSize(label, NULL, true); + const ImGuiContext & g = *GImGui; + const ImVec2 label_size = CalcTextSize(label, NULL, true); if (bb.GetWidth() <= 1.0f) return false; // Render text label (with clipping + alpha gradient) + unsaved marker - auto TAB_UNSAVED_MARKER = "*"; + const auto TAB_UNSAVED_MARKER = "*"; ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); if (flags & ImGuiTabItemFlags_UnsavedDocument) { text_pixel_clip_bb.Max.x -= CalcTextSize(TAB_UNSAVED_MARKER, NULL, false).x; - ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + frame_padding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + frame_padding.y + (float)(int)(-g.FontSize * 0.25f)); + const ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + frame_padding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + frame_padding.y + (float)(int)(-g.FontSize * 0.25f)); RenderTextClippedEx(draw_list, unsaved_marker_pos, bb.Max - frame_padding, TAB_UNSAVED_MARKER, NULL, NULL); } - ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; + const ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; // Close Button // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() @@ -7152,7 +7164,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, close_button_visible = true; if (close_button_visible) { - ImGuiItemHoveredDataBackup last_item_backup; + const ImGuiItemHoveredDataBackup last_item_backup; const float close_button_sz = g.FontSize; PushStyleVar(ImGuiStyleVar_FramePadding, frame_padding); if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x * 2.0f - close_button_sz, bb.Min.y))) @@ -7167,7 +7179,7 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, text_pixel_clip_bb.Max.x -= close_button_sz; } - float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f; + const float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f; RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size); return close_button_pressed; @@ -7197,13 +7209,13 @@ bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, int ImGui::GetColumnIndex() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; } int ImGui::GetColumnsCount() { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; } @@ -7223,8 +7235,8 @@ static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); @@ -7238,7 +7250,7 @@ static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) float ImGui::GetColumnOffset(int column_index) { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; if (columns == NULL) return 0.0f; @@ -7267,8 +7279,8 @@ static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool befo float ImGui::GetColumnWidth(int column_index) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; ImGuiColumns* columns = window->DC.CurrentColumns; if (columns == NULL) return GetContentRegionAvail().x; @@ -7280,8 +7292,8 @@ float ImGui::GetColumnWidth(int column_index) void ImGui::SetColumnOffset(int column_index, float offset) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; + const ImGuiContext & g = *GImGui; + const ImGuiWindow * window = g.CurrentWindow; ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); @@ -7302,8 +7314,8 @@ void ImGui::SetColumnOffset(int column_index, float offset) void ImGui::SetColumnWidth(int column_index, float width) { - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + const ImGuiWindow * window = GetCurrentWindowRead(); + const ImGuiColumns * columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) @@ -7313,24 +7325,24 @@ void ImGui::SetColumnWidth(int column_index, float width) void ImGui::PushColumnClipRect(int column_index) { - ImGuiWindow* window = GetCurrentWindowRead(); + const ImGuiWindow * window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; if (column_index < 0) column_index = columns->Current; - ImGuiColumnData* column = &columns->Columns[column_index]; + const ImGuiColumnData * column = &columns->Columns[column_index]; PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); } // Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) void ImGui::PushColumnsBackground() { - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + const ImGuiWindow * window = GetCurrentWindowRead(); + const ImGuiColumns * columns = window->DC.CurrentColumns; if (columns->Count == 1) return; window->DrawList->ChannelsSetCurrent(0); - int cmd_size = window->DrawList->CmdBuffer.Size; + const int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); IM_UNUSED(cmd_size); IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd @@ -7338,8 +7350,8 @@ void ImGui::PushColumnsBackground() void ImGui::PopColumnsBackground() { - ImGuiWindow* window = GetCurrentWindowRead(); - ImGuiColumns* columns = window->DC.CurrentColumns; + const ImGuiWindow * window = GetCurrentWindowRead(); + const ImGuiColumns * columns = window->DC.CurrentColumns; if (columns->Count == 1) return; window->DrawList->ChannelsSetCurrent(columns->Current + 1); @@ -7366,7 +7378,7 @@ ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. PushID(0x11223347 + (str_id ? 0 : columns_count)); - ImGuiID id = window->GetID(str_id ? str_id : "columns"); + const ImGuiID id = window->GetID(str_id ? str_id : "columns"); PopID(); return id; @@ -7374,14 +7386,14 @@ ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) { - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported // Acquire storage for the columns set - ImGuiID id = GetColumnsID(str_id, columns_count); + const ImGuiID id = GetColumnsID(str_id, columns_count); ImGuiColumns* columns = FindOrCreateColumns(window, id); IM_ASSERT(columns->ID == id); columns->Current = 0; @@ -7425,8 +7437,8 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag { // Compute clipping rectangle ImGuiColumnData* column = &columns->Columns[n]; - float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n)); - float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); + const float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n)); + const float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); column->ClipRect.ClipWith(window->ClipRect); } @@ -7439,9 +7451,9 @@ void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlag } // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user. - float offset_0 = GetColumnOffset(columns->Current); - float offset_1 = GetColumnOffset(columns->Current + 1); - float width = offset_1 - offset_0; + const float offset_0 = GetColumnOffset(columns->Current); + const float offset_1 = GetColumnOffset(columns->Current + 1); + const float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f); window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); @@ -7454,7 +7466,7 @@ void ImGui::NextColumn() if (window->SkipItems || window->DC.CurrentColumns == NULL) return; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) @@ -7492,9 +7504,9 @@ void ImGui::NextColumn() PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. - float offset_0 = GetColumnOffset(columns->Current); - float offset_1 = GetColumnOffset(columns->Current + 1); - float width = offset_1 - offset_0; + const float offset_0 = GetColumnOffset(columns->Current); + const float offset_1 = GetColumnOffset(columns->Current + 1); + const float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding; } @@ -7530,8 +7542,8 @@ void ImGui::EndColumns() int dragging_column = -1; for (int n = 1; n < columns->Count; n++) { - ImGuiColumnData* column = &columns->Columns[n]; - float x = window->Pos.x + GetColumnOffset(n); + const ImGuiColumnData * column = &columns->Columns[n]; + const float x = window->Pos.x + GetColumnOffset(n); const ImGuiID column_id = columns->ID + ImGuiID(n); const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); @@ -7562,7 +7574,7 @@ void ImGui::EndColumns() for (int n = 0; n < columns->Count + 1; n++) columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; columns->IsBeingResized = is_being_resized = true; - float x = GetDraggedColumnOffset(columns, dragging_column); + const float x = GetDraggedColumnOffset(columns, dragging_column); SetColumnOffset(dragging_column, x); } } @@ -7577,12 +7589,12 @@ void ImGui::EndColumns() // [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] void ImGui::Columns(int columns_count, const char* id, bool border) { - ImGuiWindow* window = GetCurrentWindow(); + const ImGuiWindow * window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); - ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); - //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior - ImGuiColumns* columns = window->DC.CurrentColumns; + const ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); + // flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior + const ImGuiColumns * columns = window->DC.CurrentColumns; if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) return; @@ -7602,11 +7614,11 @@ bool ImGui::BufferingBar( const char* label, float value, const ImVec2& size_arg if( window->SkipItems ) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID( label ); - ImVec2 pos = window->DC.CursorPos; + const ImVec2 pos = window->DC.CursorPos; ImVec2 size = size_arg; size.x -= style.FramePadding.x * 2; @@ -7647,12 +7659,12 @@ bool ImGui::Spinner( const char* label, float radius, int thickness, const ImU32 if( window->SkipItems ) return false; - ImGuiContext& g = *GImGui; + const ImGuiContext & g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID( label ); - ImVec2 pos = window->DC.CursorPos; - ImVec2 size( ( radius ) * 2, ( radius + style.FramePadding.y ) * 2 ); + const ImVec2 pos = window->DC.CursorPos; + const ImVec2 size( ( radius ) * 2, ( radius + style.FramePadding.y ) * 2 ); const ImRect bb( pos, ImVec2( pos.x + size.x, pos.y + size.y ) ); ItemSize( bb, style.FramePadding.y ); @@ -7662,10 +7674,10 @@ bool ImGui::Spinner( const char* label, float radius, int thickness, const ImU32 // Render window->DrawList->PathClear(); - auto progress { g.FrameCount * 0.1f }; + const auto progress { g.FrameCount * 0.1f }; - int num_segments = 30; - int start = abs( ImSin( progress * 1.8f )*( num_segments - 5 ) ); + const int num_segments = 30; + const int start = abs( ImSin( progress * 1.8f )*( num_segments - 5 ) ); const float a_min = IM_PI * 2.0f * ( (float)start ) / (float)num_segments; const float a_max = IM_PI * 2.0f * ( (float)num_segments - 3 ) / (float)num_segments; diff --git a/imgui/imstb_rectpack.h b/imgui/imstb_rectpack.h index ac9d5251..ac73806b 100644 --- a/imgui/imstb_rectpack.h +++ b/imgui/imstb_rectpack.h @@ -294,8 +294,8 @@ STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, // find minimum y position if it starts at x1 static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) { - stbrp_node *node = first; - int x1 = x0 + width; + const stbrp_node *node = first; + const int x1 = x0 + width; int min_y, visited_width, waste_area; STBRP__NOTUSED(c); @@ -419,7 +419,7 @@ static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int widt while (tail->x < width) tail = tail->next; while (tail) { - int xpos = tail->x - width; + const int xpos = tail->x - width; int y,waste; STBRP_ASSERT(xpos >= 0); // find the left position that matches this @@ -532,8 +532,8 @@ static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, i // [DEAR IMGUI] Added STBRP__CDECL static int STBRP__CDECL rect_height_compare(const void *a, const void *b) { - auto p = (const stbrp_rect *) a; - auto q = (const stbrp_rect *) b; + const auto p = (const stbrp_rect *) a; + const auto q = (const stbrp_rect *) b; if (p->h > q->h) return -1; if (p->h < q->h) @@ -544,8 +544,8 @@ static int STBRP__CDECL rect_height_compare(const void *a, const void *b) // [DEAR IMGUI] Added STBRP__CDECL static int STBRP__CDECL rect_original_order(const void *a, const void *b) { - auto p = (const stbrp_rect *) a; - auto q = (const stbrp_rect *) b; + const auto p = (const stbrp_rect *) a; + const auto q = (const stbrp_rect *) b; return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed); } @@ -571,7 +571,7 @@ STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int nu if (rects[i].w == 0 || rects[i].h == 0) { rects[i].x = rects[i].y = 0; // empty rect needs no space } else { - stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + const stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); if (fr.prev_link) { rects[i].x = (stbrp_coord) fr.x; rects[i].y = (stbrp_coord) fr.y; diff --git a/imgui/imstb_truetype.h b/imgui/imstb_truetype.h index ca5d4df9..0ce05714 100644 --- a/imgui/imstb_truetype.h +++ b/imgui/imstb_truetype.h @@ -1186,7 +1186,7 @@ static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) { - int b0 = stbtt__buf_get8(b); + const int b0 = stbtt__buf_get8(b); if (b0 >= 32 && b0 <= 246) return b0 - 139; else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; @@ -1288,11 +1288,11 @@ static int stbtt__isfont(stbtt_uint8 *font) // @OPTIMIZE: binary search static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) { - stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); - stbtt_uint32 tabledir = fontstart + 12; + const stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + const stbtt_uint32 tabledir = fontstart + 12; stbtt_int32 i; for (i=0; i < num_tables; ++i) { - stbtt_uint32 loc = tabledir + 16*i; + const stbtt_uint32 loc = tabledir + 16*i; if (stbtt_tag(data+loc+0, tag)) return ttULONG(data+loc+8); } @@ -1309,7 +1309,7 @@ static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, if (stbtt_tag(font_collection, "ttcf")) { // version 1? if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { - stbtt_int32 n = ttLONG(font_collection+8); + const stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; return ttULONG(font_collection+12+index*4); @@ -1432,7 +1432,7 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in numTables = ttUSHORT(data + cmap + 2); info->index_map = 0; for (i=0; i < numTables; ++i) { - stbtt_uint32 encoding_record = cmap + 4 + 8 * i; + const stbtt_uint32 encoding_record = cmap + 4 + 8 * i; // find an encoding we understand: switch(ttUSHORT(data+encoding_record)) { case STBTT_PLATFORM_ID_MICROSOFT: @@ -1461,17 +1461,17 @@ static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, in STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) { stbtt_uint8 *data = info->data; - stbtt_uint32 index_map = info->index_map; + const stbtt_uint32 index_map = info->index_map; - stbtt_uint16 format = ttUSHORT(data + index_map + 0); + const stbtt_uint16 format = ttUSHORT(data + index_map + 0); if (format == 0) { // apple byte encoding - stbtt_int32 bytes = ttUSHORT(data + index_map + 2); + const stbtt_int32 bytes = ttUSHORT(data + index_map + 2); if (unicode_codepoint < bytes-6) return ttBYTE(data + index_map + 6 + unicode_codepoint); return 0; } else if (format == 6) { - stbtt_uint32 first = ttUSHORT(data + index_map + 6); - stbtt_uint32 count = ttUSHORT(data + index_map + 8); + const stbtt_uint32 first = ttUSHORT(data + index_map + 6); + const stbtt_uint32 count = ttUSHORT(data + index_map + 8); if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); return 0; @@ -1479,13 +1479,13 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean return 0; } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges - stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; + const stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); - stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; + const stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; // do a binary search of the segments - stbtt_uint32 endCount = index_map + 14; + const stbtt_uint32 endCount = index_map + 14; stbtt_uint32 search = endCount; if (unicode_codepoint > 0xffff) @@ -1510,7 +1510,7 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep { stbtt_uint16 offset, start; - stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + const stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); @@ -1524,20 +1524,20 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); } } else if (format == 12 || format == 13) { - stbtt_uint32 ngroups = ttULONG(data+index_map+12); + const stbtt_uint32 ngroups = ttULONG(data+index_map+12); stbtt_int32 low,high; low = 0; high = (stbtt_int32)ngroups; // Binary search the right group. while (low < high) { - stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high - stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); - stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); + const stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high + const stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); + const stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); if ((stbtt_uint32) unicode_codepoint < start_char) high = mid; else if ((stbtt_uint32) unicode_codepoint > end_char) low = mid+1; else { - stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); + const stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); if (format == 12) return start_glyph + unicode_codepoint-start_char; else // format == 13 @@ -1592,7 +1592,7 @@ STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int if (info->cff.size) { stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); } else { - int g = stbtt__GetGlyfOffset(info, glyph_index); + const int g = stbtt__GetGlyfOffset(info, glyph_index); if (g < 0) return 0; if (x0) *x0 = ttSHORT(info->data + g + 2); @@ -1924,10 +1924,10 @@ static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) { - float cx1 = ctx->x + dx1; - float cy1 = ctx->y + dy1; - float cx2 = cx1 + dx2; - float cy2 = cy1 + dy2; + const float cx1 = ctx->x + dx1; + const float cy1 = ctx->y + dy1; + const float cx2 = cx1 + dx2; + const float cy2 = cy1 + dy2; ctx->x = cx2 + dx3; ctx->y = cy2 + dy3; stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); @@ -1935,7 +1935,7 @@ static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, flo static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) { - int count = stbtt__cff_index_count(&idx); + const int count = stbtt__cff_index_count(&idx); int bias = 107; if (count >= 33900) bias = 32768; @@ -2254,7 +2254,7 @@ static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, s static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) { stbtt__csctx c = STBTT__CSCTX_INIT(1); - int r = stbtt__run_charstring(info, glyph_index, &c); + const int r = stbtt__run_charstring(info, glyph_index, &c); if (x0) *x0 = r ? c.min_x : 0; if (y0) *y0 = r ? c.min_y : 0; if (x1) *x1 = r ? c.max_x : 0; @@ -2272,7 +2272,7 @@ STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, s STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) { - stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + const stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); if (glyph_index < numOfLongHorMetrics) { if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); @@ -2314,10 +2314,10 @@ static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) { - stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); + const stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); switch(coverageFormat) { case 1: { - stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); + const stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); // Binary search. stbtt_int32 l=0, r=glyphCount-1, m; @@ -2339,7 +2339,7 @@ static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyp } break; case 2: { - stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); + const stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); stbtt_uint8 *rangeArray = coverageTable + 4; // Binary search. @@ -2356,7 +2356,7 @@ static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyp else if (needle > strawEnd) l = m + 1; else { - stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); + const stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); return startCoverageIndex + glyph - strawStart; } } @@ -2373,12 +2373,12 @@ static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyp static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) { - stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); + const stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); switch(classDefFormat) { case 1: { - stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); - stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); + const stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); + const stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); stbtt_uint8 *classDef1ValueArray = classDefTable + 6; if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) @@ -2389,7 +2389,7 @@ static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) } break; case 2: { - stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); + const stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); stbtt_uint8 *classRangeRecords = classDefTable + 4; // Binary search. @@ -2445,34 +2445,34 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, i lookupCount = ttUSHORT(lookupList); for (i=0; i straw) l = m + 1; else { - stbtt_int16 xAdvance = ttSHORT(pairValue + 2); + const stbtt_int16 xAdvance = ttSHORT(pairValue + 2); return xAdvance; } } } break; case 2: { - stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); - stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); + const stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); + const stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); - stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); - stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); - int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); - int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); + const stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); + const stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); + const int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); + const int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); - stbtt_uint16 class1Count = ttUSHORT(table + 12); - stbtt_uint16 class2Count = ttUSHORT(table + 14); + const stbtt_uint16 class1Count = ttUSHORT(table + 12); + const stbtt_uint16 class2Count = ttUSHORT(table + 14); STBTT_assert(glyph1class < class1Count); STBTT_assert(glyph2class < class2Count); @@ -2529,7 +2529,7 @@ static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, i if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) { stbtt_uint8 *class1Records = table + 16; stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count); - stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class); + const stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class); return xAdvance; } } break; @@ -2587,7 +2587,7 @@ STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, in STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) { - int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); + const int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); if (!tab) return 0; if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); @@ -2606,13 +2606,13 @@ STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) { - int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + const int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); return (float) height / fheight; } STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) { - int unitsPerEm = ttUSHORT(info->data + info->head + 18); + const int unitsPerEm = ttUSHORT(info->data + info->head + 18); return pixels / unitsPerEm; } @@ -2683,8 +2683,8 @@ static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) return p; } else { if (hh->num_remaining_in_head_chunk == 0) { - int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); - auto c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + const int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + const auto c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); if (c == NULL) return NULL; c->next = hh->head; @@ -2972,7 +2972,7 @@ static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edg static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) { - float y_bottom = y_top+1; + const float y_bottom = y_top+1; while (e) { // brute force every pixel @@ -2981,7 +2981,7 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, STBTT_assert(e->ey >= y_top); if (e->fdx == 0) { - float x0 = e->fx; + const float x0 = e->fx; if (x0 < len) { if (x0 >= 0) { stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); @@ -3023,7 +3023,7 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, if ((int) x_top == (int) x_bottom) { float height; // simple case, only spans one pixel - int x = (int) x_top; + const int x = (int) x_top; height = sy1 - sy0; STBTT_assert(x >= 0 && x < len); scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; @@ -3091,17 +3091,17 @@ static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, // that, we need to explicitly produce segments based on x positions. // rename variables to clearly-defined pairs - float y0 = y_top; - float x1 = (float) (x); - float x2 = (float) (x+1); - float x3 = xb; - float y3 = y_bottom; + const float y0 = y_top; + const float x1 = (float) (x); + const float x2 = (float) (x+1); + const float x3 = xb; + const float y3 = y_bottom; // x = e->x + e->dx * (y-y_top) // (y-y_top) = (x - e->x) / e->dx // y = (x - e->x) / e->dx + y_top - float y1 = (x - x0) / dx + y_top; - float y2 = (x+1 - x0) / dx + y_top; + const float y1 = (x - x0) / dx + y_top; + const float y2 = (x+1 - x0) / dx + y_top; if (x0 < x1 && x3 > x2) { // three segments descending down-right stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); @@ -3155,8 +3155,8 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, while (j < result->h) { // find center of pixel for this scanline - float scan_y_top = y + 0.0f; - float scan_y_bottom = y + 1.0f; + const float scan_y_top = y + 0.0f; + const float scan_y_bottom = y + 1.0f; stbtt__active_edge **step = &active; STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); @@ -3243,8 +3243,8 @@ static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) stbtt__edge t = p[i], *a = &t; j = i; while (j > 0) { - stbtt__edge *b = &p[j-1]; - int c = STBTT__COMPARE(a,b); + const stbtt__edge *b = &p[j-1]; + const int c = STBTT__COMPARE(a,b); if (!c) break; p[j] = p[j-1]; --j; @@ -3329,13 +3329,13 @@ typedef struct static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) { - float y_scale_inv = invert ? -scale_y : scale_y; + const float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; #if STBTT_RASTERIZER_VERSION == 1 int vsubsample = result->h < 8 ? 15 : 5; #elif STBTT_RASTERIZER_VERSION == 2 - int vsubsample = 1; + const int vsubsample = 1; #else #error "Unrecognized value of STBTT_RASTERIZER_VERSION" #endif @@ -3352,7 +3352,7 @@ static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcou m=0; for (i=0; i < windings; ++i) { - stbtt__point *p = pts + m; + const stbtt__point *p = pts + m; m += wcount[i]; j = wcount[i]-1; for (k=0; k < wcount[i]; j=k++) { @@ -3395,11 +3395,11 @@ static void stbtt__add_point(stbtt__point *points, int n, float x, float y) static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) { // midpoint - float mx = (x0 + 2*x1 + x2)/4; - float my = (y0 + 2*y1 + y2)/4; + const float mx = (x0 + 2*x1 + x2)/4; + const float my = (y0 + 2*y1 + y2)/4; // versus directly drawn line - float dx = (x0+x2)/2 - mx; - float dy = (y0+y2)/2 - my; + const float dx = (x0+x2)/2 - mx; + const float dy = (y0+y2)/2 - my; if (n > 16) // 65536 segments on one curve better be enough! return 1; if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA @@ -3415,36 +3415,36 @@ static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) { // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough - float dx0 = x1-x0; - float dy0 = y1-y0; - float dx1 = x2-x1; - float dy1 = y2-y1; - float dx2 = x3-x2; - float dy2 = y3-y2; - float dx = x3-x0; - float dy = y3-y0; - float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); - float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); - float flatness_squared = longlen*longlen-shortlen*shortlen; + const float dx0 = x1-x0; + const float dy0 = y1-y0; + const float dx1 = x2-x1; + const float dy1 = y2-y1; + const float dx2 = x3-x2; + const float dy2 = y3-y2; + const float dx = x3-x0; + const float dy = y3-y0; + const float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + const float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + const float flatness_squared = longlen*longlen-shortlen*shortlen; if (n > 16) // 65536 segments on one curve better be enough! return; if (flatness_squared > objspace_flatness_squared) { - float x01 = (x0+x1)/2; - float y01 = (y0+y1)/2; - float x12 = (x1+x2)/2; - float y12 = (y1+y2)/2; - float x23 = (x2+x3)/2; - float y23 = (y2+y3)/2; + const float x01 = (x0+x1)/2; + const float y01 = (y0+y1)/2; + const float x12 = (x1+x2)/2; + const float y12 = (y1+y2)/2; + const float x23 = (x2+x3)/2; + const float y23 = (y2+y3)/2; - float xa = (x01+x12)/2; - float ya = (y01+y12)/2; - float xb = (x12+x23)/2; - float yb = (y12+y23)/2; + const float xa = (x01+x12)/2; + const float ya = (y01+y12)/2; + const float xb = (x12+x23)/2; + const float yb = (y12+y23)/2; - float mx = (xa+xb)/2; - float my = (ya+yb)/2; + const float mx = (xa+xb)/2; + const float my = (ya+yb)/2; stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); @@ -3460,7 +3460,7 @@ static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, stbtt__point *points=0; int num_points=0; - float objspace_flatness_squared = objspace_flatness * objspace_flatness; + const float objspace_flatness_squared = objspace_flatness * objspace_flatness; int i,n=0,start=0, pass; // count how many "moves" there are to get the contour count @@ -3534,7 +3534,7 @@ error: STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) { - float scale = scale_x > scale_y ? scale_y : scale_x; + const float scale = scale_x > scale_y ? scale_y : scale_x; int winding_count = 0; int *winding_lengths = NULL; stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); @@ -3554,8 +3554,8 @@ STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info { int ix0,iy0,ix1,iy1; stbtt__bitmap gbm; - stbtt_vertex *vertices; - int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt_vertex *vertices; + const int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { @@ -3599,7 +3599,7 @@ STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigne { int ix0,iy0; stbtt_vertex *vertices; - int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + const int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); stbtt__bitmap gbm; stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); @@ -3670,7 +3670,7 @@ static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // fo for (i=0; i < num_chars; ++i) { int advance, lsb, x0,y0,x1,y1,gw,gh; - int g = stbtt_FindGlyphIndex(&f, first_char + i); + const int g = stbtt_FindGlyphIndex(&f, first_char + i); stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); gw = x1-x0; @@ -3698,11 +3698,11 @@ static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // fo STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) { - float d3d_bias = opengl_fillrule ? 0 : -0.5f; + const float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; const stbtt_bakedchar *b = chardata + char_index; - int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); - int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + const int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + const int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = round_x + d3d_bias; q->y0 = round_y + d3d_bias; @@ -3852,7 +3852,7 @@ STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int s static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; - int safe_w = w - kernel_width; + const int safe_w = w - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < h; ++j) { @@ -3914,7 +3914,7 @@ static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_i static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) { unsigned char buffer[STBTT_MAX_OVERSAMPLE]; - int safe_h = h - kernel_width; + const int safe_h = h - kernel_width; int j; STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < w; ++j) { @@ -3992,14 +3992,14 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stb k=0; for (i=0; i < num_ranges; ++i) { - float fh = ranges[i].font_size; - float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + const float fh = ranges[i].font_size; + const float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); ranges[i].h_oversample = (unsigned char) spc->h_oversample; ranges[i].v_oversample = (unsigned char) spc->v_oversample; for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; - int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; - int glyph = stbtt_FindGlyphIndex(info, codepoint); + const int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + const int glyph = stbtt_FindGlyphIndex(info, codepoint); if (glyph == 0 && spc->skip_missing) { rects[k].w = rects[k].h = 0; } else { @@ -4047,13 +4047,13 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const int i,j,k, return_value = 1; // save current values - int old_h_over = spc->h_oversample; - int old_v_over = spc->v_oversample; + const int old_h_over = spc->h_oversample; + const int old_v_over = spc->v_oversample; k = 0; for (i=0; i < num_ranges; ++i) { - float fh = ranges[i].font_size; - float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + const float fh = ranges[i].font_size; + const float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); float recip_h,recip_v,sub_x,sub_y; spc->h_oversample = ranges[i].h_oversample; spc->v_oversample = ranges[i].v_oversample; @@ -4066,9 +4066,9 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const if (r->was_packed && r->w != 0 && r->h != 0) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; - int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; - int glyph = stbtt_FindGlyphIndex(info, codepoint); - stbrp_coord pad = (stbrp_coord) spc->padding; + const int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + const int glyph = stbtt_FindGlyphIndex(info, codepoint); + const stbrp_coord pad = (stbrp_coord) spc->padding; // pad on left and top r->x += pad; @@ -4196,8 +4196,8 @@ STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int const stbtt_packedchar *b = chardata + char_index; if (align_to_integer) { - float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); - float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + const float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + const float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = x; q->y0 = y; q->x1 = x + b->xoff2 - b->xoff; @@ -4227,23 +4227,23 @@ STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) { - float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; - float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; - float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; - float roperp = orig[1]*ray[0] - orig[0]*ray[1]; + const float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; + const float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; + const float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; + const float roperp = orig[1]*ray[0] - orig[0]*ray[1]; - float a = q0perp - 2*q1perp + q2perp; - float b = q1perp - q0perp; - float c = q0perp - roperp; + const float a = q0perp - 2*q1perp + q2perp; + const float b = q1perp - q0perp; + const float c = q0perp - roperp; float s0 = 0., s1 = 0.; int num_s = 0; if (a != 0.0) { - float discr = b*b - a*c; + const float discr = b*b - a*c; if (discr > 0.0) { - float rcpna = -1 / a; - float d = (float) STBTT_sqrt(discr); + const float rcpna = -1 / a; + const float d = (float) STBTT_sqrt(discr); s0 = (b+d) * rcpna; s1 = (b-d) * rcpna; if (s0 >= 0.0 && s0 <= 1.0) @@ -4264,17 +4264,17 @@ static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], if (num_s == 0) return 0; else { - float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); + const float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; - float q0d = q0[0]*rayn_x + q0[1]*rayn_y; - float q1d = q1[0]*rayn_x + q1[1]*rayn_y; - float q2d = q2[0]*rayn_x + q2[1]*rayn_y; - float rod = orig[0]*rayn_x + orig[1]*rayn_y; + const float q0d = q0[0]*rayn_x + q0[1]*rayn_y; + const float q1d = q1[0]*rayn_x + q1[1]*rayn_y; + const float q2d = q2[0]*rayn_x + q2[1]*rayn_y; + const float rod = orig[0]*rayn_x + orig[1]*rayn_y; - float q10d = q1d - q0d; - float q20d = q2d - q0d; - float q0rd = q0d - rod; + const float q10d = q1d - q0d; + const float q20d = q2d - q0d; + const float q0rd = q0d - rod; hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; hits[0][1] = a*s0+b; @@ -4318,7 +4318,7 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { - float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + const float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } @@ -4328,7 +4328,7 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); - int by = STBTT_max(y0,STBTT_max(y1,y2)); + const int by = STBTT_max(y0,STBTT_max(y1,y2)); if (y > ay && y < by && x > ax) { float q0[2],q1[2],q2[2]; float hits[2][2]; @@ -4344,12 +4344,12 @@ static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex x1 = (int)verts[i ].x; y1 = (int)verts[i ].y; if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { - float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + const float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; if (x_inter < x) winding += (y0 < y1) ? 1 : -1; } } else { - int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); + const int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); if (num_hits >= 1) if (hits[0][0] < 0) winding += (hits[0][1] < 0 ? -1 : 1); @@ -4374,13 +4374,13 @@ static float stbtt__cuberoot( float x ) // x^3 + c*x^2 + b*x + a = 0 static int stbtt__solve_cubic(float a, float b, float c, float* r) { - float s = -a / 3; - float p = b - a*a / 3; - float q = a * (2*a*a - 9*b) / 27 + c; - float p3 = p*p*p; - float d = q*q + 4*p3 / 27; + const float s = -a / 3; + const float p = b - a*a / 3; + const float q = a * (2*a*a - 9*b) / 27 + c; + const float p3 = p*p*p; + const float d = q*q + 4*p3 / 27; if (d >= 0) { - float z = (float) STBTT_sqrt(d); + const float z = (float) STBTT_sqrt(d); float u = (-q + z) / 2; float v = (-q - z) / 2; u = stbtt__cuberoot(u); @@ -4388,10 +4388,10 @@ static int stbtt__solve_cubic(float a, float b, float c, float* r) r[0] = s + u + v; return 1; } else { - float u = (float) STBTT_sqrt(-p/3); - float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative - float m = (float) STBTT_cos(v); - float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; + const float u = (float) STBTT_sqrt(-p/3); + const float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative + const float m = (float) STBTT_cos(v); + const float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; r[0] = s + u * 2 * m; r[1] = s - u * (m + n); r[2] = s - u * (m - n); @@ -4611,7 +4611,7 @@ static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, s // convert utf16 to utf8 and compare the results while converting while (len2) { - stbtt_uint16 ch = s2[0]*256 + s2[1]; + const stbtt_uint16 ch = s2[0]*256 + s2[1]; if (ch < 0x80) { if (i >= len1) return -1; if (s1[i++] != ch) return -1; @@ -4621,7 +4621,7 @@ static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, s if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; } else if (ch >= 0xd800 && ch < 0xdc00) { stbtt_uint32 c; - stbtt_uint16 ch2 = s2[2]*256 + s2[3]; + const stbtt_uint16 ch2 = s2[2]*256 + s2[3]; if (i+3 >= len1) return -1; c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; if (s1[i++] != 0xf0 + (c >> 18)) return -1; @@ -4655,14 +4655,14 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l { stbtt_int32 i,count,stringOffset; stbtt_uint8 *fc = font->data; - stbtt_uint32 offset = font->fontstart; - stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + const stbtt_uint32 offset = font->fontstart; + const stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); if (!nm) return NULL; count = ttUSHORT(fc+nm+2); stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { - stbtt_uint32 loc = nm + 6 + 12 * i; + const stbtt_uint32 loc = nm + 6 + 12 * i; if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { *length = ttUSHORT(fc+loc+8); @@ -4675,12 +4675,12 @@ STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *l static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) { stbtt_int32 i; - stbtt_int32 count = ttUSHORT(fc+nm+2); - stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + const stbtt_int32 count = ttUSHORT(fc+nm+2); + const stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); for (i=0; i < count; ++i) { - stbtt_uint32 loc = nm + 6 + 12 * i; - stbtt_int32 id = ttUSHORT(fc+loc+6); + const stbtt_uint32 loc = nm + 6 + 12 * i; + const stbtt_int32 id = ttUSHORT(fc+loc+6); if (id == target_id) { // find the encoding stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); @@ -4721,7 +4721,7 @@ static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) { - stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + const stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); stbtt_uint32 nm,hd; if (!stbtt__isfont(fc+offset)) return 0; @@ -4752,7 +4752,7 @@ static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char { stbtt_int32 i; for (i=0;;++i) { - stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); + const stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); if (off < 0) return off; if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) return off; diff --git a/input/command.cpp b/input/command.cpp index d2925fee..280bab6a 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -795,11 +795,11 @@ std::unordered_map commandMap = { void command_queue::update() { - double delta = Timer::GetDeltaTime(); + const double delta = Timer::GetDeltaTime(); for (auto c : m_active_continuous) { command_data data({c.first, GLFW_REPEAT, 0.0, 0.0, delta, false, glm::vec3()}); // todo: improve - auto lookup = m_commands.emplace( c.second, commanddata_sequence() ); + const auto lookup = m_commands.emplace( c.second, commanddata_sequence() ); // recipient stack was either located or created, so we can add to it quite safely lookup.first->second.emplace_back( data ); } @@ -809,7 +809,7 @@ void command_queue::update() void command_queue::push( command_data const &Command, uint32_t const Recipient ) { if (is_network_target(Recipient)) { - auto lookup = m_intercept_queue.emplace(Recipient, commanddata_sequence()); + const auto lookup = m_intercept_queue.emplace(Recipient, commanddata_sequence()); lookup.first->second.emplace_back(Command); } else { push_direct(Command, Recipient); @@ -828,7 +828,7 @@ void command_queue::push_direct(const command_data &Command, const uint32_t Reci return; } - auto lookup = m_commands.emplace( Recipient, commanddata_sequence() ); + const auto lookup = m_commands.emplace( Recipient, commanddata_sequence() ); // recipient stack was either located or created, so we can add to it quite safely lookup.first->second.emplace_back( Command ); } @@ -837,7 +837,7 @@ void command_queue::push_direct(const command_data &Command, const uint32_t Reci bool command_queue::pop( command_data &Command, uint32_t const Recipient ) { - auto lookup = m_commands.find( Recipient ); + const auto lookup = m_commands.find( Recipient ); if( lookup == m_commands.end() ) { // no command stack for this recipient, so no commands return false; diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 2d5f3d24..cc1ca799 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -139,7 +139,7 @@ mouse_slider::on_move( double const Mousex, double const Mousey ) { auto const controledge { Global.window_size.y * 0.5 + controlsize * 0.5 }; auto const stepsize { controlsize / m_valuerange }; - auto mousey = std::clamp( Mousey, controledge - controlsize, controledge ); + const auto mousey = std::clamp( Mousey, controledge - controlsize, controledge ); m_value = m_analogue ? (controledge - mousey) / controlsize : std::floor((controledge - mousey) / stepsize); if( m_invertrange ) { m_value = ( m_analogue ? 1.0 : m_valuerange ) - m_value; } @@ -285,7 +285,7 @@ drivermouse_input::scroll( double const Xoffset, double const Yoffset ) { else { // scroll adjusts master controller // TODO: allow configurable scroll commands - auto command { + const auto command { adjust_command( Yoffset > 0.0 ? m_wheelbindings.up : diff --git a/input/keyboardinput.cpp b/input/keyboardinput.cpp index afd4f357..209ca76c 100644 --- a/input/keyboardinput.cpp +++ b/input/keyboardinput.cpp @@ -238,7 +238,7 @@ void keyboard_input::dump_bindings() for (const std::pair> &binding : m_bindingsetups) { stream << simulation::Commands_descriptions[static_cast(binding.first)].name << ' '; - int keycode = std::get(binding.second); + const int keycode = std::get(binding.second); auto it = keytonamemap.find(keycode & 0xFFFF); if (it != keytonamemap.end()) { if (keycode & keymodifier::control) diff --git a/input/messaging.cpp b/input/messaging.cpp index 36ed853c..37258451 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -68,7 +68,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) || typeid(*event) == typeid(lights_event) || event->m_sibling != 0 ) { // tylko jawne albo niejawne Multiple - command_relay relay; + const command_relay relay; relay.post(user_command::queueevent, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &event->name()); } } @@ -78,13 +78,13 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) case 3: // rozkaz dla AI if (Global.iMultiplayer) { - int i = int(pRozkaz->cString[8]); // długość pierwszego łańcucha (z przodu dwa floaty) + const int i = int(pRozkaz->cString[8]); // długość pierwszego łańcucha (z przodu dwa floaty) CommLog( Now() + " " + std::to_string(pRozkaz->iComm) + " " + std::string(pRozkaz->cString + 11 + i, (unsigned)pRozkaz->cString[10 + i]) + " rcvd"); // nazwa pojazdu jest druga - auto *vehicle = simulation::Vehicles.find( { pRozkaz->cString + 11 + i, (unsigned)pRozkaz->cString[ 10 + i ] } ); + const auto *vehicle = simulation::Vehicles.find( { pRozkaz->cString + 11 + i, (unsigned)pRozkaz->cString[ 10 + i ] } ); if( vehicle != nullptr && vehicle->Mechanik != nullptr ) { vehicle->Mechanik->PutCommand( @@ -114,7 +114,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) if (*pRozkaz->iPar == 0) // sprawdzenie czasu if (*pRozkaz->iPar & 1) // ustawienie czasu { - auto t = pRozkaz->fPar[1]; + const auto t = pRozkaz->fPar[1]; simulation::Time.data().wDay = std::floor(t); // niby nie powinno być dnia, ale... if (Global.fMoveLight >= 0) Global.fMoveLight = t; // trzeba by deklinację Słońca przeliczyć @@ -138,7 +138,7 @@ OnCommandGet(multiplayer::DaneRozkaz *pRozkaz) + " rcvd" ); if (pRozkaz->cString[0]) { // jeśli długość nazwy jest niezerowa szukamy pierwszego pojazdu o takiej nazwie i odsyłamy parametry ramką #7 - auto *vehicle = pRozkaz->cString[1] == '*' ? simulation::Train->Dynamic() : simulation::Vehicles.find(std::string{pRozkaz->cString + 1, (unsigned)pRozkaz->cString[0]}); + const auto *vehicle = pRozkaz->cString[1] == '*' ? simulation::Train->Dynamic() : simulation::Vehicles.find(std::string{pRozkaz->cString + 1, (unsigned)pRozkaz->cString[0]}); if( vehicle != nullptr ) { WyslijNamiary( vehicle ); // wysłanie informacji o pojeździe } @@ -225,7 +225,7 @@ WyslijUszkodzenia(const std::string &t, char fl) DaneRozkaz r; r.iSygn = EU07_MESSAGEHEADER; r.iComm = 13; // numer komunikatu - size_t i = t.length(); + const size_t i = t.length(); r.cString[0] = char(fl); r.cString[1] = char(i); strcpy(r.cString + 2, t.c_str()); // z zerem kończącym @@ -245,7 +245,7 @@ WyslijString(const std::string &t, int n) DaneRozkaz r; r.iSygn = EU07_MESSAGEHEADER; r.iComm = n; // numer komunikatu - size_t i = t.length(); + const size_t i = t.length(); r.cString[0] = char(i); strcpy(r.cString + 1, t.c_str()); // z zerem kończącym COPYDATASTRUCT cData; @@ -271,7 +271,7 @@ WyslijNamiary(TDynamicObject const *Vehicle) r.iSygn = EU07_MESSAGEHEADER; r.iComm = 7; // 7 - dane pojazdu int i = 32; - size_t j = Vehicle->asName.length(); + const size_t j = Vehicle->asName.length(); r.iPar[0] = i; // ilość danych liczbowych r.fPar[1] = Global.fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) r.fPar[2] = Vehicle->MoverParameters->Loc.X; // pozycja X @@ -356,7 +356,7 @@ WyslijObsadzone() for (int i=0; i<1984; ++i) r.cString[i] = 0; // TODO: clean this up, we shouldn't be relying on direct list access - auto &vehiclelist = simulation::Vehicles.sequence(); + const auto &vehiclelist = simulation::Vehicles.sequence(); int i = 0; for( auto *vehicle : vehiclelist ) { diff --git a/input/zmq_input.cpp b/input/zmq_input.cpp index 3ac98224..0e2cc1e2 100644 --- a/input/zmq_input.cpp +++ b/input/zmq_input.cpp @@ -31,7 +31,7 @@ float zmq_input::unpack_float(const zmq::message_t &msg) { } zmq::message_t zmq_input::pack_float(float f) { - uint32_t v = reinterpret_cast(f); + const uint32_t v = reinterpret_cast(f); uint8_t buf[4]; buf[3] = v; buf[2] = v >> 8; @@ -240,7 +240,7 @@ zmq::message_t zmq_input::pack_field(zmq_input::output_fields f) { if (f == output_fields::time_millisecond_of_day) return pack_float(time.wSecond * 1000 + time.wMilliseconds); - TTrain *train = simulation::Train; + const TTrain *train = simulation::Train; if (!train) return pack_float(0.0f); const TTrain::state_t state = train->get_state(); diff --git a/launcher/deferred_image.h b/launcher/deferred_image.h index fcd25fd6..207897b8 100644 --- a/launcher/deferred_image.h +++ b/launcher/deferred_image.h @@ -36,7 +36,7 @@ public: glm::ivec2 size() const { if (image != null_handle) { - auto &tex = GfxRenderer->Texture(image); + const auto &tex = GfxRenderer->Texture(image); return glm::ivec2(tex.get_width(), tex.get_height()); } return glm::ivec2(); diff --git a/launcher/keymapper.cpp b/launcher/keymapper.cpp index 2bc133ef..4c3f9f9d 100644 --- a/launcher/keymapper.cpp +++ b/launcher/keymapper.cpp @@ -13,7 +13,7 @@ bool ui::keymapper_panel::key(int key) if (!is_open || bind_active == user_command::none) return false; - auto it = keyboard.keytonamemap.find(key); + const auto it = keyboard.keytonamemap.find(key); if (it == keyboard.keytonamemap.end()) return false; @@ -26,7 +26,7 @@ bool ui::keymapper_panel::key(int key) key = 0; // Replace the binding with a new key. - auto it2 = keyboard.bindings().find(bind_active); + const auto it2 = keyboard.bindings().find(bind_active); if (it2 != keyboard.bindings().end()) { it2->second = std::tuple(key, std::get(it2->second)); } @@ -57,7 +57,7 @@ void ui::keymapper_panel::render_contents() ImGui::Text((description.size() > 0 ? description : "(No description)").c_str()); // Binding key button - int keycode = std::get(binding.second); + const int keycode = std::get(binding.second); std::string label; if (keycode & keyboard_input::keymodifier::control) diff --git a/launcher/launcheruilayer.cpp b/launcher/launcheruilayer.cpp index 72044fe3..7b05e2aa 100644 --- a/launcher/launcheruilayer.cpp +++ b/launcher/launcheruilayer.cpp @@ -34,7 +34,7 @@ void launcher_ui::on_window_resize(int w, int h) void launcher_ui::render_() { - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove; + const ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove; const float topbar_height = 50 * Global.ui_scale; const auto topbar_button_size = ImVec2(150 * Global.ui_scale, topbar_height - 16); ImGui::SetNextWindowPos(ImVec2(0, 0)); diff --git a/launcher/scenery_list.cpp b/launcher/scenery_list.cpp index 2df6530e..79d73aaa 100644 --- a/launcher/scenery_list.cpp +++ b/launcher/scenery_list.cpp @@ -19,7 +19,7 @@ bool ui::scenerylist_panel::on_key(int key, int action) if (!is_open) return false; - auto it = keyboard.keytonamemap.find(key); + const auto it = keyboard.keytonamemap.find(key); if (it == keyboard.keytonamemap.end()) return false; @@ -50,7 +50,7 @@ void ui::scenerylist_panel::draw_scenery_list() { collapse_open = ImGui::CollapsingHeader(category.first.c_str()); if (collapse_open) { - for (auto desc : category.second) + for (const auto desc : category.second) { std::string name = desc->path.stem().string(); @@ -82,7 +82,7 @@ void ui::scenerylist_panel::draw_scenery_info() void ui::scenerylist_panel::open_link(const std::string &link) { - std::string file = ToLower(link); + const std::string file = ToLower(link); #ifdef _WIN32 system(("start \"eu07_link\" \"" + file + "\"").c_str()); #elif __linux__ @@ -95,7 +95,7 @@ void ui::scenerylist_panel::open_link(const std::string &link) void ui::scenerylist_panel::draw_scenery_image() { if (!selected_scenery->image_path.empty()) { - auto desc = const_cast(selected_scenery); + const auto desc = const_cast(selected_scenery); desc->image = GfxRenderer->Fetch_Texture(selected_scenery->image_path, true); desc->image_path.clear(); } @@ -105,8 +105,8 @@ void ui::scenerylist_panel::draw_scenery_image() tex.create(); if (tex.get_is_ready()) { - float avail_width = ImGui::GetContentRegionAvailWidth(); - float height = avail_width / tex.get_width() * tex.get_height(); + const float avail_width = ImGui::GetContentRegionAvailWidth(); + const float height = avail_width / tex.get_width() * tex.get_height(); ImGui::Image(reinterpret_cast(tex.get_id()), ImVec2(avail_width, height), ImVec2(0, 1), ImVec2(1, 0)); } @@ -238,8 +238,8 @@ void ui::scenerylist_panel::draw_summary_tooltip(const dynamic_desc &dyn_desc) { if (dyn_desc.vehicle && dyn_desc.skin) { - std::string name = (dyn_desc.vehicle->path.parent_path() / dyn_desc.vehicle->path.stem()).string(); - std::string skin = dyn_desc.skin->skin; + const std::string name = (dyn_desc.vehicle->path.parent_path() / dyn_desc.vehicle->path.stem()).string(); + const std::string skin = dyn_desc.skin->skin; ImGui::Text(STR_C("ID: %s"), dyn_desc.name.c_str()); ImGui::NewLine(); @@ -338,7 +338,7 @@ void ui::scenerylist_panel::draw_droptarget(trainset_desc &trainset, int positio if (ImGui::BeginDragDropTarget()) { const ImGuiPayload *payload = ImGui::AcceptDragDropPayload("vehicle_pure"); if (payload) { - skin_set *ptr = *reinterpret_cast(payload->Data); + const skin_set *ptr = *reinterpret_cast(payload->Data); std::shared_ptr skin; for (auto &s : ptr->vehicle.lock()->matching_skinsets) if (s.get() == ptr) @@ -354,7 +354,7 @@ void ui::scenerylist_panel::draw_droptarget(trainset_desc &trainset, int positio payload = ImGui::AcceptDragDropPayload("vehicle_set"); if (payload) { - auto moved = reinterpret_cast(payload->Data); + const auto moved = reinterpret_cast(payload->Data); dynamic_desc desc_copy = moved->dynamic; int offset = 0; @@ -399,14 +399,14 @@ void ui::dynamic_edit_popup::render_content() if (dynamic.vehicle && dynamic.skin) { - std::string name = (dynamic.vehicle->path.parent_path() / dynamic.vehicle->path.stem()).string(); + const std::string name = (dynamic.vehicle->path.parent_path() / dynamic.vehicle->path.stem()).string(); ImGui::Text(STR_C("Type: %s"), name.c_str()); if (ImGui::BeginCombo(STR_C("Skin"), dynamic.skin->skin.c_str(), ImGuiComboFlags_HeightLargest)) { for (auto const &skin : dynamic.vehicle->matching_skinsets) { - bool is_selected = skin == dynamic.skin; + const bool is_selected = skin == dynamic.skin; if (ImGui::Selectable(skin->skin.c_str(), is_selected)) dynamic.skin = skin; if (is_selected) @@ -419,7 +419,7 @@ void ui::dynamic_edit_popup::render_content() if (ImGui::BeginCombo(STR_C("Occupancy"), Translations.lookup_c(dynamic.drivertype.c_str()))) { for (auto const &str : occupancy_names) { - bool is_selected = str == dynamic.drivertype; + const bool is_selected = str == dynamic.drivertype; if (ImGui::Selectable(Translations.lookup_c(str.c_str()), is_selected)) dynamic.drivertype = str; if (is_selected) diff --git a/launcher/scenery_scanner.cpp b/launcher/scenery_scanner.cpp index 7bfa8a07..bb2a1e3d 100644 --- a/launcher/scenery_scanner.cpp +++ b/launcher/scenery_scanner.cpp @@ -111,7 +111,7 @@ void scenery_scanner::parse_trainset(cParser &parser) parser.getTokens(7, false); parser >> datafolder >> skinfile >> mmdfile >> dyn.offset >> dyn.drivertype >> params >> dyn.loadcount; - size_t params_pos = params.find('.'); + const size_t params_pos = params.find('.'); if (params_pos != -1 && params_pos < params.size()) { dyn.params = params.substr(params_pos + 1, -1); params.erase(params_pos); diff --git a/launcher/textures_scanner.cpp b/launcher/textures_scanner.cpp index 201ff967..7eebceab 100644 --- a/launcher/textures_scanner.cpp +++ b/launcher/textures_scanner.cpp @@ -30,7 +30,7 @@ void ui::vehicles_bank::parse_entry(const std::string &line) std::string content; std::shared_ptr meta; - size_t pos = line.find("//"); + const size_t pos = line.find("//"); if (pos != -1) meta = parse_meta(line.substr(pos)); content = line.substr(0, pos); @@ -86,7 +86,7 @@ void ui::vehicles_bank::parse_category_entry(const std::string ¶m) if (tok.size() < 1) return; - auto it = type_map.find(tok[0]); + const auto it = type_map.find(tok[0]); if (it != type_map.end()) ctx_type = it->second; else if (tok[0] >= 'A' && tok[0] <= 'Z') @@ -191,7 +191,7 @@ std::shared_ptr ui::vehicles_bank::parse_meta(const std::string & void ui::vehicles_bank::parse_coupling_rule(const std::string &target, const std::string ¶m) { - auto target_vehicle = get_vehicle(target); + const auto target_vehicle = get_vehicle(target); if (param == "?") return; @@ -249,7 +249,7 @@ std::shared_ptr ui::vehicles_bank::get_vehicle(const std::stri auto path = ctx_path / ToLower(name); path = std::filesystem::path(path.generic_string()); - auto it = vehicles.find(path); + const auto it = vehicles.find(path); if (it != vehicles.end()) { return it->second; } diff --git a/launcher/vehicle_picker.cpp b/launcher/vehicle_picker.cpp index 88c40ef9..8bf9927b 100644 --- a/launcher/vehicle_picker.cpp +++ b/launcher/vehicle_picker.cpp @@ -17,7 +17,7 @@ void ui::vehiclepicker_panel::render_contents() if (ImGui::BeginChild("box1")) { for (auto const &e : type_names) { - deferred_image *image = nullptr; + const deferred_image *image = nullptr; auto it = bank.category_icons.find(e.first); if (it != bank.category_icons.end()) image = &it->second; @@ -47,15 +47,15 @@ void ui::vehiclepicker_panel::render_contents() bool model_added = false; bool can_break = false; - bool map_sel_eq = selected_group && group == *selected_group; + const bool map_sel_eq = selected_group && group == *selected_group; for (auto const &vehicle : kv.second) { if (vehicle->type != selected_type) continue; for (auto const &skinset : vehicle->matching_skinsets) { - bool map_group_eq = skinset->group == group; - bool sel_group_eq = selected_group && skinset->group == *selected_group; + const bool map_group_eq = skinset->group == group; + const bool sel_group_eq = selected_group && skinset->group == *selected_group; if (!model_added && map_group_eq) { model_list.push_back(&group); @@ -81,9 +81,9 @@ void ui::vehiclepicker_panel::render_contents() ImGuiListClipper clipper(model_list.size()); while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { - auto group = model_list[i]; + const auto group = model_list[i]; - deferred_image *image = nullptr; + const deferred_image *image = nullptr; auto it = bank.group_icons.find(*group); if (it != bank.group_icons.end()) image = &it->second; @@ -144,14 +144,14 @@ void ui::vehiclepicker_panel::render_contents() ImGuiListClipper clipper(skinset_list.size()); while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { - auto skin = skinset_list[i]; + const auto skin = skinset_list[i]; //std::string label = skin->skins[0].stem().string(); std::string label = skin->skin; if (skin->meta && !skin->meta->name.empty() && skin->meta->name != "?") label = skin->meta->name; - auto mini = skin->mini ? &skin->mini : &placeholder_mini; + const auto mini = skin->mini ? &skin->mini : &placeholder_mini; if (selectable_image(label.c_str(), skin == selected_skinset, mini, skin)) selected_skinset = skin; diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 76dbf114..5db9c00b 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -629,7 +629,7 @@ void TAnimModel::RaPrepare() TSubModel::iInstance = reinterpret_cast( this ); //żeby nie robić cudzych animacji TSubModel::pasText = &asText; // przekazanie tekstu do wyświetlacza (!!!! do przemyślenia) - for (auto entry : m_animlist) { + for (const auto entry : m_animlist) { entry->PrepareModel(); } } @@ -690,7 +690,7 @@ void TAnimModel::AnimUpdate(double dt) { // wykonanie zakolejkowanych animacji, nawet gdy modele nie są aktualnie wyświetlane acAnimList.remove_if([](std::weak_ptr ptr) { - std::shared_ptr container = ptr.lock(); + const std::shared_ptr container = ptr.lock(); if (!container) return true; diff --git a/model/MdlMngr.cpp b/model/MdlMngr.cpp index 9ead9716..235d4872 100644 --- a/model/MdlMngr.cpp +++ b/model/MdlMngr.cpp @@ -45,7 +45,7 @@ TModel3d * TModelsManager::LoadModel(std::string const &Name, std::string const &virtualName, bool dynamic) { m_models.emplace_back(); - auto model = m_models.back().LoadModel( Name, dynamic ); + const auto model = m_models.back().LoadModel( Name, dynamic ); if( model != nullptr ) { m_modelsmap.emplace( virtualName, m_models.size() - 1 ); } @@ -95,7 +95,7 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const postfix = "^^" + std::to_string(uid); // see if we have it in the databank - auto banklookup { find_in_databank( filename + postfix ) }; + const auto banklookup { find_in_databank( filename + postfix ) }; TModel3d *model { banklookup.second }; if( true == banklookup.first ) { Global.asCurrentTexturePath = buftp; @@ -103,7 +103,7 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const } // first load attempt, check if it's on disk - std::string disklookup { find_on_disk( filename ) }; + const std::string disklookup { find_on_disk( filename ) }; if( false == disklookup.empty() ) { model = LoadModel( disklookup, disklookup + postfix, Dynamic ); // model nie znaleziony, to wczytać @@ -123,7 +123,7 @@ TModelsManager::GetModel(std::string const &Name, bool const Dynamic, bool const std::pair TModelsManager::find_in_databank( std::string const &Name ) { - std::vector filenames { + const std::vector filenames { Name, paths::models + Name }; @@ -141,7 +141,7 @@ TModelsManager::find_in_databank( std::string const &Name ) { std::string TModelsManager::find_on_disk( std::string const &Name ) { - std::vector extensions { { ".e3d" }, { ".t3d" } }; + const std::vector extensions { { ".e3d" }, { ".t3d" } }; for( auto const &extension : extensions ) { auto lookup = FileExists(Name + extension) ? Name : FileExists(paths::models + Name + extension) ? paths::models + Name : ""; diff --git a/model/Model3d.cpp b/model/Model3d.cpp index e6c7124f..4ad3c641 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -183,7 +183,7 @@ void TSubModel::SetSelfIllum(float const Threshold, bool const Includechildren, int TSubModel::SeekFaceNormal(std::vector const &Masks, int const Startface, unsigned int const Mask, glm::vec3 const &Position, gfx::vertex_array const &Vertices) { // szukanie punktu stycznego do (pt), zwraca numer wierzchołka, a nie trójkąta - int facecount = m_geometry.vertex_count / 3; + const int facecount = m_geometry.vertex_count / 3; for (int faceidx = Startface; faceidx < facecount; ++faceidx) { // pętla po trójkątach, od trójkąta (f) @@ -913,7 +913,7 @@ int TSubModel::count_siblings() { auto siblingcount{0}; - auto *sibling{Next}; + const auto *sibling{Next}; while (sibling != nullptr) { ++siblingcount; @@ -1179,7 +1179,7 @@ void TSubModel::RaAnimation(glm::mat4 &m, TAnimType a) case TAnimType::at_Billboard: // obrót w pionie do kamery { glm::mat4 mat = glm::make_mat4(OpenGLMatrices.data_array(GL_MODELVIEW)); - auto gdzie = float3(mat[3][0], mat[3][1], mat[3][2]); // początek układu współrzędnych submodelu względem kamery + const auto gdzie = float3(mat[3][0], mat[3][1], mat[3][2]); // początek układu współrzędnych submodelu względem kamery m = glm::mat4(1.0f); m = glm::translate(m, glm::vec3(gdzie.x, gdzie.y, gdzie.z)); // początek układu zostaje bez zmian m = glm::rotate(m, (float)atan2(gdzie.x, gdzie.z), glm::vec3(0.0f, 1.0f, 0.0f)); // jedynie obracamy w pionie o kąt @@ -1231,9 +1231,9 @@ void TSubModel::serialize_geometry(std::ostream &Output, bool const Packed, bool { if (Packed) { - auto vertices = GfxRenderer->Vertices(m_geometry.handle); - auto userdatas = GfxRenderer->UserData(m_geometry.handle); - bool has_userdata = !userdatas.empty(); + const auto vertices = GfxRenderer->Vertices(m_geometry.handle); + const auto userdatas = GfxRenderer->UserData(m_geometry.handle); + const bool has_userdata = !userdatas.empty(); for (int i = 0; i < vertices.size(); ++i) { vertices[i].serialize_packed(Output, Indexed); @@ -1248,9 +1248,9 @@ void TSubModel::serialize_geometry(std::ostream &Output, bool const Packed, bool } else { - auto vertices = GfxRenderer->Vertices(m_geometry.handle); - auto userdatas = GfxRenderer->UserData(m_geometry.handle); - bool has_userdata = !userdatas.empty(); + const auto vertices = GfxRenderer->Vertices(m_geometry.handle); + const auto userdatas = GfxRenderer->UserData(m_geometry.handle); + const bool has_userdata = !userdatas.empty(); for (int i = 0; i < vertices.size(); ++i) { vertices[i].serialize(Output, Indexed); @@ -1682,7 +1682,7 @@ template size_t get_container_pos(L &list, T o) // strukturę TModel3d::SerializerContext? void TSubModel::serialize(std::ostream &s, std::vector &models, std::vector &names, std::vector &textures, std::vector &transforms) { - size_t end = (size_t)s.tellp() + 256; + const size_t end = (size_t)s.tellp() + 256; if (!Next) sn_utils::ls_int32(s, -1); @@ -1743,7 +1743,7 @@ void TSubModel::serialize(std::ostream &s, std::vector &models, std sn_utils::ls_float32(s, diffuseMultiplier); // fill empty space - size_t fill = end - s.tellp(); + const size_t fill = end - s.tellp(); for (size_t i = 0; i < fill; i++) s.put(0); } @@ -1929,15 +1929,15 @@ void TModel3d::deserialize(std::istream &s, size_t size, bool dynamic) m_geometrybank = GfxRenderer->Create_Bank(); } - std::streampos end = s.tellg() + (std::streampos)size; + const std::streampos end = s.tellg() + (std::streampos)size; bool hastangents{false}; bool hasuserdata{false}; while (s.tellg() < end) { - uint32_t type = sn_utils::ld_uint32(s); - uint32_t size = sn_utils::ld_uint32(s) - 8; - size_t pos = s.tellg(); + const uint32_t type = sn_utils::ld_uint32(s); + const uint32_t size = sn_utils::ld_uint32(s) - 8; + const size_t pos = s.tellg(); std::streampos end = pos + (std::streampos)size; if ((type & 0x00FFFFFF) == MAKE_ID4('S', 'U', 'B', 0)) // submodels @@ -1945,8 +1945,8 @@ void TModel3d::deserialize(std::istream &s, size_t size, bool dynamic) if (Root != nullptr) throw std::runtime_error("e3d: duplicated SUB chunk"); - size_t sm_size = 256 + 64 * (((type & 0xFF000000) >> 24) - '0'); - size_t sm_cnt = size / sm_size; + const size_t sm_size = 256 + 64 * (((type & 0xFF000000) >> 24) - '0'); + const size_t sm_cnt = size / sm_size; iSubModelsCount = (int)sm_cnt; Root = new TSubModel[sm_cnt]; for (size_t i = 0; i < sm_cnt; ++i) @@ -2126,7 +2126,7 @@ void TModel3d::deserialize(std::istream &s, size_t size, bool dynamic) { if (false == Matrices.empty()) throw std::runtime_error("e3d: duplicated TRA chunk"); - size_t t_cnt = size / 64; + const size_t t_cnt = size / 64; Matrices.resize(t_cnt); for (size_t i = 0; i < t_cnt; ++i) @@ -2136,7 +2136,7 @@ void TModel3d::deserialize(std::istream &s, size_t size, bool dynamic) { if (false == Matrices.empty()) throw std::runtime_error("e3d: duplicated TRA chunk"); - size_t t_cnt = size / 128; + const size_t t_cnt = size / 128; Matrices.resize(t_cnt); for (size_t i = 0; i < t_cnt; ++i) @@ -2362,8 +2362,8 @@ void TModel3d::LoadFromBinFile(std::string const &FileName, bool dynamic) std::ifstream file(FileName, std::ios::binary); - uint32_t type = sn_utils::ld_uint32(file); - uint32_t size = sn_utils::ld_uint32(file) - 8; + const uint32_t type = sn_utils::ld_uint32(file); + const uint32_t size = sn_utils::ld_uint32(file) - 8; if (type == MAKE_ID4('E', '3', 'D', '0')) { @@ -2384,7 +2384,7 @@ TSubModel *TModel3d::AppendChildFromGeometry(const std::string &name, const std: { iFlags |= 0x0200; - auto sm = new TSubModel(); + const auto sm = new TSubModel(); sm->Parent = AddToNamed(parent.c_str(), sm); sm->m_geometry.vertex_count = vertices.size(); sm->m_geometry.index_count = indices.size(); diff --git a/model/Texture.cpp b/model/Texture.cpp index c58f2bdb..662b7992 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -137,7 +137,7 @@ void opengl_texture::gles_match_internalformat(GLuint internalformat) for (int y = 0; y < data_height; y++) for (int x = 0; x < data_width; x++) { - int offset = (y * data_width + x) * 3; + const int offset = (y * data_width + x) * 3; reverse[offset + 0] = data[offset + 2]; reverse[offset + 1] = data[offset + 1]; reverse[offset + 2] = data[offset + 0]; @@ -154,7 +154,7 @@ void opengl_texture::gles_match_internalformat(GLuint internalformat) for (int y = 0; y < data_height; y++) for (int x = 0; x < data_width; x++) { - int offset = (y * data_width + x) * 4; + const int offset = (y * data_width + x) * 4; reverse[offset + 0] = data[offset + 2]; reverse[offset + 1] = data[offset + 1]; reverse[offset + 2] = data[offset + 0]; @@ -206,9 +206,9 @@ void opengl_texture::gles_match_internalformat(GLuint internalformat) for (int y = 0; y < data_height; y++) for (int x = 0; x < data_width; x++) { - int pixel = y * data_width + x; - int in_off = pixel * in_c; - int out_off = pixel * out_c; + const int pixel = y * data_width + x; + const int in_off = pixel * in_c; + const int out_off = pixel * out_c; for (int i = 0; i < out_c; i++) { if (i < in_c) @@ -426,9 +426,9 @@ opengl_texture::make_request() { auto const components { Split( name, '?' ) }; - auto dictionary = std::make_shared( components.back() ); + const auto dictionary = std::make_shared( components.back() ); - auto rt = std::make_shared(); + const auto rt = std::make_shared(); rt->shared_tex = this; Application.request( { ToLower( components.front() ), dictionary, rt } ); @@ -623,7 +623,7 @@ opengl_texture::load_DDS() { void opengl_texture::load_KTX() { std::ifstream file( name + type, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); - std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file + const std::size_t filesize = static_cast(file.tellg()); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards std::vector filecontent; @@ -665,7 +665,7 @@ opengl_texture::load_KTX() { started = true; } - size_t data_offset = data.size(); + const size_t data_offset = data.size(); data.resize(data.size() + sub_data.size_bytes); memcpy(data.data() + data_offset, sub_data.buff, sub_data.size_bytes); } @@ -705,7 +705,7 @@ opengl_texture::load_TEX() { file.read( (char *)&data_width, sizeof( int ) ); file.read( (char *)&data_height, sizeof( int ) ); - std::size_t datasize = data_width * data_height * ( hasalpha ? 4 : 3 ); + const std::size_t datasize = data_width * data_height * ( hasalpha ? 4 : 3 ); data.resize( datasize ); file.read( reinterpret_cast( &data[0] ), datasize ); @@ -772,7 +772,7 @@ opengl_texture::load_TGA() { unsigned char buffer[ 4 ] = { 255, 255, 255, 255 }; // alpha channel will be white auto datapointer = (unsigned int*)&data[0]; - auto bufferpointer = (unsigned int*)&buffer[ 0 ]; + const auto bufferpointer = (unsigned int*)&buffer[ 0 ]; int const pixelcount = data_width * data_height; @@ -798,7 +798,7 @@ opengl_texture::load_TGA() { const int pixelcount = data_width * data_height; auto datapointer = (unsigned int *)&data[0]; - auto bufferpointer = (unsigned int *)&buffer[ 0 ]; + const auto bufferpointer = (unsigned int *)&buffer[ 0 ]; do { unsigned char chunkheader = 0; @@ -963,7 +963,7 @@ opengl_texture::create( bool const Static ) { glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); wrap_mode_s = GL_CLAMP_TO_BORDER; wrap_mode_t = GL_CLAMP_TO_BORDER; - float borderColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; + const float borderColor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, borderColor); } glTexParameteri( target, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); @@ -1006,7 +1006,7 @@ opengl_texture::create( bool const Static ) { // now map that mess into opengl internal format GLint components = data_components; - auto f_it = precompressed_formats.find(data_format); + const auto f_it = precompressed_formats.find(data_format); if (f_it != precompressed_formats.end()) components = data_format; @@ -1024,7 +1024,7 @@ opengl_texture::create( bool const Static ) { gles_match_internalformat(internal_format); } - auto blocksize_it = precompressed_formats.find(internal_format); + const auto blocksize_it = precompressed_formats.find(internal_format); if ( data_mapcount == 1 && !glGenerateMipmap ) { glTexParameteri(target, GL_GENERATE_MIPMAP, GL_TRUE); @@ -1411,7 +1411,7 @@ std::string texture_manager::info() const { // TODO: cache this data and update only during resource sweep - std::size_t totaltexturecount{ m_textures.size() - 1 }; + const std::size_t totaltexturecount{ m_textures.size() - 1 }; std::size_t totaltexturesize{ 0 }; #ifdef EU07_DEFERRED_TEXTURE_UPLOAD std::size_t readytexturecount{ 0 }; diff --git a/network/backend/asio.cpp b/network/backend/asio.cpp index 972d5e5d..1ff27bb4 100644 --- a/network/backend/asio.cpp +++ b/network/backend/asio.cpp @@ -52,13 +52,13 @@ void network::tcp::connection::handle_header(const asio::error_code &err, size_t return; } - uint32_t sig = sn_utils::ld_uint32(header); + const uint32_t sig = sn_utils::ld_uint32(header); if (sig != NETWORK_MAGIC) { disconnect(); return; } - uint32_t len = sn_utils::ld_uint32(header); + const uint32_t len = sn_utils::ld_uint32(header); m_body_buffer.resize(len); if (len > MAX_MSG_SIZE) { disconnect(); @@ -82,7 +82,7 @@ void network::tcp::connection::handle_data(const asio::error_code &err, size_t b } std::istringstream stream(m_body_buffer); - std::shared_ptr msg = deserialize_message(stream); + const std::shared_ptr msg = deserialize_message(stream); if (message_handler) message_handler(*msg); @@ -91,14 +91,14 @@ void network::tcp::connection::handle_data(const asio::error_code &err, size_t b void network::tcp::connection::write_message(const message &msg, std::ostream &stream) { - size_t beg = (size_t)stream.tellp(); + const size_t beg = (size_t)stream.tellp(); sn_utils::ls_uint32(stream, NETWORK_MAGIC); sn_utils::ls_uint32(stream, 0); serialize_message(msg, stream); - size_t size = (size_t)stream.tellp() - beg - 8; + const size_t size = (size_t)stream.tellp() - beg - 8; if (size > MAX_MSG_SIZE) { ErrorLog("net: message too big", logtype::net); return; @@ -136,7 +136,7 @@ void network::tcp::connection::send_message(const message &msg) network::tcp::server::server(std::shared_ptr buf, asio::io_context &io_ctx, const std::string &host, uint32_t port) : network::server(buf), m_acceptor(io_ctx), m_io_ctx(io_ctx) { - auto endpoint = asio::ip::tcp::endpoint(asio::ip::make_address(host), port); + const auto endpoint = asio::ip::tcp::endpoint(asio::ip::make_address(host), port); m_acceptor.open(endpoint.protocol()); m_acceptor.set_option(asio::socket_base::reuse_address(true)); m_acceptor.set_option(asio::ip::tcp::no_delay(true)); @@ -185,7 +185,7 @@ void network::tcp::client::connect() auto conn = std::make_shared(io_ctx, true, resume_frame_counter); conn->set_handler(std::bind(&client::handle_message, this, conn, std::placeholders::_1)); - asio::ip::tcp::endpoint endpoint( + const asio::ip::tcp::endpoint endpoint( asio::ip::make_address(host), port); conn->m_socket.open(endpoint.protocol()); conn->m_socket.set_option(asio::ip::tcp::no_delay(true)); diff --git a/network/manager.cpp b/network/manager.cpp index 37d72401..acc8e26a 100644 --- a/network/manager.cpp +++ b/network/manager.cpp @@ -21,7 +21,7 @@ command_queue::commands_map network::server_manager::pop_commands() { command_queue::commands_map map; - for (auto srv : servers) + for (const auto srv : servers) add_to_dequemap(map, srv->pop_commands()); return map; @@ -38,7 +38,7 @@ void network::server_manager::push_delta(double render_dt, double dt, double syn msg.sync = sync; msg.commands = commands; - for (auto srv : servers) + for (const auto srv : servers) srv->push_delta(msg); serialize_message(msg, *backbuffer.get()); @@ -46,7 +46,7 @@ void network::server_manager::push_delta(double render_dt, double dt, double syn void network::server_manager::create_server(const std::string &backend, const std::string &conf) { - auto it = backend_list().find(backend); + const auto it = backend_list().find(backend); if (it == backend_list().end()) { ErrorLog("net: unknown backend: " + backend); return; @@ -61,7 +61,7 @@ network::manager::manager() void network::manager::update() { - for (auto &backend : backend_list()) + for (const auto &backend : backend_list()) backend.second->update(); if (client) @@ -76,7 +76,7 @@ void network::manager::create_server(const std::string &backend, const std::stri void network::manager::connect(const std::string &backend, const std::string &conf) { - auto it = backend_list().find(backend); + const auto it = backend_list().find(backend); if (it == backend_list().end()) { ErrorLog("net: unknown backend: " + backend); return; diff --git a/network/message.cpp b/network/message.cpp index eb0d4f54..87958c9e 100644 --- a/network/message.cpp +++ b/network/message.cpp @@ -55,11 +55,11 @@ void ::network::request_command::serialize(std::ostream &stream) const void network::request_command::deserialize(std::istream &stream) { - uint32_t commands_size = sn_utils::ld_uint32(stream); + const uint32_t commands_size = sn_utils::ld_uint32(stream); for (uint32_t i = 0; i < commands_size; i++) { uint32_t recipient = sn_utils::ld_uint32(stream); - uint32_t sequence_size = sn_utils::ld_uint32(stream); + const uint32_t sequence_size = sn_utils::ld_uint32(stream); command_queue::commanddata_sequence sequence; for (uint32_t i = 0; i < sequence_size; i++) @@ -103,7 +103,7 @@ void network::frame_info::deserialize(std::istream &stream) std::shared_ptr network::deserialize_message(std::istream &stream) { - auto type = (message::type_e)sn_utils::ld_uint16(stream); + const auto type = (message::type_e)sn_utils::ld_uint16(stream); std::shared_ptr msg; diff --git a/network/network.cpp b/network/network.cpp index ae83bf78..a377404a 100644 --- a/network/network.cpp +++ b/network/network.cpp @@ -175,7 +175,7 @@ void network::client::update() // client std::tuple network::client::get_next_delta(int counter) { - auto now = std::chrono::high_resolution_clock::now(); + const auto now = std::chrono::high_resolution_clock::now(); if (counter == 1) { frame_time = now - last_frame; last_frame = now; @@ -187,23 +187,22 @@ std::tuple network::client::get_nex command_queue::commands_map>(0.0, 0.0, command_queue::commands_map()); } - - float size = delta_queue.size() - consume_counter; + const float size = delta_queue.size() - consume_counter; const auto& entry = delta_queue.front(); - float mult = entry.render_dt / std::chrono::duration_cast>(frame_time).count(); + const float mult = entry.render_dt / std::chrono::duration_cast>(frame_time).count(); if (counter == 1 && size < MAX_BUFFER_SIZE * 2.0f) { last_target = last_target * TARGET_MIX + (std::min(TARGET_MIN + jitteriness * JITTERINESS_MULTIPIER, MAX_BUFFER_SIZE)) * (1.0f - TARGET_MIX); - float diff = size - last_target; + const float diff = size - last_target; jitteriness = std::max(jitteriness * JITTERINESS_MIX, std::abs(diff)); - float speed = 1.0f + diff * CONSUME_MULTIPIER; + const float speed = 1.0f + diff * CONSUME_MULTIPIER; consume_counter += speed; } - float last_rcv_diff = std::chrono::duration_cast>(now - last_rcv).count(); + const float last_rcv_diff = std::chrono::duration_cast>(now - last_rcv).count(); if (size > MAX_BUFFER_SIZE || consume_counter > mult || last_rcv_diff > 1.0f) { if (consume_counter > mult) { @@ -266,7 +265,7 @@ void network::client::handle_message(std::shared_ptr conn, const mes if (msg.type == message::FRAME_INFO) { resume_frame_counter++; - auto delta = dynamic_cast(msg); + const auto delta = dynamic_cast(msg); delta_queue.push(delta); last_rcv = std::chrono::high_resolution_clock::now(); } diff --git a/rendering/flip-s3tc.h b/rendering/flip-s3tc.h index 16c0ab1b..77375c76 100644 --- a/rendering/flip-s3tc.h +++ b/rendering/flip-s3tc.h @@ -125,7 +125,7 @@ void flip_dxt1_image(void *data, int width, int height) { int x, y; struct dxt1_block temp1, temp2; - auto blocks = (struct dxt1_block *)data; + const auto blocks = (struct dxt1_block *)data; width = (width + 3) / 4; height = (height + 3) / 4; @@ -154,7 +154,7 @@ void flip_dxt23_image(void *data, int width, int height) { int x, y; struct dxt23_block temp1, temp2; - auto blocks = (struct dxt23_block *)data; + const auto blocks = (struct dxt23_block *)data; width = (width + 3) / 4; height = (height + 3) / 4; @@ -183,7 +183,7 @@ void flip_dxt45_image(void *data, int width, int height) { int x, y; struct dxt45_block temp1, temp2; - auto blocks = (struct dxt45_block *)data; + const auto blocks = (struct dxt45_block *)data; width = (width + 3) / 4; height = (height + 3) / 4; diff --git a/rendering/frustum.cpp b/rendering/frustum.cpp index afe16441..a1fc4373 100644 --- a/rendering/frustum.cpp +++ b/rendering/frustum.cpp @@ -171,7 +171,7 @@ cFrustum::cube_inside( float const X, float const Y, float const Z, float const void cFrustum::normalize_plane( cFrustum::side const Side ) { - float magnitude = + const float magnitude = std::sqrt( m_frustum[ Side ][ plane_A ] * m_frustum[ Side ][ plane_A ] + m_frustum[ Side ][ plane_B ] * m_frustum[ Side ][ plane_B ] diff --git a/rendering/geometrybank.cpp b/rendering/geometrybank.cpp index fcd731dd..66ac1097 100644 --- a/rendering/geometrybank.cpp +++ b/rendering/geometrybank.cpp @@ -212,7 +212,7 @@ void calculate_indices( index_array &Indices, vertex_array &Vertices, userdata_a vertex_array indexedvertices{}; userdata_array indexeduserdata{}; indexedvertices.reserve( std::max( 100, Vertices.size() / 3 ) ); // optimistic guesstimate, but should reduce re-allocation somewhat - bool has_userdata = !Userdata.empty(); + const bool has_userdata = !Userdata.empty(); if (has_userdata) indexeduserdata.reserve(std::max(100, Userdata.size() / 3)); auto const matchtolerance { 1e-5f * tolerancescale }; @@ -258,7 +258,7 @@ geometry_bank::create( gfx::vertex_array &Vertices, userdata_array &Userdata, un m_chunks.emplace_back( Vertices, Userdata, Type ); // NOTE: handle is effectively (index into chunk array + 1) this leaves value of 0 to serve as error/empty handle indication - gfx::geometry_handle chunkhandle { 0, static_cast(m_chunks.size()) }; + const gfx::geometry_handle chunkhandle { 0, static_cast(m_chunks.size()) }; // template method implementation create_( chunkhandle ); // all done @@ -273,7 +273,7 @@ geometry_bank::create( gfx::index_array &Indices, gfx::vertex_array &Vertices, u m_chunks.emplace_back( Indices, Vertices, Userdata, Type ); // NOTE: handle is effectively (index into chunk array + 1) this leaves value of 0 to serve as error/empty handle indication - gfx::geometry_handle chunkhandle { 0, static_cast(m_chunks.size()) }; + const gfx::geometry_handle chunkhandle { 0, static_cast(m_chunks.size()) }; // template method implementation create_( chunkhandle ); // all done diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index 41bff159..9b9e0643 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -71,7 +71,7 @@ light_array::update() { // set intensity if( light.count > 0 ) { - bool isEnabled = light.index == end::front ? !light.owner->HeadlightsAoff : !light.owner->HeadlightsBoff; + const bool isEnabled = light.index == end::front ? !light.owner->HeadlightsAoff : !light.owner->HeadlightsBoff; light.intensity = std::max(0.0f, std::log((float)light.count + 1.0f)); if (light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // tylko przyciemnione diff --git a/rendering/opengl33particles.cpp b/rendering/opengl33particles.cpp index a54173e6..433583de 100644 --- a/rendering/opengl33particles.cpp +++ b/rendering/opengl33particles.cpp @@ -120,7 +120,7 @@ opengl33_particles::render() { if (!m_shader) { gl::shader vert("smoke.vert"); gl::shader frag("smoke.frag"); - auto prog = new gl::program({vert, frag}); + const auto prog = new gl::program({vert, frag}); m_shader = std::unique_ptr(prog); } diff --git a/rendering/opengl33precipitation.cpp b/rendering/opengl33precipitation.cpp index e31eb25f..ef8e06b9 100644 --- a/rendering/opengl33precipitation.cpp +++ b/rendering/opengl33precipitation.cpp @@ -36,8 +36,8 @@ opengl33_precipitation::create( int const Tesselation ) { std::uint16_t index = 0; // auto const radius { 25.f }; // cylinder radius - std::vector radii { 25.f, 10.f, 5.f, 1.f }; - for( auto radius : radii ) { + const std::vector radii { 25.f, 10.f, 5.f, 1.f }; + for (const auto radius : radii ) { for( int i = 0; i <= latitudes; ++i ) { @@ -54,7 +54,7 @@ opengl33_precipitation::create( int const Tesselation ) { m_vertices.emplace_back( glm::vec3( -x * zr, -z * heightfactor, -y * zr ) * radius ); // uvs // NOTE: first and last row receives modified u values to deal with limitation of mapping onto triangles - auto u = ( + const auto u = ( i == 0 ? longitude + longitudehalfstep : i == latitudes ? longitude - longitudehalfstep : longitude ); diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index bf9c0c73..f6cf479c 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -393,7 +393,7 @@ bool opengl33_renderer::AddViewport(const global_settings::extraviewport_config vp->proj_type = viewport_config::custom; vp->draw_range = conf.draw_range; - bool ret = init_viewport(*vp); + const bool ret = init_viewport(*vp); glfwMakeContextCurrent(m_window); return ret; @@ -445,7 +445,7 @@ bool opengl33_renderer::init_viewport(viewport_config &vp) glBindVertexArray(v); } - int samples = 1 << Global.iMultisampling; + const int samples = 1 << Global.iMultisampling; model_ubo->bind_uniform(); scene_ubo->bind_uniform(); @@ -510,8 +510,8 @@ bool opengl33_renderer::init_viewport(viewport_config &vp) if (Global.gfx_postfx_ssao_enabled) { - int ssao_w = std::max(1, vp.width / 2); - int ssao_h = std::max(1, vp.height / 2); + const int ssao_w = std::max(1, vp.width / 2); + const int ssao_h = std::max(1, vp.height / 2); vp.ssao_tex = std::make_unique(); vp.ssao_tex->alloc_rendertarget(GL_R8, GL_RED, ssao_w, ssao_h, 1, 1, GL_CLAMP_TO_EDGE); @@ -559,7 +559,7 @@ bool opengl33_renderer::Render() if (!Global.gfx_usegles) { - std::optional result = m_timequery->result(); + const std::optional result = m_timequery->result(); if (result) { m_gllasttime = *result; m_timequery->begin(); @@ -622,7 +622,7 @@ void opengl33_renderer::SwapBuffers() { Timer::subsystem.gfx_swap.start(); - for (auto &viewport : m_viewports) { + for (const auto &viewport : m_viewports) { if (viewport->window && viewport->real_window) glfwSwapBuffers(viewport->window); } @@ -1489,7 +1489,7 @@ glm::mat4 opengl33_renderer::perspective_projection_raw(float fovy, float aspect glm::mat4 opengl33_renderer::ortho_projection(float l, float r, float b, float t, float znear, float zfar) { - glm::mat4 proj = glm::ortho(l, r, b, t, znear, zfar); + const glm::mat4 proj = glm::ortho(l, r, b, t, znear, zfar); if (GLAD_GL_ARB_clip_control || GLAD_GL_EXT_clip_control) // when clip_control available, use projection matrix with 1..0 Z range return glm::mat4( // @@ -2141,11 +2141,11 @@ material_handle opengl33_renderer::Fetch_Material(std::string const &Filename, b std::shared_ptr opengl33_renderer::Fetch_Shader(const std::string &name) { - auto it = m_shaders.find(name); + const auto it = m_shaders.find(name); if (it == m_shaders.end()) { gl::shader fragment("mat_" + name + ".frag"); - auto program = new gl::program({fragment, *m_vertex_shader.get()}); + const auto program = new gl::program({fragment, *m_vertex_shader.get()}); m_shaders.insert({name, std::shared_ptr(program)}); } @@ -2305,7 +2305,7 @@ void opengl33_renderer::Bind_Material_Shadow(material_handle const Material) { if (Material != null_handle) { - auto &material = m_materials.material(Material); + const auto &material = m_materials.material(Material); if (material.textures[0] != null_handle) { @@ -3653,7 +3653,7 @@ void opengl33_renderer::Render(TSubModel *Submodel) if ((Submodel->iVisible) && (TSubModel::fSquareDist >= Submodel->fSquareMinDist) && (TSubModel::fSquareDist < Submodel->fSquareMaxDist)) { - glm::mat4 future_stack = model_ubs.future; + const glm::mat4 future_stack = model_ubs.future; if (Submodel->iFlags & 0xC000) { @@ -3664,7 +3664,7 @@ void opengl33_renderer::Render(TSubModel *Submodel) { Submodel->RaAnimation(Submodel->b_aAnim); - glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); + const glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); model_ubs.future *= (mv * Submodel->future_transform) * glm::inverse(mv); } } @@ -4133,8 +4133,8 @@ void opengl33_renderer::Render_vr_models() Global.pCamera.SetMatrix(tmpmat); tmpmat = glm::dmat3(tmpmat); glMultMatrixd(glm::value_ptr(glm::inverse(tmpmat))); - std::vector list = vr->get_render_models(); - material_data data; + const std::vector list = vr->get_render_models(); + const material_data data; for (TModel3d *mdl : list) Render(mdl, &data, 0.0); ::glPopMatrix(); @@ -4516,7 +4516,7 @@ bool opengl33_renderer::Render_Alpha(TDynamicObject *Dynamic) bool opengl33_renderer::Render_Alpha(TModel3d *Model, material_data const *Material, float const Squaredistance) { - auto alpha = (Material != nullptr ? Material->textures_alpha : 0x30300030); + const auto alpha = (Material != nullptr ? Material->textures_alpha : 0x30300030); if (0 == (alpha & Model->iFlags & 0x2F2F002F)) { @@ -5043,7 +5043,7 @@ void opengl33_renderer::Update(double const Deltatime) // adjust draw ranges etc, based on recent performance if (Global.targetfps != 0.0f) { - float fps_diff = Global.targetfps - m_framerate; + const float fps_diff = Global.targetfps - m_framerate; if (fps_diff > 0.0f) Global.fDistanceFactor = std::max(0.5f, Global.fDistanceFactor - 0.05f); else @@ -5291,9 +5291,9 @@ void opengl33_renderer::Update_Lights(light_array &Lights) bool opengl33_renderer::Init_caps() { - std::string gl_renderer((char *)glGetString(GL_RENDERER)); - std::string gl_vendor((char *)glGetString(GL_VENDOR)); - std::string gl_version((char *)glGetString(GL_VERSION)); + const std::string gl_renderer((char *)glGetString(GL_RENDERER)); + const std::string gl_vendor((char *)glGetString(GL_VENDOR)); + const std::string gl_version((char *)glGetString(GL_VERSION)); crashreport_add_info("gl_renderer", gl_renderer); crashreport_add_info("gl_vendor", gl_vendor); @@ -5314,7 +5314,7 @@ bool opengl33_renderer::Init_caps() WriteLog("Supported extensions:"); for (int i = 0; i < extCount; i++) { - auto ext = (const char *)glGetStringi(GL_EXTENSIONS, i); + const auto ext = (const char *)glGetStringi(GL_EXTENSIONS, i); WriteLog(ext); } WriteLog("--------"); diff --git a/rendering/openglgeometrybank.cpp b/rendering/openglgeometrybank.cpp index ec950c0f..168b59d2 100644 --- a/rendering/openglgeometrybank.cpp +++ b/rendering/openglgeometrybank.cpp @@ -249,7 +249,7 @@ opengl_vbogeometrybank::bind_streams( gfx::stream_units const &Units, unsigned i ::glDisableClientState( GL_COLOR_ARRAY ); } if( Streams & gfx::stream::texture ) { - for( auto unit : Units.texture ) { + for (const auto unit : Units.texture ) { ::glClientActiveTexture( GL_TEXTURE0 + unit ); ::glTexCoordPointer( 2, GL_FLOAT, sizeof( gfx::basic_vertex ), reinterpret_cast( offsetof(gfx::basic_vertex, texture) + sizeof( gfx::basic_vertex ) * offset ) ); ::glEnableClientState( GL_TEXTURE_COORD_ARRAY ); @@ -257,7 +257,7 @@ opengl_vbogeometrybank::bind_streams( gfx::stream_units const &Units, unsigned i m_activetexturearrays = Units.texture; } else { - for( auto unit : Units.texture ) { + for (const auto unit : Units.texture ) { ::glClientActiveTexture( GL_TEXTURE0 + unit ); ::glDisableClientState( GL_TEXTURE_COORD_ARRAY ); } @@ -273,7 +273,7 @@ opengl_vbogeometrybank::release_streams() { ::glDisableClientState( GL_VERTEX_ARRAY ); ::glDisableClientState( GL_NORMAL_ARRAY ); ::glDisableClientState( GL_COLOR_ARRAY ); - for( auto unit : m_activetexturearrays ) { + for (const auto unit : m_activetexturearrays ) { ::glClientActiveTexture( GL_TEXTURE0 + unit ); ::glDisableClientState( GL_TEXTURE_COORD_ARRAY ); } @@ -321,7 +321,7 @@ opengl_dlgeometrybank::draw_( gfx::geometry_handle const &Geometry, gfx::stream_ auto const &vertex { chunk.vertices[ index ] }; if( Streams & gfx::stream::normal ) { ::glNormal3fv( glm::value_ptr( vertex.normal ) ); } else if( Streams & gfx::stream::color ) { ::glColor3fv( glm::value_ptr( vertex.normal ) ); } - if( Streams & gfx::stream::texture ) { for( auto unit : Units.texture ) { ::glMultiTexCoord2fv( unit, glm::value_ptr( vertex.texture ) ); } } + if( Streams & gfx::stream::texture ) { for (const auto unit : Units.texture ) { ::glMultiTexCoord2fv( unit, glm::value_ptr( vertex.texture ) ); } } if( Streams & gfx::stream::position ) { ::glVertex3fv( glm::value_ptr( vertex.position ) ); } } } @@ -330,7 +330,7 @@ opengl_dlgeometrybank::draw_( gfx::geometry_handle const &Geometry, gfx::stream_ for( auto const &vertex : chunk.vertices ) { if( Streams & gfx::stream::normal ) { ::glNormal3fv( glm::value_ptr( vertex.normal ) ); } else if( Streams & gfx::stream::color ) { ::glColor3fv( glm::value_ptr( vertex.normal ) ); } - if( Streams & gfx::stream::texture ) { for( auto unit : Units.texture ) { ::glMultiTexCoord2fv( unit, glm::value_ptr( vertex.texture ) ); } } + if( Streams & gfx::stream::texture ) { for (const auto unit : Units.texture ) { ::glMultiTexCoord2fv( unit, glm::value_ptr( vertex.texture ) ); } } if( Streams & gfx::stream::position ) { ::glVertex3fv( glm::value_ptr( vertex.position ) ); } } } diff --git a/rendering/openglgeometrybank.h b/rendering/openglgeometrybank.h index ec6bdd89..1ab47445 100644 --- a/rendering/openglgeometrybank.h +++ b/rendering/openglgeometrybank.h @@ -87,7 +87,7 @@ public: opengl_dlgeometrybank() = default; // destructor: ~opengl_dlgeometrybank() { - for( auto &chunkrecord : m_chunkrecords ) { + for (const auto &chunkrecord : m_chunkrecords ) { ::glDeleteLists( chunkrecord.list, 1 ); } } private: diff --git a/rendering/openglprecipitation.cpp b/rendering/openglprecipitation.cpp index fc93b2a9..ce73800d 100644 --- a/rendering/openglprecipitation.cpp +++ b/rendering/openglprecipitation.cpp @@ -39,8 +39,8 @@ opengl_precipitation::create( int const Tesselation ) { std::uint16_t index = 0; // auto const radius { 25.f }; // cylinder radius - std::vector radii { 25.f, 10.f, 5.f, 1.f }; - for( auto radius : radii ) { + const std::vector radii { 25.f, 10.f, 5.f, 1.f }; + for (const auto radius : radii ) { for( int i = 0; i <= latitudes; ++i ) { @@ -57,7 +57,7 @@ opengl_precipitation::create( int const Tesselation ) { m_vertices.emplace_back( glm::vec3( -x * zr, -z * heightfactor, -y * zr ) * radius ); // uvs // NOTE: first and last row receives modified u values to deal with limitation of mapping onto triangles - auto u = ( + const auto u = ( i == 0 ? longitude + longitudehalfstep : i == latitudes ? longitude - longitudehalfstep : longitude ); diff --git a/rendering/openglrenderer.cpp b/rendering/openglrenderer.cpp index 08016c40..668ba201 100644 --- a/rendering/openglrenderer.cpp +++ b/rendering/openglrenderer.cpp @@ -143,7 +143,7 @@ opengl_renderer::Init( GLFWwindow *Window ) { ::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, m_picktexture, 0 ); ::glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_pickdepthbuffer ); // check if we got it working - GLenum status = ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ); + const GLenum status = ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ); if( status == GL_FRAMEBUFFER_COMPLETE_EXT ) { WriteLog( "Picking framebuffer setup complete" ); } @@ -288,7 +288,7 @@ opengl_renderer::Init( GLFWwindow *Window ) { ::glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X, m_environmentcubetexture, 0 ); ::glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_environmentdepthbuffer ); // check if we got it working - GLenum status = ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ); + const GLenum status = ::glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ); if( status == GL_FRAMEBUFFER_COMPLETE_EXT ) { WriteLog( "Reflections framebuffer setup complete" ); m_environmentcubetexturesupport = true; @@ -3738,7 +3738,7 @@ opengl_renderer::Render_Alpha( TDynamicObject *Dynamic ) { bool opengl_renderer::Render_Alpha( TModel3d *Model, material_data const *Material, float const Squaredistance ) { - auto alpha = + const auto alpha = ( Material != nullptr ? Material->textures_alpha : 0x30300030 ); @@ -4393,9 +4393,9 @@ opengl_renderer::Disable_Lights() { bool opengl_renderer::Init_caps() { - std::string gl_renderer((char *)glGetString(GL_RENDERER)); - std::string gl_vendor((char *)glGetString(GL_VENDOR)); - std::string gl_version((char *)glGetString(GL_VERSION)); + const std::string gl_renderer((char *)glGetString(GL_RENDERER)); + const std::string gl_vendor((char *)glGetString(GL_VENDOR)); + const std::string gl_version((char *)glGetString(GL_VERSION)); crashreport_add_info("gl_renderer", gl_renderer); crashreport_add_info("gl_vendor", gl_vendor); @@ -4414,7 +4414,7 @@ opengl_renderer::Init_caps() { m_isATI = (gl_vendor.find("ATI") != -1); - auto extensions = (char*)glGetString( GL_EXTENSIONS ); + const auto extensions = (char*)glGetString( GL_EXTENSIONS ); if (extensions) WriteLog( "Supported extensions: \n" + std::string(extensions)); diff --git a/rendering/openglskydome.cpp b/rendering/openglskydome.cpp index 58951f17..9990d9e0 100644 --- a/rendering/openglskydome.cpp +++ b/rendering/openglskydome.cpp @@ -57,7 +57,7 @@ void opengl_skydome::update() { if( true == skydome.is_dirty() ) { if( ( m_coloursbuffer > 0 ) && ( m_coloursbuffer != (GLuint)-1 ) ) { ::glBindBuffer( GL_ARRAY_BUFFER, m_coloursbuffer ); - auto &colors{ skydome.colors() }; + const auto &colors{ skydome.colors() }; /* float twilightfactor = std::clamp( -simulation::Environment.sun().getAngle(), 0.0f, 18.0f ) / 18.0f; auto gamma = std::lerp( glm::vec3( 0.45f ), glm::vec3( 1.0f ), twilightfactor ); diff --git a/rendering/renderer.cpp b/rendering/renderer.cpp index 610473a3..919eb4ac 100644 --- a/rendering/renderer.cpp +++ b/rendering/renderer.cpp @@ -21,7 +21,7 @@ bool gfx_renderer_factory::register_backend(const std::string &backend, gfx_rend std::unique_ptr gfx_renderer_factory::create(const std::string &backend) { - auto it = backends.find(backend); + const auto it = backends.find(backend); if (it != backends.end()) return it->second(); diff --git a/rendering/screenshot.cpp b/rendering/screenshot.cpp index f8f888d9..cba86e68 100644 --- a/rendering/screenshot.cpp +++ b/rendering/screenshot.cpp @@ -44,7 +44,7 @@ void screenshot_manager::screenshot_save_thread( char *img, int w, int h ) perf = ts.tv_nsec; #endif - std::string filename = Global.screenshot_dir + "/" + std::string(datetime) + + const std::string filename = Global.screenshot_dir + "/" + std::string(datetime) + "_" + std::to_string(perf) + ".png"; if (png_image_write_to_file(&png, filename.c_str(), 0, img, stride, nullptr) == 1) diff --git a/scene/scene.cpp b/scene/scene.cpp index 14825705..3ccbde8c 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -450,7 +450,7 @@ basic_cell::erase( TAnimModel *Instance ) { if( mat != nullptr ) { for( int i = 0; i < 5; ++i ) { key.skins[i] = mat->replacable_skins[i]; } } - auto bucket = m_instancebuckets_opaque.find( key ); + const auto bucket = m_instancebuckets_opaque.find( key ); if( bucket != m_instancebuckets_opaque.end() ) { bucket->second.erase( std::remove( std::begin( bucket->second ), std::end( bucket->second ), Instance ), @@ -511,7 +511,7 @@ basic_cell::find( glm::dvec3 const &Point, float const Radius, bool const Onlyco float distance; float const distancecutoff { Radius * Radius }; // we'll ignore vehicles farther than this - for( auto *path : m_paths ) { + for (const auto *path : m_paths ) { for( auto *vehicle : path->Dynamics ) { if( true == Onlycontrolled && vehicle->Mechanik == nullptr ) { @@ -682,7 +682,7 @@ basic_cell::launch_event( TEventLauncher *Launcher, bool local_only ) { simulation::Events.AddToQuery( Launcher->Event1, nullptr ); } } else { - command_relay commandrelay; + const command_relay commandrelay; if (Global.shiftState && Launcher->Event2 != nullptr) commandrelay.post(user_command::queueevent, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &Launcher->Event2->name()); else if (Launcher->Event1) @@ -1031,7 +1031,7 @@ basic_region::basic_region() { basic_region::~basic_region() { - for( auto *section : m_sections ) { if( section != nullptr ) { delete section; } } + for (const auto *section : m_sections ) { if( section != nullptr ) { delete section; } } } // potentially activates event handler with the same name as provided node, and within handler activation range @@ -1110,8 +1110,8 @@ basic_region::is_scene( std::string const &Scenariofile ) const { // file type and version check std::ifstream input( filename, std::ios::binary ); - uint32_t headermain{ sn_utils::ld_uint32( input ) }; - uint32_t headertype{ sn_utils::ld_uint32( input ) }; + const uint32_t headermain{ sn_utils::ld_uint32( input ) }; + const uint32_t headertype{ sn_utils::ld_uint32( input ) }; if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { // wrong file type @@ -1143,7 +1143,7 @@ basic_region::serialize( std::string const &Scenariofile ) const { // sections // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range std::uint32_t sectioncount { 0 }; - for( auto *section : m_sections ) { + for (const auto *section : m_sections ) { if( section != nullptr ) { ++sectioncount; } @@ -1151,7 +1151,7 @@ basic_region::serialize( std::string const &Scenariofile ) const { // section count, followed by section data sn_utils::ls_uint32( output, sectioncount ); std::uint32_t sectionindex { 0 }; - for( auto *section : m_sections ) { + for (const auto *section : m_sections ) { // section data: section index, followed by length of section data, followed by section data if( section != nullptr ) { sn_utils::ls_uint32( output, sectionindex ); @@ -1181,8 +1181,8 @@ basic_region::deserialize( std::string const &Scenariofile ) { // file type and version check std::ifstream input( filename, std::ios::binary ); - uint32_t headermain { sn_utils::ld_uint32( input ) }; - uint32_t headertype { sn_utils::ld_uint32( input ) }; + const uint32_t headermain { sn_utils::ld_uint32( input ) }; + const uint32_t headertype { sn_utils::ld_uint32( input ) }; if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { // wrong file type @@ -1210,7 +1210,7 @@ basic_region::deserialize( std::string const &Scenariofile ) { void basic_region::export_as_text( std::ostream &Output ) const { - for( auto *section : m_sections ) { + for (const auto *section : m_sections ) { // text format export dumps only relevant basic objects from non-empty sections if( section != nullptr ) { section->export_as_text( Output ); @@ -1734,7 +1734,7 @@ void basic_region::update_poi_geometry() vertices.push_back(std::move(sem->vertex())); if (!m_map_poipoints) { - gfx::geometrybank_handle poibank = GfxRenderer->Create_Bank(); + const gfx::geometrybank_handle poibank = GfxRenderer->Create_Bank(); m_map_poipoints = GfxRenderer->Insert(vertices, userdata, poibank, GL_POINTS); } else { diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index e9ffd2fe..c57cefe2 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -60,7 +60,7 @@ void shape_node::shapenode_data::serialize( std::ostream &Output ) const { // bounding area area.serialize( Output ); - bool has_userdata = !userdata.empty(); + const bool has_userdata = !userdata.empty(); // visibility sn_utils::ls_float64( Output, rangesquared_min ); sn_utils::ls_float64( Output, rangesquared_max ); @@ -98,7 +98,7 @@ shape_node::shapenode_data::deserialize( std::istream &Input ) { visible = sn_utils::d_bool( Input ); // material translucent = sn_utils::d_bool( Input ); - bool has_userdata = sn_utils::d_bool( Input ); + const bool has_userdata = sn_utils::d_bool( Input ); auto const materialname { sn_utils::d_str( Input ) }; if( false == materialname.empty() ) { material = GfxRenderer->Fetch_Material( materialname ); diff --git a/scene/scenenodegroups.cpp b/scene/scenenodegroups.cpp index be98ebad..662cf672 100644 --- a/scene/scenenodegroups.cpp +++ b/scene/scenenodegroups.cpp @@ -41,7 +41,7 @@ node_groups::close() if( true == m_activegroup.empty() || m_activegroup.top() != closinggroup ) { - auto lookup { m_groupmap.find( closinggroup ) }; + const auto lookup { m_groupmap.find( closinggroup ) }; if( lookup != m_groupmap.end() && lookup->second.nodes.size() + lookup->second.events.size() <= 1 ) { @@ -62,7 +62,7 @@ bool node_groups::assign_cross_switch(map::track_switch& sw, std::string &sw_nam if (!sw.action[idx]) return false; - auto multi = dynamic_cast(sw.action[idx]); + const auto multi = dynamic_cast(sw.action[idx]); if (!multi) return false; @@ -73,13 +73,13 @@ bool node_groups::assign_cross_switch(map::track_switch& sw, std::string &sw_nam if (it->size() > 4) continue; - int pos_a = it->find_last_of('a'); - int pos_b = it->find_last_of('b'); - int pos_c = it->find_last_of('c'); - int pos_d = it->find_last_of('d'); + const int pos_a = it->find_last_of('a'); + const int pos_b = it->find_last_of('b'); + const int pos_c = it->find_last_of('c'); + const int pos_d = it->find_last_of('d'); - int pos_0 = it->find_last_of('0'); - int pos_1 = it->find_last_of('1'); + const int pos_0 = it->find_last_of('0'); + const int pos_1 = it->find_last_of('1'); int pos; @@ -135,7 +135,7 @@ node_groups::update_map() } if (Global.map_manualswitchcontrol) { - if (auto track = dynamic_cast(node)) { + if (const auto track = dynamic_cast(node)) { if (track->eType != tt_Switch) continue; @@ -161,7 +161,7 @@ node_groups::update_map() if (sw_name.size() <= 2) continue; - char lastc = sw_name.back(); + const char lastc = sw_name.back(); sw_name.pop_back(); if (sw_name.back() == '_') sw_name.pop_back(); @@ -184,7 +184,7 @@ node_groups::update_map() continue; last_switch->track[lastc - 'a'] = track; - for (auto trk : last_switch->track) + for (const auto trk : last_switch->track) if (!trk) goto skip_e; @@ -203,7 +203,7 @@ node_groups::update_map() last_switch_map.erase(sw_name); } } else { - if (auto launcher = dynamic_cast(node)) { + if (const auto launcher = dynamic_cast(node)) { if (!launcher || !launcher->Event1 || !launcher->Event2) continue; @@ -287,7 +287,7 @@ node_groups::export_as_text( std::ostream &Output, bool Dirty ) const { node->export_as_text( Output ); } - for( auto *event : group.second.events ) { + for (const auto *event : group.second.events ) { if (Dirty) continue; diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp index 71e6549c..2a7bd5f7 100644 --- a/scene/sn_utils.cpp +++ b/scene/sn_utils.cpp @@ -195,7 +195,7 @@ void sn_utils::ls_int64(std::ostream &s, int64_t v) void sn_utils::ls_float32(std::ostream &s, float t) { - uint32_t v = reinterpret_cast(t); + const uint32_t v = reinterpret_cast(t); uint8_t buf[4]; buf[0] = v; buf[1] = v >> 8; @@ -206,7 +206,7 @@ void sn_utils::ls_float32(std::ostream &s, float t) void sn_utils::ls_float64(std::ostream &s, double t) { - uint64_t v = reinterpret_cast(t); + const uint64_t v = reinterpret_cast(t); uint8_t buf[8]; buf[0] = v; buf[1] = v >> 8; diff --git a/scripting/PyInt.cpp b/scripting/PyInt.cpp index 1474a584..158a3328 100644 --- a/scripting/PyInt.cpp +++ b/scripting/PyInt.cpp @@ -169,7 +169,7 @@ void render_task::run() auto *commandsPO = PyObject_CallMethod(m_renderer, const_cast("getCommands"), nullptr); if (commandsPO != nullptr) { - std::vector commands = python_external_utils::PyObjectToStringArray(commandsPO); + const std::vector commands = python_external_utils::PyObjectToStringArray(commandsPO); Py_DECREF(commandsPO); // we perform any actions ONLY when there are any commands in buffer @@ -180,7 +180,7 @@ void render_task::run() std::string baseCmd; int p1 = 0, p2 = 0; - size_t pos1 = cmd.find(';'); + const size_t pos1 = cmd.find(';'); if (pos1 == std::string::npos) { baseCmd = cmd; @@ -189,7 +189,7 @@ void render_task::run() { baseCmd = cmd.substr(0, pos1); - size_t pos2 = cmd.find(';', pos1 + 1); + const size_t pos2 = cmd.find(';', pos1 + 1); if (pos2 == std::string::npos) { p1 = std::stoi(cmd.substr(pos1 + 1)); @@ -346,7 +346,7 @@ void python_taskqueue::exit() // which the previous code did not do (cancel() is a no-op stub). { std::lock_guard lock(m_tasks.mutex); - for (auto &task : m_tasks.data) + for (const auto &task : m_tasks.data) { task->cancel(); } @@ -359,7 +359,7 @@ void python_taskqueue::exit() // reclaim cached python objects while the interpreter is still alive, // so no Py_DECREF lands on a finalized interpreter during later teardown acquire_lock(); - for (auto &entry : m_renderers) + for (const auto &entry : m_renderers) { Py_XDECREF(entry.second); } @@ -593,7 +593,7 @@ void python_taskqueue::update() { std::lock_guard lock(m_uploadtasks.mutex); - for (auto &task : m_uploadtasks.data) + for (const auto &task : m_uploadtasks.data) task->upload(); m_uploadtasks.data.clear(); @@ -674,7 +674,7 @@ std::vector python_external_utils::PyObjectToStringArray(PyObject * return emptyIfError; } - Py_ssize_t size = PySequence_Size(pyList); + const Py_ssize_t size = PySequence_Size(pyList); for (Py_ssize_t i = 0; i < size; ++i) { PyObject *item = PySequence_GetItem(pyList, i); // Increments reference count diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 58cdd41a..4e67bb87 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -57,14 +57,14 @@ std::string lua::get_error() const void lua::interpret(const std::string& file) const { if (luaL_dofile(state, file.c_str())) { - std::string str = lua_tostring(state, -1); + const std::string str = lua_tostring(state, -1); ErrorLog("lua: Runtime error: " + str, logtype::lua); } } int lua::atpanic(lua_State *s) { - std::string err = lua_tostring(s, -1); + const std::string err = lua_tostring(s, -1); ErrorLog("lua: Runtime error: " + err, logtype::lua); return 0; } @@ -124,11 +124,11 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) int lua::scriptapi_event_create(lua_State *L) { - std::string name = lua_tostring(L, 1); - double delay = lua_tonumber(L, 2); - double randomdelay = lua_tonumber(L, 3); + const std::string name = lua_tostring(L, 1); + const double delay = lua_tonumber(L, 2); + const double randomdelay = lua_tonumber(L, 3); lua_pushvalue(L, 4); - int funcRef = luaL_ref(L, LUA_REGISTRYINDEX); + const int funcRef = luaL_ref(L, LUA_REGISTRYINDEX); basic_event *event = new lua_event(L, funcRef); event->m_name = name; @@ -144,7 +144,7 @@ int lua::scriptapi_event_create(lua_State *L) int lua::scriptapi_event_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + const std::string name = lua_tostring(L, 1); basic_event *event = simulation::Events.FindEvent(name); if (event) { @@ -157,15 +157,15 @@ int lua::scriptapi_event_find(lua_State *L) int lua::scriptapi_event_exists(lua_State *L) { - std::string name = lua_tostring(L, 1); - basic_event *event = simulation::Events.FindEvent(name); + const std::string name = lua_tostring(L, 1); + const basic_event *event = simulation::Events.FindEvent(name); lua_pushboolean(L, event != nullptr); return 1; } int lua::scriptapi_event_getname(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); + const auto *event = static_cast(lua_touserdata(L, 1)); if (event) { lua_pushstring(L, event->m_name.c_str()); @@ -177,8 +177,8 @@ int lua::scriptapi_event_getname(lua_State *L) int lua::scriptapi_event_dispatch(lua_State *L) { auto *event = static_cast(lua_touserdata(L, 1)); - auto *activator = static_cast(lua_touserdata(L, 2)); - double delay = lua_tonumber(L, 3); + const auto *activator = static_cast(lua_touserdata(L, 2)); + const double delay = lua_tonumber(L, 3); if (event) simulation::Events.AddToQuery(event, activator, delay); return 0; @@ -186,9 +186,9 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { - std::string name = lua_tostring(L, 1); - auto *activator = static_cast(lua_touserdata(L, 2)); - double delay = lua_tonumber(L, 3); + const std::string name = lua_tostring(L, 1); + const auto *activator = static_cast(lua_touserdata(L, 2)); + const double delay = lua_tonumber(L, 3); basic_event *event = simulation::Events.FindEvent(name); if (event) simulation::Events.AddToQuery(event, activator, delay); @@ -199,7 +199,7 @@ int lua::scriptapi_event_dispatch_n(lua_State *L) int lua::scriptapi_track_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + const std::string name = lua_tostring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -223,7 +223,7 @@ int lua::scriptapi_track_isoccupied(lua_State *L) int lua::scriptapi_track_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + const std::string name = lua_tostring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -236,7 +236,7 @@ int lua::scriptapi_track_isoccupied_n(lua_State *L) int lua::scriptapi_isolated_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + const std::string name = lua_tostring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -260,7 +260,7 @@ int lua::scriptapi_isolated_isoccupied(lua_State *L) int lua::scriptapi_isolated_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + const std::string name = lua_tostring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -273,7 +273,7 @@ int lua::scriptapi_isolated_isoccupied_n(lua_State *L) int lua::scriptapi_train_getname(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + const auto *dyn = static_cast(lua_touserdata(L, 1)); if (dyn && dyn->Mechanik) { lua_pushstring(L, dyn->Mechanik->TrainName().c_str()); @@ -284,11 +284,11 @@ int lua::scriptapi_train_getname(lua_State *L) int lua::scriptapi_dynobj_putvalues(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + const auto *dyn = static_cast(lua_touserdata(L, 1)); auto [str, num1, num2] = get_memcell_values(L, 2); if (!dyn) return 0; - TLocation loc{}; + const TLocation loc{}; if (dyn->Mechanik) dyn->Mechanik->PutCommand(str, num1, num2, loc); else @@ -298,7 +298,7 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) int lua::scriptapi_memcell_find(lua_State *L) { - std::string str = lua_tostring(L, 1); + const std::string str = lua_tostring(L, 1); TMemCell *mc = simulation::Memory.find(str); if (mc) { @@ -311,15 +311,15 @@ int lua::scriptapi_memcell_find(lua_State *L) int lua::scriptapi_memcell_read(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + const auto *mc = static_cast(lua_touserdata(L, 1)); push_memcell_values(L, mc); return 1; } int lua::scriptapi_memcell_read_n(lua_State *L) { - std::string str = lua_tostring(L, 1); - TMemCell *mc = simulation::Memory.find(str); + const std::string str = lua_tostring(L, 1); + const TMemCell *mc = simulation::Memory.find(str); push_memcell_values(L, mc); if (!mc) ErrorLog("lua: missing memcell: " + str); @@ -338,7 +338,7 @@ int lua::scriptapi_memcell_update(lua_State *L) int lua::scriptapi_memcell_update_n(lua_State *L) { - std::string mstr = lua_tostring(L, 1); + const std::string mstr = lua_tostring(L, 1); auto [str, num1, num2] = get_memcell_values(L, 2); TMemCell *mc = simulation::Memory.find(mstr); if (mc) @@ -351,22 +351,22 @@ int lua::scriptapi_memcell_update_n(lua_State *L) int lua::scriptapi_random(lua_State *L) { - double a = lua_tonumber(L, 1); - double b = lua_tonumber(L, 2); + const double a = lua_tonumber(L, 1); + const double b = lua_tonumber(L, 2); lua_pushnumber(L, Random(a, b)); return 1; } int lua::scriptapi_writelog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + const std::string txt = lua_tostring(L, 1); WriteLog("lua: log: " + txt, logtype::lua); return 0; } int lua::scriptapi_writeerrorlog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + const std::string txt = lua_tostring(L, 1); ErrorLog("lua: log: " + txt, logtype::lua); return 0; } diff --git a/scripting/pythonscreenviewer.cpp b/scripting/pythonscreenviewer.cpp index 4d1c8048..d6caefb2 100644 --- a/scripting/pythonscreenviewer.cpp +++ b/scripting/pythonscreenviewer.cpp @@ -7,25 +7,25 @@ void texture_window_resize(GLFWwindow *win, int w, int h) { - auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + const auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_window_size(win, w, h); } void texture_window_fb_resize(GLFWwindow *win, int w, int h) { - auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + const auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_window_fb_size(win, w, h); } void texture_window_mouse_button(GLFWwindow *win, int button, int action, int mods) { - auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + const auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_click(win, button, action); } void texture_window_cursor_pos(GLFWwindow *win, double x, double y) { - auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); + const auto texwindow = (python_screen_viewer*)glfwGetWindowUserPointer(win); texwindow->notify_cursor_pos(win, x, y); } @@ -187,7 +187,7 @@ void python_screen_viewer::threadfunc() void python_screen_viewer::notify_window_fb_size(GLFWwindow *window, int w, int h) { - for (auto &conf : m_windows) { + for (const auto &conf : m_windows) { if (conf->window == window) { conf->fb_size.x = w; conf->fb_size.y = h; @@ -198,7 +198,7 @@ void python_screen_viewer::notify_window_fb_size(GLFWwindow *window, int w, int void python_screen_viewer::notify_window_size(GLFWwindow *window, int w, int h) { - for (auto &conf : m_windows) { + for (const auto &conf : m_windows) { if (conf->window == window) { conf->window_size.x = w; conf->window_size.y = h; @@ -209,7 +209,7 @@ void python_screen_viewer::notify_window_size(GLFWwindow *window, int w, int h) void python_screen_viewer::notify_cursor_pos(GLFWwindow *window, double x, double y) { - for (auto &conf : m_windows) { + for (const auto &conf : m_windows) { if (conf->window == window) { conf->cursor_pos.x = x; conf->cursor_pos.y = y; diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 7fa6b5a1..10c862cb 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -127,7 +127,7 @@ state_serializer::deserialize_continue(std::shared_ptr state scene::scratch_data &Scratchpad = state->scratchpad; // deserialize content from the provided input - auto timelast { std::chrono::steady_clock::now() }; + const auto timelast { std::chrono::steady_clock::now() }; auto token { Input.getToken() }; while( false == token.empty() ) { @@ -390,7 +390,7 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc } void state_serializer::init_time() { - auto &time = simulation::Time.data(); + const auto &time = simulation::Time.data(); if( true == Global.ScenarioTimeCurrent ) { // calculate time shift required to match scenario time with local clock auto const *localtime = std::gmtime( &Global.starting_timestamp ); @@ -758,9 +758,9 @@ state_serializer::deserialize_time( cParser &Input, scene::scratch_data &Scratch void state_serializer::deserialize_trainset( cParser &Input, scene::scratch_data &Scratchpad ) { - int line = Input.LineMain(); + const int line = Input.LineMain(); if (line != -1) { - auto it = Global.trainset_overrides.find(line); + const auto it = Global.trainset_overrides.find(line); if (it != Global.trainset_overrides.end()) { skip_until(Input, "endtrainset"); Input.injectString(it->second); diff --git a/simulation/simulationtime.cpp b/simulation/simulationtime.cpp index 52886709..2620f281 100644 --- a/simulation/simulationtime.cpp +++ b/simulation/simulationtime.cpp @@ -21,7 +21,7 @@ scenario_time Time; void scenario_time::init(std::time_t timestamp) { - char monthdaycounts[ 2 ][ 13 ] = { + const char monthdaycounts[ 2 ][ 13 ] = { { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; ::memcpy( m_monthdaycounts, monthdaycounts, sizeof( monthdaycounts ) ); @@ -32,7 +32,7 @@ scenario_time::init(std::time_t timestamp) { auto const requestedminute { requestedtime % 60 }; // cache requested elements, if any - std::tm *tms = std::gmtime(×tamp); + const std::tm *tms = std::gmtime(×tamp); m_time.wYear = tms->tm_year + 1900; m_time.wMonth = tms->tm_mon + 1; m_time.wDayOfWeek = tms->tm_wday; @@ -147,7 +147,7 @@ scenario_time::year_day( int Day, const int Month, const int Year ) const { void scenario_time::daymonth( WORD &Day, WORD &Month, WORD const Year, WORD const Yearday ) { - WORD daytab[ 2 ][ 13 ] = { + const WORD daytab[ 2 ][ 13 ] = { { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } }; @@ -165,12 +165,12 @@ scenario_time::daymonth( WORD &Day, WORD &Month, WORD const Year, WORD const Yea int scenario_time::julian_day() const { - int yy = ( m_time.wYear < 0 ? m_time.wYear + 1 : m_time.wYear ) - std::floor( ( 12 - m_time.wMonth ) / 10.f ); + const int yy = ( m_time.wYear < 0 ? m_time.wYear + 1 : m_time.wYear ) - std::floor( ( 12 - m_time.wMonth ) / 10.f ); int mm = m_time.wMonth + 9; if( mm >= 12 ) { mm -= 12; } - int K1 = std::floor( 365.25 * ( yy + 4712 ) ); - int K2 = std::floor( 30.6 * mm + 0.5 ); + const int K1 = std::floor( 365.25 * ( yy + 4712 ) ); + const int K2 = std::floor( 30.6 * mm + 0.5 ); // for dates in Julian calendar int JD = K1 + K2 + m_time.wDay + 59; @@ -178,7 +178,7 @@ scenario_time::julian_day() const { const int gregorianswitchday = 2299160; if( JD > gregorianswitchday ) { - int K3 = std::floor( std::floor( yy * 0.01 + 49 ) * 0.75 ) - 38; + const int K3 = std::floor( std::floor( yy * 0.01 + 49 ) * 0.75 ) - 38; JD -= K3; } @@ -212,7 +212,7 @@ int scenario_time::day_of_month( int const Week, int const Weekday, int const Month, int const Year ) const { int day = 0; - int dayoffset = weekdays( day_of_week( 1, Month, Year ), Weekday ); + const int dayoffset = weekdays( day_of_week( 1, Month, Year ), Weekday ); day = ( Week - 1 ) * 7 + 1 + dayoffset; diff --git a/stb/stb_image.h b/stb/stb_image.h index a632d543..ce6c72f0 100644 --- a/stb/stb_image.h +++ b/stb/stb_image.h @@ -752,7 +752,7 @@ static int stbi__cpuid3(void) #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) static int stbi__sse2_available(void) { - int info3 = stbi__cpuid3(); + const int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } #endif @@ -1189,7 +1189,7 @@ static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int re static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) { int i; - int img_len = w * h * channels; + const int img_len = w * h * channels; stbi_uc *reduced; reduced = (stbi_uc *) stbi__malloc(img_len); @@ -1205,7 +1205,7 @@ static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int chan static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) { int i; - int img_len = w * h * channels; + const int img_len = w * h * channels; stbi__uint16 *enlarged; enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); @@ -1221,7 +1221,7 @@ static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int chan static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) { int row; - size_t bytes_per_row = (size_t)w * bytes_per_pixel; + const size_t bytes_per_row = (size_t)w * bytes_per_pixel; stbi_uc temp[2048]; stbi_uc *bytes = (stbi_uc *)image; @@ -1231,7 +1231,7 @@ static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) // swap row0 with row1 size_t bytes_left = bytes_per_row; while (bytes_left) { - size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + const size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); memcpy(temp, row0, bytes_copy); memcpy(row0, row1, bytes_copy); memcpy(row1, temp, bytes_copy); @@ -1246,7 +1246,7 @@ static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) { int slice; - int slice_size = w * h * bytes_per_pixel; + const int slice_size = w * h * bytes_per_pixel; stbi_uc *bytes = (stbi_uc *)image; for (slice = 0; slice < z; ++slice) { @@ -1275,7 +1275,7 @@ static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, // @TODO: move stbi__convert_format to here if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; + const int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); } @@ -1302,7 +1302,7 @@ static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; + const int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); } @@ -1313,7 +1313,7 @@ static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { - int channels = req_comp ? req_comp : *comp; + const int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); } } @@ -1541,7 +1541,7 @@ STBIDEF int stbi_is_hdr (char const *filename) STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR - long pos = ftell(f); + const long pos = ftell(f); int res; stbi__context s; stbi__start_file(&s,f); @@ -1595,7 +1595,7 @@ enum static void stbi__refill_buffer(stbi__context *s) { - int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + const int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case @@ -1648,7 +1648,7 @@ static void stbi__skip(stbi__context *s, int n) return; } if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); + const int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { s->img_buffer = s->img_buffer_end; (s->io.skip)(s->io_user_data, n - blen); @@ -1665,7 +1665,7 @@ static void stbi__skip(stbi__context *s, int n) static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); + const int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { int res, count; @@ -1692,7 +1692,7 @@ static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) #else static int stbi__get16be(stbi__context *s) { - int z = stbi__get8(s); + const int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } #endif @@ -1702,7 +1702,7 @@ static int stbi__get16be(stbi__context *s) #else static stbi__uint32 stbi__get32be(stbi__context *s) { - stbi__uint32 z = stbi__get16be(s); + const stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } #endif @@ -1712,7 +1712,7 @@ static stbi__uint32 stbi__get32be(stbi__context *s) #else static int stbi__get16le(stbi__context *s) { - int z = stbi__get8(s); + const int z = stbi__get8(s); return z + (stbi__get8(s) << 8); } #endif @@ -2032,10 +2032,10 @@ static int stbi__build_huffman(stbi__huffman *h, int *count) // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i=0; i < k; ++i) { - int s = h->size[i]; + const int s = h->size[i]; if (s <= FAST_BITS) { - int c = h->code[i] << (FAST_BITS-s); - int m = 1 << (FAST_BITS-s); + const int c = h->code[i] << (FAST_BITS-s); + const int m = 1 << (FAST_BITS-s); for (j=0; j < m; ++j) { h->fast[c+j] = (stbi_uc) i; } @@ -2050,18 +2050,18 @@ static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) { int i; for (i=0; i < (1 << FAST_BITS); ++i) { - stbi_uc fast = h->fast[i]; + const stbi_uc fast = h->fast[i]; fast_ac[i] = 0; if (fast < 255) { - int rs = h->values[fast]; - int run = (rs >> 4) & 15; - int magbits = rs & 15; - int len = h->size[fast]; + const int rs = h->values[fast]; + const int run = (rs >> 4) & 15; + const int magbits = rs & 15; + const int len = h->size[fast]; if (magbits && len + magbits <= FAST_BITS) { // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); - int m = 1 << (magbits - 1); + const int m = 1 << (magbits - 1); if (k < m) k += (~0U << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) @@ -2074,7 +2074,7 @@ static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { - unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + const unsigned int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes @@ -2105,7 +2105,7 @@ stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); k = h->fast[c]; if (k < 255) { - int s = h->size[k]; + const int s = h->size[k]; if (s > j->code_bits) return -1; j->code_buffer <<= s; @@ -2243,7 +2243,7 @@ static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * dequant[zig]); } else { - int rs = stbi__jpeg_huff_decode(j, hac); + const int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; @@ -2297,7 +2297,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->succ_high == 0) { - int shift = j->succ_low; + const int shift = j->succ_low; if (j->eob_run) { --j->eob_run; @@ -2320,7 +2320,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * (1 << shift)); } else { - int rs = stbi__jpeg_huff_decode(j, hac); + const int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; @@ -2343,7 +2343,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ } else { // refinement scan for these AC coefficients - short bit = (short) (1 << j->succ_low); + const short bit = (short) (1 << j->succ_low); if (j->eob_run) { --j->eob_run; @@ -2362,7 +2362,7 @@ static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__ k = j->spec_start; do { int r,s; - int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + const int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; @@ -2952,16 +2952,16 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg *z) if (z->scan_n == 1) { int i,j; STBI_SIMD_ALIGN(short, data[64]); - int n = z->order[0]; + const int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; + const int w = (z->img_comp[n].x+7) >> 3; + const int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { - int ha = z->img_comp[n].ha; + const int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); // every data block is an MCU, so countdown the restart interval @@ -2982,14 +2982,14 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg *z) for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; + const int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x)*8; - int y2 = (j*z->img_comp[n].v + y)*8; - int ha = z->img_comp[n].ha; + const int x2 = (i*z->img_comp[n].h + x)*8; + const int y2 = (j*z->img_comp[n].v + y)*8; + const int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); } @@ -3009,13 +3009,13 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg *z) } else { if (z->scan_n == 1) { int i,j; - int n = z->order[0]; + const int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; + const int w = (z->img_comp[n].x+7) >> 3; + const int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); @@ -3023,7 +3023,7 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg *z) if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } else { - int ha = z->img_comp[n].ha; + const int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) return 0; } @@ -3042,13 +3042,13 @@ static int stbi__parse_entropy_coded_data(stbi__jpeg *z) for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; + const int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x); - int y2 = (j*z->img_comp[n].v + y); + const int x2 = (i*z->img_comp[n].h + x); + const int y2 = (j*z->img_comp[n].v + y); short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; @@ -3082,8 +3082,8 @@ static void stbi__jpeg_finish(stbi__jpeg *z) // dequantize and idct the data int i,j,n; for (n=0; n < z->s->img_n; ++n) { - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; + const int w = (z->img_comp[n].x+7) >> 3; + const int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); @@ -3110,7 +3110,7 @@ static int stbi__process_marker(stbi__jpeg *z, int m) case 0xDB: // DQT - define quantization table L = stbi__get16be(z->s)-2; while (L > 0) { - int q = stbi__get8(z->s); + const int q = stbi__get8(z->s); int p = q >> 4, sixteen = (p != 0); int t = q & 15,i; if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); @@ -3127,9 +3127,9 @@ static int stbi__process_marker(stbi__jpeg *z, int m) while (L > 0) { stbi_uc *v; int sizes[16],i,n=0; - int q = stbi__get8(z->s); - int tc = q >> 4; - int th = q & 15; + const int q = stbi__get8(z->s); + const int tc = q >> 4; + const int th = q & 15; if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); for (i=0; i < 16; ++i) { sizes[i] = stbi__get8(z->s); @@ -3202,13 +3202,13 @@ static int stbi__process_marker(stbi__jpeg *z, int m) static int stbi__process_scan_header(stbi__jpeg *z) { int i; - int Ls = stbi__get16be(z->s); + const int Ls = stbi__get16be(z->s); z->scan_n = stbi__get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); for (i=0; i < z->scan_n; ++i) { int id = stbi__get8(z->s), which; - int q = stbi__get8(z->s); + const int q = stbi__get8(z->s); for (which = 0; which < z->s->img_n; ++which) if (z->img_comp[which].id == id) break; @@ -3430,8 +3430,8 @@ static int stbi__decode_jpeg_image(stbi__jpeg *j) if (STBI__RESTART(m)) m = stbi__get_marker(j); } else if (stbi__DNL(m)) { - int Ld = stbi__get16be(j->s); - stbi__uint32 NL = stbi__get16be(j->s); + const int Ld = stbi__get16be(j->s); + const stbi__uint32 NL = stbi__get16be(j->s); if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); m = stbi__get_marker(j); @@ -3475,7 +3475,7 @@ static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc { // need to generate two samples horizontally for every one in input int i; - stbi_uc *input = in_near; + const stbi_uc *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation @@ -3486,7 +3486,7 @@ static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc out[0] = input[0]; out[1] = stbi__div4(input[0]*3 + input[1] + 2); for (i=1; i < w-1; ++i) { - int n = 3*input[i]+2; + const int n = 3*input[i]+2; out[i*2+0] = stbi__div4(n+input[i-1]); out[i*2+1] = stbi__div4(n+input[i+1]); } @@ -3660,10 +3660,10 @@ static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc { int i; for (i=0; i < count; ++i) { - int y_fixed = (y[i] << 20) + (1<<19); // rounding + const int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; + const int cr = pcr[i] - 128; + const int cb = pcb[i] - 128; r = y_fixed + cr* stbi__float2fixed(1.40200f); g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* stbi__float2fixed(1.77200f); @@ -3857,7 +3857,7 @@ typedef struct // fast 0..255 * 0..255 => 0..255 rounded multiplication static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) { - unsigned int t = x*y + 128; + const unsigned int t = x*y + 128; return (stbi_uc) ((t + (t >>8)) >> 8); } @@ -3926,7 +3926,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp stbi_uc *out = output + n * z->s->img_x * j; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; - int y_bot = r->ystep >= (r->vs >> 1); + const int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, @@ -3939,7 +3939,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp } } if (n >= 3) { - stbi_uc *y = coutput[0]; + const stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { if (is_rgb) { for (i=0; i < z->s->img_x; ++i) { @@ -3955,7 +3955,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp } else if (z->s->img_n == 4) { if (z->app14_color_transform == 0) { // CMYK for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; + const stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(coutput[0][i], m); out[1] = stbi__blinn_8x8(coutput[1][i], m); out[2] = stbi__blinn_8x8(coutput[2][i], m); @@ -3965,7 +3965,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp } else if (z->app14_color_transform == 2) { // YCCK z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; + const stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(255 - out[0], m); out[1] = stbi__blinn_8x8(255 - out[1], m); out[2] = stbi__blinn_8x8(255 - out[2], m); @@ -3993,10 +3993,10 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp } } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); - stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); - stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + const stbi_uc m = coutput[3][i]; + const stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + const stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + const stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); out[0] = stbi__compute_y(r, g, b); out[1] = 255; out += n; @@ -4008,7 +4008,7 @@ static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp out += n; } } else { - stbi_uc *y = coutput[0]; + const stbi_uc *y = coutput[0]; if (n == 1) for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; else @@ -4148,10 +4148,10 @@ static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int } z->maxcode[16] = 0x10000; // sentinel for (i=0; i < num; ++i) { - int s = sizelist[i]; + const int s = sizelist[i]; if (s) { - int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; - stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + const int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + const stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); z->size [c] = (stbi_uc ) s; z->value[c] = (stbi__uint16) i; if (s <= STBI__ZFAST_BITS) { @@ -4346,7 +4346,7 @@ static int stbi__parse_huffman_block(stbi__zbuf *a) } p = (stbi_uc *) (zout - dist); if (dist == 1) { // run of one byte; common in images. - stbi_uc v = *p; + const stbi_uc v = *p; if (len) { do *zout++ = v; while (--len); } } else { if (len) { do *zout++ = *p++; while (--len); } @@ -4363,14 +4363,14 @@ static int stbi__compute_huffman_codes(stbi__zbuf *a) stbi_uc codelength_sizes[19]; int i,n; - int hlit = stbi__zreceive(a,5) + 257; - int hdist = stbi__zreceive(a,5) + 1; - int hclen = stbi__zreceive(a,4) + 4; - int ntot = hlit + hdist; + const int hlit = stbi__zreceive(a,5) + 257; + const int hdist = stbi__zreceive(a,5) + 1; + const int hclen = stbi__zreceive(a,4) + 4; + const int ntot = hlit + hdist; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { - int s = stbi__zreceive(a,3); + const int s = stbi__zreceive(a,3); codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; } if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; @@ -4436,10 +4436,10 @@ static int stbi__parse_uncompressed_block(stbi__zbuf *a) static int stbi__parse_zlib_header(stbi__zbuf *a) { - int cmf = stbi__zget8(a); - int cm = cmf & 15; + const int cmf = stbi__zget8(a); + const int cm = cmf & 15; /* int cinfo = cmf >> 4; */ - int flg = stbi__zget8(a); + const int flg = stbi__zget8(a); if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png @@ -4658,11 +4658,11 @@ static int stbi__paeth(int a, int b, int c) // This formulation looks very different from the reference in the PNG spec, but is // actually equivalent and has favorable data dependencies and admits straightforward // generation of branch-free code, which helps performance significantly. - int thresh = c*3 - (a + b); - int lo = a < b ? a : b; - int hi = a < b ? b : a; - int t0 = (hi <= thresh) ? lo : c; - int t1 = (thresh <= lo) ? hi : t0; + const int thresh = c*3 - (a + b); + const int lo = a < b ? a : b; + const int hi = a < b ? b : a; + const int t0 = (hi <= thresh) ? lo : c; + const int t1 = (thresh <= lo) ? hi : t0; return t1; } @@ -4694,16 +4694,16 @@ static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__ui // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { - int bytes = (depth == 16 ? 2 : 1); - stbi__context *s = a->s; + const int bytes = (depth == 16 ? 2 : 1); + const stbi__context *s = a->s; stbi__uint32 i,j,stride = x*out_n*bytes; stbi__uint32 img_len, img_width_bytes; stbi_uc *filter_buf; int all_ok = 1; int k; - int img_n = s->img_n; // copy it into a local for later + const int img_n = s->img_n; // copy it into a local for later - int output_bytes = out_n*bytes; + const int output_bytes = out_n*bytes; int filter_bytes = img_n*bytes; int width = x; @@ -4736,9 +4736,9 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r for (j=0; j < y; ++j) { // cur/prior filter buffers alternate stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes; - stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes; + const stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes; stbi_uc *dest = a->out + stride*j; - int nk = width * filter_bytes; + const int nk = width * filter_bytes; int filter = *raw++; // check filter type @@ -4787,11 +4787,11 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r // expand decoded bits in cur to dest, also adding an extra alpha channel if desired if (depth < 8) { - stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range - stbi_uc *in = cur; + const stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + const stbi_uc *in = cur; stbi_uc *out = dest; stbi_uc inb = 0; - stbi__uint32 nsmp = x*img_n; + const stbi__uint32 nsmp = x*img_n; // expand bits to bytes first if (depth == 4) { @@ -4826,7 +4826,7 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r } else if (depth == 16) { // convert the image data from big-endian to platform-native stbi__uint16 *dest16 = (stbi__uint16*)dest; - stbi__uint32 nsmp = x*img_n; + const stbi__uint32 nsmp = x*img_n; if (img_n == out_n) { for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) @@ -4859,8 +4859,8 @@ static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 r static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { - int bytes = (depth == 16 ? 2 : 1); - int out_bytes = out_n * bytes; + const int bytes = (depth == 16 ? 2 : 1); + const int out_bytes = out_n * bytes; stbi_uc *final; int p; if (!interlaced) @@ -4870,24 +4870,24 @@ static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint3 final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); if (!final) return stbi__err("outofmem", "Out of memory"); for (p=0; p < 7; ++p) { - int xorig[] = { 0,4,0,2,0,1,0 }; - int yorig[] = { 0,0,4,0,2,0,1 }; - int xspc[] = { 8,8,4,4,2,2,1 }; - int yspc[] = { 8,8,8,4,4,2,2 }; + const int xorig[] = { 0,4,0,2,0,1,0 }; + const int yorig[] = { 0,0,4,0,2,0,1 }; + const int xspc[] = { 8,8,4,4,2,2,1 }; + const int yspc[] = { 8,8,8,4,4,2,2 }; int i,j,x,y; // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; if (x && y) { - stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + const stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { STBI_FREE(final); return 0; } for (j=0; j < y; ++j) { for (i=0; i < x; ++i) { - int out_y = j*yspc[p]+yorig[p]; - int out_x = i*xspc[p]+xorig[p]; + const int out_y = j*yspc[p]+yorig[p]; + const int out_x = i*xspc[p]+xorig[p]; memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, a->out + (j*x+i)*out_bytes, out_bytes); } @@ -4904,7 +4904,7 @@ static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint3 static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) { - stbi__context *s = z->s; + const stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; @@ -4929,7 +4929,7 @@ static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) { - stbi__context *s = z->s; + const stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi__uint16 *p = (stbi__uint16*) z->out; @@ -4965,7 +4965,7 @@ static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int if (pal_img_n == 3) { for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; + const int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; @@ -4973,7 +4973,7 @@ static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int } } else { for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; + const int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; @@ -5031,13 +5031,13 @@ STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_conve static void stbi__de_iphone(stbi__png *z) { - stbi__context *s = z->s; + const stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; if (s->img_out_n == 3) { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { - stbi_uc t = p[0]; + const stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 3; @@ -5047,10 +5047,10 @@ static void stbi__de_iphone(stbi__png *z) if (stbi__unpremultiply_on_load) { // convert bgr to rgb and unpremultiply for (i=0; i < pixel_count; ++i) { - stbi_uc a = p[3]; - stbi_uc t = p[0]; + const stbi_uc a = p[3]; + const stbi_uc t = p[0]; if (a) { - stbi_uc half = a / 2; + const stbi_uc half = a / 2; p[0] = (p[2] * 255 + half) / a; p[1] = (p[1] * 255 + half) / a; p[2] = ( t * 255 + half) / a; @@ -5063,7 +5063,7 @@ static void stbi__de_iphone(stbi__png *z) } else { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { - stbi_uc t = p[0]; + const stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 4; @@ -5092,7 +5092,7 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (scan == STBI__SCAN_type) return 1; for (;;) { - stbi__pngchunk c = stbi__get_chunk_header(s); + const stbi__pngchunk c = stbi__get_chunk_header(s); switch (c.type) { case STBI__PNG_TYPE('C','g','B','I'): is_iphone = 1; @@ -5179,7 +5179,7 @@ static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { - stbi__uint32 idata_limit_old = idata_limit; + const stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) @@ -5357,7 +5357,7 @@ static int stbi__bmp_test_raw(stbi__context *s) static int stbi__bmp_test(stbi__context *s) { - int r = stbi__bmp_test_raw(s); + const int r = stbi__bmp_test_raw(s); stbi__rewind(s); return r; } @@ -5467,7 +5467,7 @@ static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); info->bpp = stbi__get16le(s); if (hsz != 12) { - int compress = stbi__get32le(s); + const int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel @@ -5848,12 +5848,12 @@ errorEnd: // read 16bit value and convert to 24bit RGB static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) { - stbi__uint16 px = (stbi__uint16)stbi__get16le(s); - stbi__uint16 fiveBitMask = 31; + const stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + const stbi__uint16 fiveBitMask = 31; // we have 3 channels with 5bits each - int r = (px >> 10) & fiveBitMask; - int g = (px >> 5) & fiveBitMask; - int b = px & fiveBitMask; + const int r = (px >> 10) & fiveBitMask; + const int g = (px >> 5) & fiveBitMask; + const int b = px & fiveBitMask; // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later out[0] = (stbi_uc)((r * 255)/31); out[1] = (stbi_uc)((g * 255)/31); @@ -5868,8 +5868,8 @@ static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { // read in the TGA header stuff - int tga_offset = stbi__get8(s); - int tga_indexed = stbi__get8(s); + const int tga_offset = stbi__get8(s); + const int tga_indexed = stbi__get8(s); int tga_image_type = stbi__get8(s); int tga_is_RLE = 0; int tga_palette_start = stbi__get16le(s); @@ -5877,9 +5877,9 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req int tga_palette_bits = stbi__get8(s); int tga_x_origin = stbi__get16le(s); int tga_y_origin = stbi__get16le(s); - int tga_width = stbi__get16le(s); - int tga_height = stbi__get16le(s); - int tga_bits_per_pixel = stbi__get8(s); + const int tga_width = stbi__get16le(s); + const int tga_height = stbi__get16le(s); + const int tga_bits_per_pixel = stbi__get8(s); int tga_comp, tga_rgb16=0; int tga_inverted = stbi__get8(s); // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) @@ -5929,7 +5929,7 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { for (i=0; i < tga_height; ++i) { - int row = tga_inverted ? tga_height -i - 1 : i; + const int row = tga_inverted ? tga_height -i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; stbi__getn(s, tga_row, tga_width * tga_comp); } @@ -5972,7 +5972,7 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req if ( RLE_count == 0 ) { // yep, get the next byte as a RLE command - int RLE_cmd = stbi__get8(s); + const int RLE_cmd = stbi__get8(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; @@ -6029,7 +6029,7 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req int index2 = (tga_height - 1 - j) * tga_width * tga_comp; for (i = tga_width * tga_comp; i > 0; --i) { - unsigned char temp = tga_data[index1]; + const unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; @@ -6050,7 +6050,7 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req unsigned char* tga_pixel = tga_data; for (i=0; i < tga_width * tga_height; ++i) { - unsigned char temp = tga_pixel[0]; + const unsigned char temp = tga_pixel[0]; tga_pixel[0] = tga_pixel[2]; tga_pixel[2] = temp; tga_pixel += tga_comp; @@ -6077,7 +6077,7 @@ static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s) { - int r = (stbi__get32be(s) == 0x38425053); + const int r = (stbi__get32be(s) == 0x38425053); stbi__rewind(s); return r; } @@ -6248,12 +6248,12 @@ static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req // Fill this channel with default data. if (bitdepth == 16 && bpc == 16) { stbi__uint16 *q = ((stbi__uint16 *) out) + channel; - stbi__uint16 val = channel == 3 ? 65535 : 0; + const stbi__uint16 val = channel == 3 ? 65535 : 0; for (i = 0; i < pixelCount; i++, q += 4) *q = val; } else { stbi_uc *p = out+channel; - stbi_uc val = channel == 3 ? 255 : 0; + const stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) *p = val; } @@ -6282,9 +6282,9 @@ static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req for (i=0; i < w*h; ++i) { stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; if (pixel[3] != 0 && pixel[3] != 65535) { - float a = pixel[3] / 65535.0f; - float ra = 1.0f / a; - float inv_a = 65535.0f * (1 - ra); + const float a = pixel[3] / 65535.0f; + const float ra = 1.0f / a; + const float inv_a = 65535.0f * (1 - ra); pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); @@ -6294,9 +6294,9 @@ static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req for (i=0; i < w*h; ++i) { unsigned char *pixel = out + 4*i; if (pixel[3] != 0 && pixel[3] != 255) { - float a = pixel[3] / 255.0f; - float ra = 1.0f / a; - float inv_a = 255.0f * (1 - ra); + const float a = pixel[3] / 255.0f; + const float ra = 1.0f / a; + const float inv_a = 255.0f * (1 - ra); pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); @@ -6416,7 +6416,7 @@ static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *c int packet_idx; for(packet_idx=0; packet_idx < num_packets; ++packet_idx) { - stbi__pic_packet *packet = &packets[packet_idx]; + const stbi__pic_packet *packet = &packets[packet_idx]; stbi_uc *dest = result+y*width*4; switch (packet->type) { @@ -6537,7 +6537,7 @@ static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_c static int stbi__pic_test(stbi__context *s) { - int r = stbi__pic_test_core(s); + const int r = stbi__pic_test_core(s); stbi__rewind(s); return r; } @@ -6586,7 +6586,7 @@ static int stbi__gif_test_raw(stbi__context *s) static int stbi__gif_test(stbi__context *s) { - int r = stbi__gif_test_raw(s); + const int r = stbi__gif_test_raw(s); stbi__rewind(s); return r; } @@ -6723,7 +6723,7 @@ static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) bits |= (stbi__int32) stbi__get8(s) << valid_bits; valid_bits += 8; } else { - stbi__int32 code = bits & codemask; + const stbi__int32 code = bits & codemask; bits >>= codesize; valid_bits -= codesize; // @OPTIMIZE: is there some way we can accelerate the non-clear path? @@ -6837,7 +6837,7 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame for (;;) { - int tag = stbi__get8(s); + const int tag = stbi__get8(s); switch (tag) { case 0x2C: /* Image Descriptor */ { @@ -6905,7 +6905,7 @@ static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, i case 0x21: // Comment Extension. { int len; - int ext = stbi__get8(s); + const int ext = stbi__get8(s); if (ext == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { @@ -6961,7 +6961,7 @@ static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, { if (stbi__gif_test(s)) { int layers = 0; - stbi_uc *u = 0; + const stbi_uc *u = 0; stbi_uc *out = 0; stbi_uc *two_back = 0; stbi__gif g; @@ -7699,7 +7699,7 @@ STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) { int r; stbi__context s; - long pos = ftell(f); + const long pos = ftell(f); stbi__start_file(&s, f); r = stbi__info_main(&s,x,y,comp); fseek(f,pos,SEEK_SET); @@ -7720,7 +7720,7 @@ STBIDEF int stbi_is_16_bit_from_file(FILE *f) { int r; stbi__context s; - long pos = ftell(f); + const long pos = ftell(f); stbi__start_file(&s, f); r = stbi__is_16_main(&s); fseek(f,pos,SEEK_SET); diff --git a/stb/stb_image_write.h b/stb/stb_image_write.h index 95943eb6..47eaffd4 100644 --- a/stb/stb_image_write.h +++ b/stb/stb_image_write.h @@ -353,13 +353,15 @@ static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); s->func(s->context,&x,1); break; } - case '2': { int x = va_arg(v,int); + case '2': { + const int x = va_arg(v,int); unsigned char b[2]; b[0] = STBIW_UCHAR(x); b[1] = STBIW_UCHAR(x>>8); s->func(s->context,b,2); break; } - case '4': { stbiw_uint32 x = va_arg(v,int); + case '4': { + const stbiw_uint32 x = va_arg(v,int); unsigned char b[4]; b[0]=STBIW_UCHAR(x); b[1]=STBIW_UCHAR(x>>8); @@ -490,7 +492,7 @@ static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) { - int pad = (-x*3) & 3; + const int pad = (-x*3) & 3; return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, "11 4 22 4" "4 44 22 444444", 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header @@ -509,7 +511,7 @@ STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_bmp_core(&s, x, y, comp, data); + const int r = stbi_write_bmp_core(&s, x, y, comp, data); stbi__end_write_file(&s); return r; } else @@ -519,9 +521,9 @@ STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) { - int has_alpha = (comp == 2 || comp == 4); - int colorbytes = has_alpha ? comp-1 : comp; - int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 + const int has_alpha = (comp == 2 || comp == 4); + const int colorbytes = has_alpha ? comp-1 : comp; + const int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 if (y < 0 || x < 0) return 0; @@ -579,13 +581,13 @@ static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, v } if (diff) { - unsigned char header = STBIW_UCHAR(len - 1); + const unsigned char header = STBIW_UCHAR(len - 1); stbiw__write1(s, header); for (k = 0; k < len; ++k) { stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); } } else { - unsigned char header = STBIW_UCHAR(len - 129); + const unsigned char header = STBIW_UCHAR(len - 129); stbiw__write1(s, header); stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); } @@ -608,7 +610,7 @@ STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); + const int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); stbi__end_write_file(&s); return r; } else @@ -625,12 +627,12 @@ STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) { int exponent; - float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); + const float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); if (maxcomp < 1e-32f) { rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; } else { - float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; + const float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; rgbe[0] = (unsigned char)(linear[0] * normalize); rgbe[1] = (unsigned char)(linear[1] * normalize); @@ -782,7 +784,7 @@ STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); + const int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); stbi__end_write_file(&s); return r; } else @@ -812,7 +814,7 @@ STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) { - int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; + const int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); STBIW_ASSERT(p); if (p) { @@ -1046,7 +1048,7 @@ static unsigned int stbiw__crc32(unsigned char *buffer, int len) static void stbiw__wpcrc(unsigned char **data, int len) { - unsigned int crc = stbiw__crc32(*data - len - 4, len+4); + const unsigned int crc = stbiw__crc32(*data - len - 4, len+4); stbiw__wp32(*data, crc); } @@ -1063,11 +1065,11 @@ static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int { static int mapping[] = { 0,1,2,3,4 }; static int firstmap[] = { 0,1,0,5,6 }; - int *mymap = (y != 0) ? mapping : firstmap; + const int *mymap = (y != 0) ? mapping : firstmap; int i; - int type = mymap[filter_type]; - unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); - int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; + const int type = mymap[filter_type]; + const unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); + const int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; if (type==0) { memcpy(line_buffer, z, width*n); @@ -1098,8 +1100,8 @@ static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) { int force_filter = stbi_write_force_png_filter; - int ctype[5] = { -1, 0, 4, 2, 6 }; - unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; + const int ctype[5] = { -1, 0, 4, 2, 6 }; + const unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; unsigned char *out,*o, *filt, *zlib; signed char *line_buffer; int j,zlen; @@ -1225,7 +1227,7 @@ static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitC bitCnt += bs[1]; bitBuf |= bs[0] << (24 - bitCnt); while(bitCnt >= 8) { - unsigned char c = (bitBuf >> 16) & 255; + const unsigned char c = (bitBuf >> 16) & 255; stbiw__putc(s, c); if(c == 255) { stbiw__putc(s, 0); @@ -1241,18 +1243,18 @@ static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; float z1, z2, z3, z4, z5, z11, z13; - float tmp0 = d0 + d7; - float tmp7 = d0 - d7; - float tmp1 = d1 + d6; - float tmp6 = d1 - d6; - float tmp2 = d2 + d5; - float tmp5 = d2 - d5; - float tmp3 = d3 + d4; - float tmp4 = d3 - d4; + const float tmp0 = d0 + d7; + const float tmp7 = d0 - d7; + const float tmp1 = d1 + d6; + const float tmp6 = d1 - d6; + const float tmp2 = d2 + d5; + const float tmp5 = d2 - d5; + const float tmp3 = d3 + d4; + const float tmp4 = d3 - d4; // Even part float tmp10 = tmp0 + tmp3; // phase 2 - float tmp13 = tmp0 - tmp3; + const float tmp13 = tmp0 - tmp3; float tmp11 = tmp1 + tmp2; float tmp12 = tmp1 - tmp2; @@ -1342,14 +1344,14 @@ static int stbiw__jpg_processDU(stbi__write_context *s, int *bitBuf, int *bitCnt return DU[0]; } for(i = 1; i <= end0pos; ++i) { - int startpos = i; + const int startpos = i; int nrzeroes; unsigned short bits[2]; for (; DU[i]==0 && i<=end0pos; ++i) { } nrzeroes = i-startpos; if ( nrzeroes >= 16 ) { - int lng = nrzeroes>>4; + const int lng = nrzeroes>>4; int nrmarker; for (nrmarker=1; nrmarker <= lng; ++nrmarker) stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); @@ -1587,7 +1589,7 @@ STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const { stbi__write_context s = { 0 }; if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); + const int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); stbi__end_write_file(&s); return r; } else diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index c8939838..0895007f 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -987,7 +987,7 @@ bool global_settings::ConfigParseHardware(cParser& Parser, const std::string& to if (token == "uartfeature") { Parser.getTokens(1); - std::string firstToken = Parser.peek(); + const std::string firstToken = Parser.peek(); if (firstToken.find('|') != std::string::npos || firstToken == "none" || uartfeatures_map.contains(firstToken)) { diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 554a77b9..bbcfd03e 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -60,7 +60,7 @@ std::string filename_date() { std::string filename_scenery() { - auto extension = Global.SceneryFile.rfind( '.' ); + const auto extension = Global.SceneryFile.rfind( '.' ); if( extension != std::string::npos ) { return Global.SceneryFile.substr( 0, extension ); } @@ -99,7 +99,7 @@ void LogService() { logMutex.lock(); std::string msg = InfoStack.front().first; - bool isError = InfoStack.front().second; + const bool isError = InfoStack.front().second; InfoStack.pop_front(); logMutex.unlock(); diff --git a/utilities/Names.h b/utilities/Names.h index 0533c696..6adc437f 100644 --- a/utilities/Names.h +++ b/utilities/Names.h @@ -44,7 +44,7 @@ public: } void purge (std::string const &Name) { - auto lookup = m_itemmap.find( Name ); + const auto lookup = m_itemmap.find( Name ); if (lookup == m_itemmap.end()) return; delete m_items[lookup->second]; @@ -53,7 +53,7 @@ public: } void detach (std::string const &Name) { - auto lookup = m_itemmap.find( Name ); + const auto lookup = m_itemmap.find( Name ); if (lookup == m_itemmap.end()) return; @@ -63,7 +63,7 @@ public: m_itemmap.erase(lookup); } uint32_t find_id( std::string const &Name) const { - auto lookup = m_itemmap.find( Name ); + const auto lookup = m_itemmap.find( Name ); return lookup != m_itemmap.end() ? lookup->second : -1; } void purge (Type_ *Item) @@ -79,7 +79,7 @@ public: // locates item with specified name. returns pointer to the item, or nullptr Type_ * find( std::string const &Name ) const { - auto lookup = m_itemmap.find( Name ); + const auto lookup = m_itemmap.find( Name ); return lookup != m_itemmap.end() ? m_items[lookup->second] : nullptr; } protected: diff --git a/utilities/Timer.cpp b/utilities/Timer.cpp index 5cc9f93a..29d4e052 100644 --- a/utilities/Timer.cpp +++ b/utilities/Timer.cpp @@ -94,7 +94,7 @@ void UpdateTimers(bool pause) #if __unix__ double fTime = (double)(count / 1000000000); #elif _WIN32_WINNT >= _WIN32_WINNT_VISTA - double fTime = ::GetTickCount64() * 0.001f; // Get current time in seconds + const double fTime = ::GetTickCount64() * 0.001f; // Get current time in seconds #elif _WIN32 double fTime = ::GetTickCount() * 0.001f; // Get current time in seconds #endif diff --git a/utilities/parser.cpp b/utilities/parser.cpp index 7209df01..a088d003 100644 --- a/utilities/parser.cpp +++ b/utilities/parser.cpp @@ -27,7 +27,7 @@ namespace inline std::array makeBreakTable(const char *brk) { std::array arr{}; - for (unsigned char c : std::string_view(brk ? brk : "")) + for (const unsigned char c : std::string_view(brk ? brk : "")) { arr[c] = true; } @@ -535,7 +535,7 @@ int cParser::getProgress() const int cParser::getFullProgress() const { - int progress = getProgress(); + const int progress = getProgress(); if (mIncludeParser) return progress + (100 - progress) * mIncludeParser->getProgress() / 100; else diff --git a/utilities/translation.cpp b/utilities/translation.cpp index 0885ab7c..4ab188a2 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -36,12 +36,12 @@ void locale::init() const std::string& locale::lookup_s(const std::string &msg, bool constant) { if (constant) { - auto it = pointer_cache.find(&msg); + const auto it = pointer_cache.find(&msg); if (it != pointer_cache.end()) return *(const std::string *)it->second; } - auto it = lang_mapping.find(msg); + const auto it = lang_mapping.find(msg); if (it != lang_mapping.end()) { if (constant) pointer_cache.emplace(&msg, &it->second); @@ -56,12 +56,12 @@ const std::string& locale::lookup_s(const std::string &msg, bool constant) const char* locale::lookup_c(const char *msg, bool constant) { if (constant) { - auto it = pointer_cache.find(msg); + const auto it = pointer_cache.find(msg); if (it != pointer_cache.end()) return (const char*)it->second; } - auto it = lang_mapping.find(std::string(msg)); + const auto it = lang_mapping.find(std::string(msg)); if (it != lang_mapping.end()) { if (constant) pointer_cache.emplace(msg, it->second.c_str()); @@ -370,7 +370,7 @@ const std::string& locale::coupling_name(int c) static std::string unknown(STRN("unknown")); - auto it = coupling_names.find(static_cast(c)); + const auto it = coupling_names.find(static_cast(c)); if (it != coupling_names.end()) return lookup_s(it->second); else diff --git a/utilities/uart.cpp b/utilities/uart.cpp index 4ab5dca6..2cb748bc 100644 --- a/utilities/uart.cpp +++ b/utilities/uart.cpp @@ -28,7 +28,7 @@ const char* uart_baudrates_list[] = { "2000000" }; -const size_t uart_baudrates_list_num = sizeof(uart_baudrates_list) / sizeof(uart_baudrates_list[0]); +const size_t uart_baudrates_list_num = std::size(uart_baudrates_list); void uart_status::reset_stats() { packets_sent = 0; diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 156d16cc..ba2c57a6 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -49,7 +49,7 @@ std::string Now() std::strftime(buf, sizeof(buf), "%c", &tm); return std::string(buf); #else - auto now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); auto local = std::chrono::current_zone()->to_local(now); return std::format("{:%c}", local); #endif @@ -242,7 +242,7 @@ std::string to_minutes_str(float const Minutes, bool const Leadingzero, int cons float minutesintegral; auto const minutesfractional{std::modf(Minutes, &minutesintegral)}; auto const width{Width - 1}; - auto minutes = std::string(width - 1, ' ') + (Leadingzero ? std::to_string(100 + minutesintegral).substr(1, 2) : to_string(minutesintegral, 0)); + const auto minutes = std::string(width - 1, ' ') + (Leadingzero ? std::to_string(100 + minutesintegral).substr(1, 2) : to_string(minutesintegral, 0)); return minutes.substr(minutes.size() - width, width) + fractionlabels[static_cast(std::floor(minutesfractional * 10 + 0.1))]; } @@ -338,7 +338,7 @@ std::string Bezogonkow(std::string Input, bool const Underscorestospaces) template <> bool extract_value(bool &Variable, std::string const &Key, std::string const &Input, std::string const &Default) { - auto value = extract_value(Key, Input); + const auto value = extract_value(Key, Input); if (false == value.empty()) { // set the specified variable to retrieved value @@ -381,7 +381,7 @@ std::pair FileExists(std::vector const &N // returns time of last modification for specified file std::time_t last_modified(std::string const &Filename) { - std::string fn = Filename; + const std::string fn = Filename; struct stat filestat; if (::stat(fn.c_str(), &filestat) == 0) return filestat.st_mtime; @@ -411,7 +411,7 @@ bool erase_extension(std::string &Filename) void erase_leading_slashes(std::string &Filename) { - auto pos = Filename.find_first_not_of('/'); + const auto pos = Filename.find_first_not_of('/'); Filename.erase(0, pos); } @@ -425,7 +425,7 @@ void replace_slashes(std::string &Filename) std::string substr_path(std::string const &Filename) { // String::substr returns new string so substr_path has to return std::string - if (auto pos = Filename.rfind('/'); pos != std::string::npos) + if (const auto pos = Filename.rfind('/'); pos != std::string::npos) return Filename.substr(0, pos + 1); return {}; } diff --git a/utilities/utilities.h b/utilities/utilities.h index d7ab293b..591b71f3 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -87,7 +87,7 @@ inline double LocalRandom(double b) inline double BorlandTime() { - auto timesinceepoch = std::time(nullptr); + const auto timesinceepoch = std::time(nullptr); return timesinceepoch / (24.0 * 60 * 60); /* // std alternative @@ -177,7 +177,7 @@ inline std::string extract_value(std::string const &Key, std::string const &Inpu template bool extract_value(Type_ &Variable, std::string const &Key, std::string const &Input, std::string const &Default) { - auto value = extract_value(Key, Input); + const auto value = extract_value(Key, Input); if (false == value.empty()) { // set the specified variable to retrieved value diff --git a/utilities/uuid.hpp b/utilities/uuid.hpp index d94fd0cc..6797ee9c 100644 --- a/utilities/uuid.hpp +++ b/utilities/uuid.hpp @@ -15,8 +15,8 @@ public: static UID random() { static thread_local std::mt19937_64 gen(std::random_device{}()); UID u; - uint64_t a = gen(); - uint64_t b = gen(); + const uint64_t a = gen(); + const uint64_t b = gen(); for (int i = 0; i < 8; ++i) u.bytes[i] = uint8_t(a >> (i * 8) & 0xFF); for (int i = 0; i < 8; ++i) u.bytes[8 + i] = uint8_t(b >> (i * 8) & 0xFF); diff --git a/vehicle/AirCoupler.cpp b/vehicle/AirCoupler.cpp index 22a5a6bb..4db2adad 100644 --- a/vehicle/AirCoupler.cpp +++ b/vehicle/AirCoupler.cpp @@ -66,7 +66,7 @@ void AirCoupler::Init(std::string const &asName, TModel3d *Model) */ void AirCoupler::Load(cParser *Parser, TModel3d *Model) { - auto name = Parser->getToken(); + const auto name = Parser->getToken(); if(Model) { Init(name, Model); diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index 3186030e..c1885fb8 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -45,10 +45,10 @@ void TCamera::OnCursorMove(double x, double y) { } static double ComputeAxisSpeed(double param, double walkspeed, double maxspeed, double threshold) { - double absval = std::abs(param); + const double absval = std::abs(param); // 2/3rd of the stick range lerps walk speed, past that we lerp between max walk and run speed - double walk = walkspeed * std::min(absval / threshold, 1.0); - double run = std::max(0.0, absval - threshold) / (1.0 - threshold) * std::max(0.0, maxspeed - walkspeed); + const double walk = walkspeed * std::min(absval / threshold, 1.0); + const double run = std::max(0.0, absval - threshold) / (1.0 - threshold) * std::max(0.0, maxspeed - walkspeed); return (param >= 0.0 ? 1.0 : -1.0) * (walk + run); } diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index 368264b0..a8901593 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -200,9 +200,9 @@ void TSpeedPos::Clear() void TSpeedPos::CommandCheck() { // sprawdzenie typu komendy w evencie i określenie prędkości - TCommandType command = evEvent->input_command(); - double value1 = evEvent->input_value(1); - double value2 = evEvent->input_value(2); + const TCommandType command = evEvent->input_command(); + const double value1 = evEvent->input_value(1); + const double value2 = evEvent->input_value(2); switch (command) { case TCommandType::cm_ShuntVelocity: @@ -459,9 +459,9 @@ std::vector TController::CheckTrackEvent( TTrack *Track, double c std::vector events; auto const &eventsequence { ( fDirection > 0 ? Track->m_events2 : Track->m_events1 ) }; for( auto const &event : eventsequence ) { - if( event.second != nullptr - && event.second->m_passive ) { - events.emplace_back( event.second ); + if( event != nullptr + && event->m_passive ) { + events.emplace_back( event ); } } return events; @@ -476,7 +476,7 @@ bool TController::TableAddNew() bool TController::TableNotFound(basic_event const *Event, double const Distance ) const { // sprawdzenie, czy nie został już dodany do tabelki (np. podwójne W4 robi problemy) - auto lookup = + const auto lookup = std::find_if( sSpeedTable.begin(), sSpeedTable.end(), @@ -1150,8 +1150,8 @@ TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, doub Drugi paramer dodatni - długość peronu (W4). */ auto L = 0.0; - auto Par1 = Point.evEvent->input_value(1); - auto Par2 = Point.evEvent->input_value(2); + const auto Par1 = Point.evEvent->input_value(1); + const auto Par2 = Point.evEvent->input_value(2); if (Par2 >= 0 || fLength < -Par2) { //użyj tego W4 if (Par1 < 0) { L = -Par1; @@ -2014,7 +2014,7 @@ void TController::Activation() iDirection = iDirectionOrder; // kierunek (względem sprzęgów pojazdu z AI) właśnie został ustalony (zmieniony) if (iDirection) { // jeśli jest ustalony kierunek - auto *initialvehicle { pVehicle }; + const auto *initialvehicle { pVehicle }; /* auto const initiallocalbrakelevel { mvOccupied->LocalBrakePosA }; */ @@ -2107,7 +2107,7 @@ void TController::Activation() void TController::AutoRewident() { // autorewident: nastawianie hamulców w składzie int r = 0, g = 0, p = 0; // ilości wagonów poszczególnych typów - TDynamicObject *d = pVehicles[0]; // pojazd na czele składu + const TDynamicObject *d = pVehicles[0]; // pojazd na czele składu // 1. Zebranie informacji o składzie pociągu — przejście wzdłuż składu i odczyt parametrów: // · ilość wagonów -> są zliczane, wszystkich pojazdów jest (iVehicles) // · długość (jako suma) -> jest w (fLength) @@ -2266,7 +2266,7 @@ void TController::AutoRewident() BrakingLevelIncrease = IsHeavyCargoTrain ? 0.25 : IsCargoTrain ? 0.25 : 0.25; if( is_emu() ) { - auto ep_factor { ( BrakeSystem == TBrakeSystem::ElectroPneumatic ? 8 : 4 ) }; + const auto ep_factor { ( BrakeSystem == TBrakeSystem::ElectroPneumatic ? 8 : 4 ) }; if( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors fNominalAccThreshold = std::max( -0.60, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); @@ -2295,8 +2295,8 @@ void TController::AutoRewident() double TController::ESMVelocity(bool Main) { - double fCurrentCoeff = 0.9; - double fFrictionCoeff = 0.85; + const double fCurrentCoeff = 0.9; + const double fFrictionCoeff = 0.85; double ESMVel = 9999; int MCPN = mvControlling->MainCtrlActualPos; int SCPN = mvControlling->ScndCtrlActualPos; @@ -2306,7 +2306,7 @@ double TController::ESMVelocity(bool Main) SCPN += 1; if (mvControlling->RList[MCPN].ScndAct < 255 && mvControlling->ScndCtrlActualPos == 0) SCPN = mvControlling->RList[MCPN].ScndAct; - double FrictionMax = mvControlling->Mass*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; + const double FrictionMax = mvControlling->Mass*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; double IF = mvControlling->Imax; double MS = 0; double Fmax = 0; @@ -2324,11 +2324,11 @@ double TController::ESMVelocity(bool Main) } } IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); - double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; - double pole = mvControlling->MotorParam[SCPN].fi * + const double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; + const double pole = mvControlling->MotorParam[SCPN].fi * std::max(abs(IF) / (abs(IF) + mvControlling->MotorParam[SCPN].Isat) - mvControlling->MotorParam[SCPN].fi0, 0.0); - double Us = abs(mvControlling->EngineVoltage) - IF*R; - double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); + const double Us = abs(mvControlling->EngineVoltage) - IF*R; + const double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio; return ESMVel; } @@ -2589,7 +2589,7 @@ TBrakeSystem TController::consist_brake_system() const { auto isepcapable = true; if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first + const auto *vehicle = pVehicles[ end::front ]; // start from first while( true == isepcapable && vehicle != nullptr ) { // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself @@ -2606,7 +2606,7 @@ TBrakeSystem TController::consist_brake_system() const { int TController::OrderDirectionChange(int newdir, TMoverParameters *Vehicle) { // zmiana kierunku jazdy, niezależnie od kabiny - int testd = newdir; + const int testd = newdir; if (Vehicle->Vel < 0.5) { // jeśli prawie stoi, można zmienić kierunek, musi być wykonane dwukrotnie, bo za pierwszym razem daje na zero switch (newdir * Vehicle->CabActive) @@ -3017,7 +3017,7 @@ bool TController::IncBrake() */ if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first + const auto *vehicle = pVehicles[ end::front ]; // start from first while( true == standalone && vehicle != nullptr ) { // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself @@ -3070,7 +3070,7 @@ bool TController::IncBrake() pos_corr += mvOccupied->Handle->GetCP()*0.2; } - double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); + const double deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); if( deltaAcc > fBrake_a1[0]) { @@ -3577,7 +3577,7 @@ bool TController::IncSpeed() if (mvControlling->EIMCtrlType > 0) { if (true == Ready) { - bool max = mvControlling->Vel > mvControlling->dizel_minVelfullengage + const bool max = mvControlling->Vel > mvControlling->dizel_minVelfullengage || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0); DizelPercentage = max ? 100 : 1; } @@ -3958,7 +3958,7 @@ void TController::SpeedCntrl(double DesiredSpeed) } else if (mvControlling->ScndCtrlPosNo > 1 && !mvOccupied->SpeedCtrlTypeTime) { - int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); + const int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); while( mvControlling->ScndCtrlPos > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop } @@ -4060,8 +4060,8 @@ void TController::SetTimeControllers() if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) { - DizelPercentage_Speed = DizelPercentage; //wstepnie procenty - auto MinVel{ std::min(mvControlling->hydro_TC_LockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity + DizelPercentage_Speed = DizelPercentage; // wstepnie procenty + const auto MinVel{ std::min(mvControlling->hydro_TC_LockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity //when speed controll unit is active - start with the procedure if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0) { if (mvControlling->ScndCtrlPos > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) @@ -4119,12 +4119,12 @@ void TController::SetTimeControllers() //5.2. Analog direct controller if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax > 30) { - int MaxPos = mvControlling->MainCtrlPosNo; + const int MaxPos = mvControlling->MainCtrlPosNo; int MinPos = MaxPos; for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i; if (MaxPos > MinPos && mvControlling->MainCtrlPos > 0 && AccDesired > 0) { - double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel); + const double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel); int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0); if (DesiredPos > MaxPos) DesiredPos = MaxPos; if (DesiredPos < MinPos) DesiredPos = MinPos; @@ -4228,7 +4228,7 @@ void TController::CheckTimeControllers() //5.1. Digital controller in DMUs with hydro if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) { - int DizelActualPercentage = 100.4 * mvControlling->eimic_real; + const int DizelActualPercentage = 100.4 * mvControlling->eimic_real; int NeutralPos = mvControlling->MainCtrlPosNo - 1; //przedostatnia powinna wstrzymywać - hipoteza robocza for (int i = mvControlling->MainCtrlPosNo; i >= 0; i--) if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0 && mvControlling->UniCtrlList[i].SpeedDown < 0.01) //niby zero, ale nie zmniejsza procentów @@ -5262,7 +5262,7 @@ std::string TController::StopReasonText() const bool TController::IsOccupiedByAnotherConsist( TTrack *Track, double const Distance = 0 ) { // najpierw sprawdzamy, czy na danym torze są pojazdy z innego składu if( false == Track->Dynamics.empty() ) { - for( auto dynamic : Track->Dynamics ) { + for (const auto dynamic : Track->Dynamics ) { if( dynamic->ctOwner != this ) { // jeśli jest jakiś cudzy to tor jest zajęty i skanowanie nie obowiązuje if( Distance == 0 ) { @@ -5812,7 +5812,7 @@ void TController::ControllingSet() BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego { - auto *lookup { pVehicle->FindPantographCarrier() }; + const auto *lookup { pVehicle->FindPantographCarrier() }; mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlling; } BrakeSystem = consist_brake_system(); @@ -5938,7 +5938,7 @@ TController::determine_consist_state() { fBrake_a1[0] = fBrake_a1[index]; if (is_emu() || is_dmu()) { - auto Coeff = std::clamp( mvOccupied->Vel*0.015 , 0.5 , 1.0); + const auto Coeff = std::clamp( mvOccupied->Vel*0.015 , 0.5 , 1.0); fAccThreshold = fNominalAccThreshold * Coeff - fBrake_a0[BrakeAccTableSize] * (1.0 - Coeff); } @@ -5952,7 +5952,7 @@ TController::determine_consist_state() { IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false; IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false; ConsistShade = 0.0; - auto *p { pVehicles[ end::front ] }; // pojazd na czole składu + const auto *p { pVehicles[ end::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów @@ -6059,7 +6059,7 @@ TController::determine_consist_state() { auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { absaccs = 0; - auto *d = pVehicles[ end::front ]; // pojazd na czele składu + const auto *d = pVehicles[ end::front ]; // pojazd na czele składu while( d ) { absaccs += d->MoverParameters->TotalMass * d->MoverParameters->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) @@ -6535,7 +6535,7 @@ TController::scan_obstacles( double const Range ) { // HACK: vehicle order in the consist is based on intended travel direction // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist // we cast to int to avoid getting confused by microstutters - auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? end::front : end::rear ) ] }; + const auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? end::front : end::rear ) ] }; int routescandirection; // for moving vehicle determine heading from velocity; for standing fall back on the set direction @@ -6757,7 +6757,7 @@ TController::check_load_exchange() { if( fStopTime > 0 ) { return; } // czas postoju przed dalszą jazdą (np. na przystanku) - auto *vehicle { pVehicles[ end::front ] }; + const auto *vehicle { pVehicles[ end::front ] }; while( vehicle != nullptr ) { auto const vehicleexchangetime { vehicle->LoadExchangeTime() }; DoesAnyDoorNeedOpening |= vehicleexchangetime > 0 && vehicle->LoadExchangeSpeed() == 0; @@ -6829,7 +6829,7 @@ TController::UpdateLooseShunt() { && AccDesired > 0.1 && mvOccupied->Vel < 1.0 ) { - auto *vehicle { Obstacle.vehicle }; + const auto *vehicle { Obstacle.vehicle }; auto const direction { ( vehicle->Prev() != nullptr ? end::front : end::rear ) }; while( vehicle != nullptr ) { if( vehicle->MoverParameters->BrakePress > 0.2 ) { @@ -6889,7 +6889,7 @@ TController::UpdateConnect() { // podłączanie do składu if (iDrivigFlags & moveConnect) { // sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec - auto *vehicle { iCouplingVehicle.value().first }; + const auto *vehicle { iCouplingVehicle.value().first }; auto const couplingend { iCouplingVehicle.value().second }; auto *vehicleparameters { vehicle->MoverParameters }; if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != iCoupler ) { @@ -6949,7 +6949,7 @@ TController::UpdateConnect() { void TController::GuardOpenDoor() { if ((iDrivigFlags & moveGuardOpenDoor) != 0) { - auto *vehicle{ pVehicles[end::front] }; + const auto *vehicle{ pVehicles[end::front] }; while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) { vehicle = vehicle->Next(); } @@ -6972,7 +6972,7 @@ TController::GuardOpenDoor() { int TController::unit_count( int const Threshold ) const { - auto *vehicle { pVehicle }; + const auto *vehicle { pVehicle }; auto unitcount { 1 }; do { auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu @@ -7900,7 +7900,7 @@ void TController::control_tractive_force() { // zmniejszanie predkosci // margines dla prędkości jest doliczany tylko jeśli oczekiwana prędkość jest większa od 5km/h if( false == TestFlag( iDrivigFlags, movePress ) ) { - double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0; + const double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0; // jeśli nie dociskanie if( AccDesired <= EU07_AI_NOACCELERATION ) { cue_action( driver_hint::mastercontrollersetzerospeed ); diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index 03eba754..9623a469 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -552,7 +552,7 @@ void TDynamicObject::SetPneumatic(bool front, bool red) void TDynamicObject::UpdateAxle(TAnim *pAnim) { // animacja osi - size_t wheel_id = pAnim->dWheelAngle; + const size_t wheel_id = pAnim->dWheelAngle; pAnim->smAnimated->SetRotate(float3(1, 0, 0), dWheelAngle[wheel_id]); pAnim->smAnimated->future_transform = glm::rotate((float)glm::radians(m_future_wheels_angle[wheel_id]), glm::vec3(1.0f, 0.0f, 0.0f)); }; @@ -718,7 +718,7 @@ void TDynamicObject::UpdateWiper(TAnim* pAnim) if (!pAnim || !pAnim->smElement) return; - int i = pAnim->iNumber; + const int i = pAnim->iNumber; // odwaramy animacje dla parzystych indexow const double rotateAngle = (i + 1) % 2 == 0 ? -MoverParameters->WiperAngle : MoverParameters->WiperAngle; @@ -1525,7 +1525,7 @@ TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const } double objectposition; // robocza odległość od kolejnych pojazdów na danym odcinku - for( auto dynamic : Track->Dynamics ) { + for (const auto dynamic : Track->Dynamics ) { if( dynamic == this ) { continue; } // szukający się nie liczy /* @@ -1894,7 +1894,7 @@ void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) -axle.offset : axle.offset + MoverParameters->Dim.L ) + fDist; } - double fAxleDistHalf = fAxleDist * 0.5; + const double fAxleDistHalf = fAxleDist * 0.5; // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) switch (iNumAxles) { @@ -2739,8 +2739,8 @@ void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) // potentially attach automatic coupler adapter to allow the connection // HACK: we're doing it after establishin actual connection, as the method needs valid neighbour data - auto &coupler { MoverParameters->Couplers[ vehicleend ] }; - auto &othercoupler { Object->MoverParameters->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; + const auto &coupler { MoverParameters->Couplers[ vehicleend ] }; + const auto &othercoupler { Object->MoverParameters->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; if( coupler.type() != othercoupler.type() ) { if( othercoupler.type() == TCouplerType::Automatic ) { @@ -4181,7 +4181,7 @@ void TDynamicObject::pants_up() auto d = this; bool isAnyPantUp = false; while (d) { - for (auto &item : d->MoverParameters->Pantographs) + for (const auto &item : d->MoverParameters->Pantographs) { isAnyPantUp |= item.is_active; } @@ -4189,7 +4189,7 @@ void TDynamicObject::pants_up() } d = Prev(4); while (d) { - for (auto &item : d->MoverParameters->Pantographs) + for (const auto &item : d->MoverParameters->Pantographs) { isAnyPantUp |= item.is_active; } @@ -7295,9 +7295,9 @@ void TDynamicObject::RaLightsSet(int head, int rear) bool tRight = MoverParameters->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej if (Controller == Humandriver) { - int ¤tDimPos = MoverParameters->modernDimmerPosition; - auto &dimmerPositions = MoverParameters->dimPositions; - TMoverParameters::dimPosition dps = dimmerPositions[currentDimPos]; + const int ¤tDimPos = MoverParameters->modernDimmerPosition; + const auto &dimmerPositions = MoverParameters->dimPositions; + const TMoverParameters::dimPosition dps = dimmerPositions[currentDimPos]; // domyślnie HighBeamLights = false; @@ -7359,9 +7359,9 @@ void TDynamicObject::SetLightDimmings() if (Controller == Humandriver) { - int ¤tDimPos = MoverParameters->modernDimmerPosition; - auto &dimmerPositions = MoverParameters->dimPositions; - TMoverParameters::dimPosition dps = dimmerPositions[currentDimPos]; + const int ¤tDimPos = MoverParameters->modernDimmerPosition; + const auto &dimmerPositions = MoverParameters->dimPositions; + const TMoverParameters::dimPosition dps = dimmerPositions[currentDimPos]; // domyślnie HighBeamLights = false; @@ -8247,7 +8247,7 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } if (Vehicle.Mains) { - float power = std::clamp(Vehicle.eimv_pr, 0.0, 1.0); + const float power = std::clamp(Vehicle.eimv_pr, 0.0, 1.0); fake_engine .pitch(fake_engine.m_frequencyoffset + power * fake_engine.m_frequencyfactor) @@ -8311,7 +8311,7 @@ TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, doub } if (Vehicle.hydro_R) { - float speed = std::abs(Vehicle.hydro_R_n); + const float speed = std::abs(Vehicle.hydro_R_n); retarder .pitch(retarder.m_frequencyoffset + speed * retarder.m_frequencyfactor) diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index a510b05f..75b62ef4 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -184,7 +184,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu endscale *= mul; } TSubModel *submodel { nullptr }; - std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; + const std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; for( auto const *source : sources ) { if( source != nullptr && ( submodel = source->GetFromName( submodelname ) ) != nullptr ) { @@ -219,7 +219,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu { "wip", TGaugeAnimation::gt_Wiper }, { "dgt", TGaugeAnimation::gt_Digital } }; - auto lookup = gaugetypes.find( gaugetypename ); + const auto lookup = gaugetypes.find( gaugetypename ); auto const type = lookup != gaugetypes.end() ? lookup->second : TGaugeAnimation::gt_Unknown; Init( submodel, submodelon, type, scale, offset, friction, 0, endvalue, endscale, interpolatescale ); @@ -358,7 +358,7 @@ void TGauge::Update( bool const Power ) { // update value // TODO: remove passing manually power state when LD is in place if( m_value != m_targetvalue ) { - float dt = Timer::GetDeltaTime(); + const float dt = Timer::GetDeltaTime(); if( m_friction > 0 && dt < 0.5 * m_friction ) { // McZapkie-281102: zabezpieczenie przed oscylacjami dla dlugich czasow m_value += dt * ( m_targetvalue - m_value ) / m_friction; diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp index 753ab0d4..c25dac2f 100644 --- a/vehicle/Train.cpp +++ b/vehicle/Train.cpp @@ -849,8 +849,8 @@ std::shared_ptr TTrain::GetTrainState(dictionary_source const dict->insert("compressors_" + idx + "_car_no", std::get<2>(bCompressors[i])); } - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); + const bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; + const TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); int in = 0; while (p && in < 8) { @@ -1878,7 +1878,7 @@ void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const else { // car brake handling, while in walk mode - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + const auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle != nullptr) { if (Command.action == GLFW_PRESS) @@ -2135,7 +2135,7 @@ void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + const auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle == nullptr) { return; @@ -2151,7 +2151,7 @@ void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Co if (Command.action != GLFW_RELEASE) { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + const auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle == nullptr) { return; @@ -2171,7 +2171,7 @@ void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Co if (Command.action != GLFW_RELEASE) { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + const auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle == nullptr) { return; @@ -2576,7 +2576,7 @@ void TTrain::OnCommand_brakeloadcompensationincrease(TTrain *Train, command_data if (true == Command.freefly && Command.action == GLFW_PRESS) { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + const auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle != nullptr) { vehicle->MoverParameters->IncBrakeMult(); @@ -2589,7 +2589,7 @@ void TTrain::OnCommand_brakeloadcompensationdecrease(TTrain *Train, command_data if (true == Command.freefly && Command.action == GLFW_PRESS) { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + const auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle != nullptr) { vehicle->MoverParameters->DecBrakeMult(); @@ -3516,7 +3516,7 @@ void TTrain::update_pantograph_valves() { auto const &presets{mvOccupied->PantsPreset.first}; - auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; + const auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; auto const preset{presets[selection] - '0'}; auto const swapends{cab_to_end() != end::front}; @@ -3550,7 +3550,7 @@ void TTrain::change_pantograph_selection(int const Change) void TTrain::OnCommand_pantographvalvesupdate(TTrain *Train, command_data const &Command) { - bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); + const bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); if (Command.action == GLFW_REPEAT) { @@ -3590,7 +3590,7 @@ void TTrain::OnCommand_pantographvalvesupdate(TTrain *Train, command_data const void TTrain::OnCommand_pantographvalvesoff(TTrain *Train, command_data const &Command) { - bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); + const bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); if (Command.action == GLFW_REPEAT) { @@ -5893,7 +5893,7 @@ void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data con // update modern dimmer state auto &dimPos = Train->mvOccupied->modernDimmerPosition; - auto dimCount = Train->mvOccupied->dimPositions.size(); + const auto dimCount = Train->mvOccupied->dimPositions.size(); if (dimPos + 1 < dimCount) dimPos++; else if (Train->mvOccupied->modernDimmerCanCycle) @@ -5917,7 +5917,7 @@ void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data con if (Command.action == GLFW_PRESS) { auto &dimPos = Train->mvOccupied->modernDimmerPosition; - auto dimCount = Train->mvOccupied->dimPositions.size(); + const auto dimCount = Train->mvOccupied->dimPositions.size(); if (dimCount == 0) return; @@ -6106,7 +6106,7 @@ void TTrain::OnCommand_endsignalstoggle(TTrain *Train, command_data const &Comma if (true == Command.freefly && Command.action == GLFW_PRESS) { - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; + const auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; if (vehicle == nullptr) { @@ -6878,7 +6878,7 @@ void TTrain::OnCommand_springbrakerelease(TTrain *Train, command_data const &Com { // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + const auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; if (vehicle == nullptr) { return; @@ -6985,9 +6985,9 @@ void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + const bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; + const int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; + const TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) @@ -7024,9 +7024,9 @@ void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Comman if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + const bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; + const int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; + const TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) @@ -7063,9 +7063,9 @@ void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command if (Command.action == GLFW_PRESS) { // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + const bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; + const int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; + const TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) @@ -8373,14 +8373,14 @@ void TTrain::OnCommand_vehicleboost(TTrain *Train, const command_data &Command) if (Command.action == GLFW_RELEASE || !DebugModeFlag) return; - double boost = Command.param1 != 0.0 ? Command.param1 : 2.78; + const double boost = Command.param1 != 0.0 ? Command.param1 : 2.78; if (Train->DynamicObject == nullptr) { return; } - auto *vehicle{Train->DynamicObject}; + const auto *vehicle{Train->DynamicObject}; while (vehicle) { vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; @@ -8589,7 +8589,7 @@ bool TTrain::Update(double const Deltatime) } fTachoVelocity = static_cast(std::min(std::abs(11.31 * mvControlled->WheelDiameter * mvControlled->nrot), maxSpeed)); { // skacze osobna zmienna - float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy + const float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy // pomiar, pol sekundy ustawienie if (ff != fTachoTimer) // jesli w tej sekundzie nie zmienial { @@ -8643,8 +8643,8 @@ bool TTrain::Update(double const Deltatime) fHCurrent[3] = mvControlled->ShowCurrent(3); } - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); + const bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; + const TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); int in = 0; fEIMParams[0][6] = 0; iCarNo = 0; @@ -8843,7 +8843,7 @@ bool TTrain::Update(double const Deltatime) // youBy - prad w drugim czlonie: galaz lub calosc { - TDynamicObject *tmp{nullptr}; + const TDynamicObject *tmp{nullptr}; if (DynamicObject->NextConnected()) if (TestFlag(mvControlled->Couplers[end::rear].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == 1) tmp = DynamicObject->NextConnected(); @@ -8976,7 +8976,7 @@ bool TTrain::Update(double const Deltatime) if (mvControlled->SlippingWheels) { // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax; + const double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax; if (veldiff < -0.01) { // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza @@ -9303,7 +9303,7 @@ bool TTrain::Update(double const Deltatime) } { // yB - wskazniki drugiego czlonu - TDynamicObject *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... + const TDynamicObject *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce if (TestFlag(mvControlled->Couplers[1].CouplingFlag, coupling::control) && mvOccupied->CabOccupied > 0) tmp = DynamicObject->NextConnected(); @@ -10202,7 +10202,7 @@ void TTrain::update_sounds_resonancenoise(sound_source &Sound) auto const frequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 + const auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 if (volume > 0.05) { @@ -10261,7 +10261,7 @@ void TTrain::update_sounds_radio() } // adjust audibility of remaining messages based on current radio conditions auto const radioenabled{true == mvOccupied->Radio && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)}; - for (auto &message : m_radiomessages) + for (const auto &message : m_radiomessages) { auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && message.first == RadioChannel() ? m_radiovolume : 0.0}; message.second->gain(volume); @@ -10298,7 +10298,7 @@ void TTrain::update_screens(double dt) screen.updatetimecounter = screen.updatetime > 0 ? 0 : -1; - auto state_dict = GetTrainState(screen.parameters); + const auto state_dict = GetTrainState(screen.parameters); state_dict->insert("touches", *screen.touch_list); screen.touch_list->clear(); @@ -10871,7 +10871,7 @@ void TTrain::DynamicSet(TDynamicObject *d) } // cache nearest unit equipped with pantographs { - auto *lookup{DynamicObject->FindPantographCarrier()}; + const auto *lookup{DynamicObject->FindPantographCarrier()}; // HACK: set pointer to existing vehicle to avoid error checking all over the place mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlled; } @@ -11597,14 +11597,14 @@ void TTrain::set_cab_controls(int const Cab) ggRadioVolumeSelector.PutValue(m_radiovolume); // finding each inverter - not so optimal, but action ins performed only during changing cabin - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - int flag = DynamicObject->MoverParameters->InverterControlCouplerFlag; + const bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; + const int flag = DynamicObject->MoverParameters->InverterControlCouplerFlag; int itemstart = 0; for (auto &item : ggInverterToggleButtons) // for each button { int itemindex = itemstart; itemstart++; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); + const TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); while (p) { if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) @@ -11742,7 +11742,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-edenabled", btEDenabled}, }; { - auto lookup = lights.find(Label); + const auto lookup = lights.find(Label); if (lookup != lights.end()) { lookup->second.Load(Parser, DynamicObject); @@ -11761,7 +11761,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co {"i-cablight:", &Cabine[iCabn].bLight}, }; { - auto lookup = autolights.find(Label); + const auto lookup = autolights.find(Label); if (lookup != autolights.end()) { auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka @@ -11798,7 +11798,7 @@ bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int co } else if (Label == "i-doors:") { - int i = Parser.getToken() - 1; + const int i = Parser.getToken() - 1; auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka button.Load(Parser, DynamicObject); button.AssignBool(bDoors[0] + 3 * i); diff --git a/vr/openvr_imp.cpp b/vr/openvr_imp.cpp index 8cdda85f..814058d9 100644 --- a/vr/openvr_imp.cpp +++ b/vr/openvr_imp.cpp @@ -19,7 +19,7 @@ vr_openvr::vr_openvr() vr::VRInput()->GetInputSourceHandle("/user/hand/left", &inputhandle_left); vr::VRInput()->GetInputSourceHandle("/user/hand/right", &inputhandle_right); - std::string action_path = std::filesystem::current_path().string() + "/openvrconfig/openvr_actions.json"; + const std::string action_path = std::filesystem::current_path().string() + "/openvrconfig/openvr_actions.json"; vr::VRInput()->SetActionManifestPath(action_path.c_str()); vr::VRInput()->GetActionSetHandle("/actions/main", &actionset); @@ -342,7 +342,7 @@ bool vr_openvr::update_component(const std::string &rendermodel, vr::VRInputValu vr::VRRenderModels()->GetComponentStateForDevicePath(rendermodel.c_str(), component->pName.c_str(), handle, &state, &component_state); - glm::mat4 component_pose = get_matrix(component_state.mTrackingToComponentRenderModel); + const glm::mat4 component_pose = get_matrix(component_state.mTrackingToComponentRenderModel); bool visible = (component_state.uProperties & vr::VRComponentProperty_IsVisible); component->ReplaceMatrix(component_pose); @@ -368,7 +368,7 @@ std::vector vr_openvr::get_render_models() if (!draw_controllers) return list; - for (auto entry : controllers) + for (const auto entry : controllers) { if (entry && entry->model && entry->pending_components.empty()) list.push_back(entry->model.get()); diff --git a/vr/vr_interface.cpp b/vr/vr_interface.cpp index 9f9ff4e4..64452ba0 100644 --- a/vr/vr_interface.cpp +++ b/vr/vr_interface.cpp @@ -12,7 +12,7 @@ bool vr_interface_factory::register_backend(const std::string &backend, vr_inter std::unique_ptr vr_interface_factory::create(const std::string &backend) { - auto it = backends.find(backend); + const auto it = backends.find(backend); if (it != backends.end()) return it->second(); diff --git a/widgets/cameraview_extcam.cpp b/widgets/cameraview_extcam.cpp index 6ee09043..c41abc50 100644 --- a/widgets/cameraview_extcam.cpp +++ b/widgets/cameraview_extcam.cpp @@ -112,17 +112,17 @@ void ui::cameraview_panel::render_contents() } } - ImVec2 surface_size = ImGui::GetContentRegionAvail(); + const ImVec2 surface_size = ImGui::GetContentRegionAvail(); ImGui::Image((ImTextureID)(intptr_t)(texture->id), surface_size); } void ui::cameraview_panel::capture_func() { - std::string cmdline = Global.extcam_cmd; + const std::string cmdline = Global.extcam_cmd; piped_proc proc(cmdline); - size_t frame_size = Global.extcam_res.x * Global.extcam_res.y * 3; + const size_t frame_size = Global.extcam_res.x * Global.extcam_res.y * 3; auto read_buffer = new uint8_t[frame_size]; auto active_buffer = new uint8_t[frame_size]; @@ -165,15 +165,15 @@ void ui::cameraview_panel::record_func() if (!rec_name.empty()) { const std::string magic{"{RECORD}"}; - size_t pos = cmdline.find(magic); + const size_t pos = cmdline.find(magic); if (pos != -1) cmdline.replace(pos, magic.size(), rec_name); } piped_proc proc(cmdline, true); - size_t frame_size = Global.extcam_res.x * Global.extcam_res.y * 3; - auto read_buffer = new uint8_t[frame_size]; + const size_t frame_size = Global.extcam_res.x * Global.extcam_res.y * 3; + const auto read_buffer = new uint8_t[frame_size]; uint32_t last_cnt = 0; size_t bufpos = frame_size; @@ -182,7 +182,7 @@ void ui::cameraview_panel::record_func() if (bufpos == frame_size) { std::unique_lock lock(mutex); - auto r = notify_var.wait_for(lock, std::chrono::milliseconds(50), [this, last_cnt]{return last_cnt != frame_cnt;}); + const auto r = notify_var.wait_for(lock, std::chrono::milliseconds(50), [this, last_cnt]{return last_cnt != frame_cnt;}); last_cnt = frame_cnt; if (!image_ptr || !r) continue; diff --git a/widgets/map.cpp b/widgets/map.cpp index f2fb6b9e..826f2765 100644 --- a/widgets/map.cpp +++ b/widgets/map.cpp @@ -544,7 +544,7 @@ ui::track_switch_window::track_switch_window(ui_panel &panel, std::shared_ptr names = { "ac", "ad", "bc", "bd" }; + const std::array names = { "ac", "ad", "bc", "bd" }; for (size_t i = 0; i < 4; i++) { if (m_switch->action[i]) { @@ -661,19 +661,19 @@ void ui::vehicle_click_window::render_content() ImGui::TextUnformatted(STR_C("Light signal:")); if (ImGui::Button(STR_C("none"))) { - std::string name = m_vehicle->name + "%SetSignal"; + const std::string name = m_vehicle->name + "%SetSignal"; m_relay.post(user_command::sendaicommand, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(), &name); ImGui::CloseCurrentPopup(); } if (ImGui::Button(STR_C("Pc6"))) { - std::string name = m_vehicle->name + "%SetSignal"; + const std::string name = m_vehicle->name + "%SetSignal"; m_relay.post(user_command::sendaicommand, Signal_Pc6, 1.0, GLFW_PRESS, 0, glm::vec3(), &name); ImGui::CloseCurrentPopup(); } if (ImGui::Button(STR_C("A1"))) { - std::string name = m_vehicle->name + "%SetSignal"; + const std::string name = m_vehicle->name + "%SetSignal"; m_relay.post(user_command::sendaicommand, Signal_A1, 1.0, GLFW_PRESS, 0, glm::vec3(), &name); ImGui::CloseCurrentPopup(); @@ -701,7 +701,7 @@ void ui::vehicle_click_window::render_content() ImGui::InputInt(STR_C("Param 1"), &command_param1); ImGui::InputInt(STR_C("Param 2"), &command_param2); if (ImGui::Button(STR_C("Send"))) { - std::string name = m_vehicle->name + "%" + std::string(command_buf.data()); + const std::string name = m_vehicle->name + "%" + std::string(command_buf.data()); m_relay.post(user_command::sendaicommand, command_param1, command_param2, GLFW_PRESS, 0, glm::vec3(), &name); ImGui::CloseCurrentPopup(); diff --git a/widgets/map_objects.h b/widgets/map_objects.h index f5d07ebf..460eb998 100644 --- a/widgets/map_objects.h +++ b/widgets/map_objects.h @@ -30,7 +30,7 @@ struct semaphore : public map_object TMemCell *memcell = nullptr; virtual gfx::basic_vertex vertex() override { - bool stop_signal = memcell->IsVelocity() && (memcell->Value1() == 0.0); + const bool stop_signal = memcell->IsVelocity() && (memcell->Value1() == 0.0); return gfx::basic_vertex(location, glm::vec3(), (!stop_signal) ? glm::vec2(0.0f, 0.2f) : glm::vec2(0.2f, 0.4f)); } diff --git a/widgets/perfgraphs.cpp b/widgets/perfgraphs.cpp index 574cc7ef..bff56356 100644 --- a/widgets/perfgraphs.cpp +++ b/widgets/perfgraphs.cpp @@ -10,7 +10,7 @@ void perfgraph_panel::render_contents() { { for (size_t i = 0; i < (size_t)TIMER_MAX; i++) { - bool is_selected = (current_timer == (timers_e)i); + const bool is_selected = (current_timer == (timers_e)i); if (ImGui::Selectable(timer_label[i].c_str(), is_selected)) current_timer = (timers_e)i; if (is_selected) @@ -19,7 +19,7 @@ void perfgraph_panel::render_contents() { ImGui::EndCombo(); } - Timer::stopwatch *stopwatch = nullptr; + const Timer::stopwatch *stopwatch = nullptr; if (current_timer == gfx_total) stopwatch = &Timer::subsystem.gfx_total; diff --git a/widgets/time.cpp b/widgets/time.cpp index d299d17b..2975058f 100644 --- a/widgets/time.cpp +++ b/widgets/time.cpp @@ -26,7 +26,7 @@ void ui::time_panel::render_contents() void ui::time_panel::open() { - auto &data = simulation::Time.data(); + const auto &data = simulation::Time.data(); time = (float)data.wHour + (float)data.wMinute / 60.0f; yearday = simulation::Time.year_day(); diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp index d4d11e5b..64ee7c6a 100644 --- a/widgets/trainingcard.cpp +++ b/widgets/trainingcard.cpp @@ -91,7 +91,7 @@ void trainingcard_panel::render_contents() if (ImGui::BeginPopupModal("Zapisywanie danych")) { ImGui::SetWindowSize(ImVec2(-1, -1)); - int s = state.load(); + const int s = state.load(); if (s == 1) { @@ -121,8 +121,8 @@ void trainingcard_panel::render_contents() if (start_time_wall) { - std::tm *tm = std::localtime(&(*start_time_wall)); - std::string rep = "Czas rozpoczęcia: " + std::to_string(tm->tm_year + 1900) + "-" + std::to_string(tm->tm_mon + 1) + "-" + std::to_string(tm->tm_mday) + " " + std::to_string(tm->tm_hour) + + const std::tm *tm = std::localtime(&(*start_time_wall)); + const std::string rep = "Czas rozpoczęcia: " + std::to_string(tm->tm_year + 1900) + "-" + std::to_string(tm->tm_mon + 1) + "-" + std::to_string(tm->tm_mday) + " " + std::to_string(tm->tm_hour) + ":" + std::to_string(tm->tm_min); ImGui::TextUnformatted(rep.c_str()); } @@ -159,11 +159,11 @@ void trainingcard_panel::render_contents() if (ImGui::Button("Rozpocznij szkolenie")) { start_time_wall = std::time(nullptr); - std::tm *tm = std::localtime(&(*start_time_wall)); + const std::tm *tm = std::localtime(&(*start_time_wall)); recording_timestamp = std::to_string(tm->tm_year + 1900) + std::to_string(tm->tm_mon + 1) + std::to_string(tm->tm_mday) + std::to_string(tm->tm_hour) + std::to_string(tm->tm_min) + "_" + std::string(trainee_name.c_str()) + "_" + std::string(instructor_name.c_str()); - int ret = StartRecording(); + const int ret = StartRecording(); if (ret != 1) { state.store(ret); diff --git a/widgets/vehiclelist.cpp b/widgets/vehiclelist.cpp index 92f9edf1..9da0c8f5 100644 --- a/widgets/vehiclelist.cpp +++ b/widgets/vehiclelist.cpp @@ -12,7 +12,7 @@ ui::vehiclelist_panel::vehiclelist_panel(ui_layer &parent) void ui::vehiclelist_panel::render_contents() { if (m_first_show && Global.gui_trainingdefault) { - for (TDynamicObject *vehicle : simulation::Vehicles.sequence()) + for (const TDynamicObject *vehicle : simulation::Vehicles.sequence()) { if (!vehicle->Mechanik || vehicle->name() != ToLower(Global.local_start_vehicle)) continue; @@ -26,13 +26,13 @@ void ui::vehiclelist_panel::render_contents() return; } - for (TDynamicObject *vehicle : simulation::Vehicles.sequence()) + for (const TDynamicObject *vehicle : simulation::Vehicles.sequence()) { if (!vehicle->Mechanik) continue; std::string name = vehicle->name(); - double speed = vehicle->GetVelocity(); + const double speed = vehicle->GetVelocity(); std::string timetable; if (vehicle->Mechanik) timetable = vehicle->Mechanik->TrainName() + ", "; diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index b46fe516..aca13cf4 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -12,7 +12,7 @@ ui::vehicleparams_panel::vehicleparams_panel(const std::string &vehicle) : ui_pa void screen_window_callback(ImGuiSizeCallbackData *data) { - auto config = static_cast(data->UserData); + const auto config = static_cast(data->UserData); data->DesiredSize.y = data->DesiredSize.x * (float)config->size.y / (float)config->size.x; } @@ -20,11 +20,11 @@ void ui::vehicleparams_panel::draw_infobutton(const char *str, ImVec2 pos, const { if (pos.x != -1.0f) { - ImVec2 window_size = ImGui::GetWindowSize(); + const ImVec2 window_size = ImGui::GetWindowSize(); - ImGuiStyle &style = ImGui::GetStyle(); - ImVec2 text_size = ImGui::CalcTextSize(str); - auto button_size = ImVec2(text_size.x + style.FramePadding.x * 2.0f, text_size.y + style.FramePadding.y * 2.0f); + const ImGuiStyle &style = ImGui::GetStyle(); + const ImVec2 text_size = ImGui::CalcTextSize(str); + const auto button_size = ImVec2(text_size.x + style.FramePadding.x * 2.0f, text_size.y + style.FramePadding.y * 2.0f); pos.x = pos.x * window_size.x / 512.0f - button_size.x / 2.0f; pos.y = pos.y * window_size.y / 118.0f - button_size.y / 2.0f; @@ -54,9 +54,9 @@ void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover) auto &tex = GfxRenderer->Texture(vehicle_mini); tex.create(); - ImVec2 size = ImGui::GetContentRegionAvail(); - float x = size.x; - float y = x * ((float)tex.get_height() / tex.get_width()); + const ImVec2 size = ImGui::GetContentRegionAvail(); + const float x = size.x; + const float y = x * ((float)tex.get_height() / tex.get_width()); if (ImGui::BeginChild("mini", ImVec2(x, y))) { diff --git a/world/EvLaunch.cpp b/world/EvLaunch.cpp index 29c3104f..c276e520 100644 --- a/world/EvLaunch.cpp +++ b/world/EvLaunch.cpp @@ -70,7 +70,7 @@ bool TEventLauncher::Load(cParser *parser) { "radio_call1", radio_message::call1 }, { "radio_call3", radio_message::call3 } }; - auto lookup = messages.find( token ); + const auto lookup = messages.find( token ); iKey = lookup != messages.end() ? lookup->second : // a jak więcej, to jakby numer klawisza jest vk_to_glfw_key(stol_def(token, 0)); @@ -160,11 +160,11 @@ bool TEventLauncher::check_activation_key() { if (iKey <= 0) return false; - char key = iKey & 0xff; + const char key = iKey & 0xff; bool result = Console::Pressed(key); - char modifier = iKey >> 8; + const char modifier = iKey >> 8; if (modifier & GLFW_MOD_SHIFT) result &= Global.shiftState; if (modifier & GLFW_MOD_CONTROL) diff --git a/world/Event.cpp b/world/Event.cpp index eb679e72..314bab77 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -126,7 +126,7 @@ basic_event::event_conditions::test() const { if( flags & ( flags::text | flags::value1 | flags::value2 ) ) { // porównanie wartości for( auto &cellwrapper : *memcompare_cells ) { - auto *cell { static_cast( std::get( cellwrapper ) ) }; + const auto *cell { static_cast( std::get( cellwrapper ) ) }; if( cell == nullptr ) { // ErrorLog( "Event " + asName + " trying conditional_memcompare with nonexistent memcell" ); continue; // though this is technically error, we treat it as a success to maintain backward compatibility @@ -357,7 +357,7 @@ basic_event::export_as_text( std::ostream &Output ) const { else { auto targetidx { 0 }; for( auto &target : m_targets ) { - auto *targetnode { std::get( target ) }; + const auto *targetnode { std::get( target ) }; Output << ( targetnode != nullptr ? targetnode->name() : std::get( target ) ) << ( ++targetidx < m_targets.size() ? '|' : ' ' ); @@ -534,7 +534,7 @@ updatevalues_event::run_() { // targetcell->LogValues(); if( targetcell->Track == nullptr ) { continue; } // McZapkie-100302 - updatevalues oprocz zmiany wartosci robi putcommand dla wszystkich 'dynamic' na danym torze - for( auto vehicle : targetcell->Track->Dynamics ) { + for (const auto vehicle : targetcell->Track->Dynamics ) { if( vehicle->Mechanik ) { WriteLog( " Vehicle: [" + vehicle->name() + "]" ); targetcell->PutCommand( @@ -575,7 +575,7 @@ getvalues_event::init() { init_targets( simulation::Memory, "memory cell" ); // custom target initialization code for( auto &target : m_targets ) { - auto *targetcell { static_cast( std::get( target ) ) }; + const auto *targetcell { static_cast( std::get( target ) ) }; if( targetcell == nullptr ) { continue; } if( targetcell->IsVelocity() ) { // jeśli odczyt komórki a komórka zawiera komendę SetVelocity albo ShuntVelocity @@ -1189,7 +1189,7 @@ logvalues_event::run_() { else { // jeśli była podana nazwa komórki for( auto &target : m_targets ) { - auto *targetcell { static_cast( std::get( target ) ) }; + const auto *targetcell { static_cast( std::get( target ) ) }; if( targetcell == nullptr ) { continue; } targetcell->LogValues(); } @@ -1322,7 +1322,7 @@ multi_event::export_as_text_( std::ostream &Output ) const { for( auto const &childevent : m_children ) { if( true == std::get( childevent ) ) { - auto *childeventdata { std::get( childevent ) }; + const auto *childeventdata { std::get( childevent ) }; Output << ( childeventdata != nullptr ? childeventdata->m_name : @@ -1335,7 +1335,7 @@ multi_event::export_as_text_( std::ostream &Output ) const { Output << "else "; for( auto const &childevent : m_children ) { if( false == std::get( childevent ) ) { - auto *childeventdata{ std::get( childevent ) }; + const auto *childeventdata{ std::get( childevent ) }; Output << ( childeventdata != nullptr ? childeventdata->m_name : @@ -1652,7 +1652,7 @@ animation_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { m_animationfilename = token; std::ifstream file( paths::models + m_animationfilename, std::ios::binary | std::ios::ate ); file.unsetf( std::ios::skipws ); - auto size = file.tellg(); // ios::ate already positioned us at the end of the file + const auto size = file.tellg(); // ios::ate already positioned us at the end of the file file.seekg( 0, std::ios::beg ); // rewind the caret afterwards // animation size, previously held in param 7 m_animationfilesize = size; @@ -1685,7 +1685,7 @@ animation_event::run_() { // animation modes target specific submodels m_animationcontainers.remove_if([this](std::weak_ptr ptr) { - auto targetcontainer = ptr.lock(); + const auto targetcontainer = ptr.lock(); if (!targetcontainer) return true; @@ -2235,7 +2235,7 @@ make_event( cParser &Input, scene::scratch_data &Scratchpad ) { event_manager::~event_manager() { - for( auto *event : m_events ) { + for (const auto *event : m_events ) { delete event; } } @@ -2292,7 +2292,7 @@ event_manager::update() { bool event_manager::insert( basic_event *Event ) { // najpierw sprawdzamy, czy nie ma, a potem dopisujemy - auto lookup = m_eventmap.find( Event->m_name ); + const auto lookup = m_eventmap.find( Event->m_name ); if( lookup != m_eventmap.end() ) { // duplicate of already existing event auto const size = Event->m_name.size(); @@ -2499,7 +2499,7 @@ event_manager::InitEvents() { void event_manager::InitLaunchers() { - std::vector *> launchertables { + const std::vector *> launchertables { &m_inputdrivenlaunchers, &m_radiodrivenlaunchers }; diff --git a/world/Event.h b/world/Event.h index 52ee3468..21828339 100644 --- a/world/Event.h +++ b/world/Event.h @@ -678,7 +678,7 @@ public: basic_event * FindEvent( std::string const &Name ); inline TEventLauncher* FindEventlauncher(std::string const &Name) { - auto ptr = m_inputdrivenlaunchers.find(Name); + const auto ptr = m_inputdrivenlaunchers.find(Name); return ptr ? ptr : m_radiodrivenlaunchers.find(Name); } // legacy method, inserts specified event in the event query diff --git a/world/MemCell.cpp b/world/MemCell.cpp index 76e9e4f1..386929c8 100644 --- a/world/MemCell.cpp +++ b/world/MemCell.cpp @@ -157,7 +157,7 @@ bool TMemCell::Compare( std::string const &szTestText, double const fTestValue1, if( TestFlag( CheckMask, basic_event::flags::text ) ) { // porównać teksty - auto range = szTestText.find( '*' ); + const auto range = szTestText.find( '*' ); auto const result { ( range == std::string::npos ? compare( szText, szTestText, TextOperator ) : @@ -277,7 +277,7 @@ memory_table::InitCells() { void memory_table::log_all() { - for( auto *cell : m_items ) { + for (const auto *cell : m_items ) { cell->LogValues(); } } diff --git a/world/Segment.cpp b/world/Segment.cpp index 53f1f904..a91ecea8 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -193,8 +193,8 @@ double TSegment::RombergIntegral(double const fA, double const fB) const double TSegment::GetTFromS(double const s) const { // initial guess for Newton's method - double fTolerance = 0.001; - double fRatio = s / RombergIntegral(0, 1); + const double fTolerance = 0.001; + const double fRatio = s / RombergIntegral(0, 1); double fTime = std::lerp( 0.0, 1.0, fRatio ); int iteration = 0; @@ -295,10 +295,10 @@ const double fDirectionOffset = 0.1; // długość wektora do wyliczenia kierunk glm::dvec3 TSegment::GetDirection(double const fDistance) const { // takie toporne liczenie pochodnej dla podanego dystansu od Point1 - double t1 = GetTFromS(fDistance - fDirectionOffset); + const double t1 = GetTFromS(fDistance - fDirectionOffset); if (t1 <= 0.0) return CPointOut - Point1; // na zewnątrz jako prosta - double t2 = GetTFromS(fDistance + fDirectionOffset); + const double t2 = GetTFromS(fDistance + fDirectionOffset); if (t2 >= 1.0) return Point1 - CPointIn; // na zewnątrz jako prosta return FastGetPoint(t2) - FastGetPoint(t1); @@ -306,10 +306,10 @@ glm::dvec3 TSegment::GetDirection(double const fDistance) const glm::dvec3 TSegment::FastGetDirection(double fDistance, double fOffset) { // takie toporne liczenie pochodnej dla parametru 0.0÷1.0 - double t1 = fDistance - fOffset; + const double t1 = fDistance - fOffset; if (t1 <= 0.0) return CPointOut - Point1; // wektor na początku jest stały - double t2 = fDistance + fOffset; + const double t2 = fDistance + fOffset; if (t2 >= 1.0) return Point2 - CPointIn; // wektor na końcu jest stały return FastGetPoint(t2) - FastGetPoint(t1); diff --git a/world/Track.cpp b/world/Track.cpp index 39dcb6df..f915084c 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -1082,7 +1082,7 @@ const int numPts = 4; bool TTrack::CheckDynamicObject(TDynamicObject *Dynamic) { // sprawdzenie, czy pojazd jest przypisany do toru - for( auto dynamic : Dynamics ) { + for (const auto dynamic : Dynamics ) { if( dynamic == Dynamic ) { return true; } @@ -1142,7 +1142,7 @@ bool TTrack::InMovement() if (!SwitchExtension->CurrentIndex) return false; // 0=zablokowana się nie animuje // trzeba każdorazowo porównywać z kątem modelu - auto ac = SwitchExtension->pModel ? SwitchExtension->pModel->GetContainer() : nullptr; + const auto ac = SwitchExtension->pModel ? SwitchExtension->pModel->GetContainer() : nullptr; return ac ? ac->AngleGet() != SwitchExtension->fOffset || !(ac->TransGet() == SwitchExtension->vTrans) : @@ -1208,7 +1208,7 @@ TTrack *TTrack::Next(TTrack *visitor) { else return trPrev; } else if (eType == tt_Switch) { - int state = GetSwitchState(); + const int state = GetSwitchState(); if (SwitchExtension->pPrevs[0] == visitor || SwitchExtension->pPrevs[1] == visitor) @@ -1754,7 +1754,7 @@ void TTrack::create_geometry( gfx::geometrybank_handle const &Bank ) { void TTrack::RenderDynSounds() { // odtwarzanie dźwięków pojazdów jest niezależne od ich wyświetlania - for( auto dynamic : Dynamics ) { + for (const auto dynamic : Dynamics ) { dynamic->RenderSounds(); } }; @@ -2095,7 +2095,7 @@ TTrack * TTrack::RaAnimate() //--------------------------------------------------------------------------- void TTrack::RadioStop() { // przekazanie pojazdom rozkazu zatrzymania - for( auto dynamic : Dynamics ) { + for (const auto dynamic : Dynamics ) { dynamic->RadioStop(); } }; @@ -2147,7 +2147,7 @@ int TTrack::TestPoint(const glm::dvec3 *Point) break; case tt_Switch: // zwrotnica { - int state = GetSwitchState(); // po co? + const int state = GetSwitchState(); // po co? // Ra: TODO: jak się zmieni na bezpośrednie odwołania do segmentow zwrotnicy, // to się wykoleja, ponieważ trNext zależy od przełożenia Switch(0); diff --git a/world/Traction.cpp b/world/Traction.cpp index 762ecc07..f5ca973b 100644 --- a/world/Traction.cpp +++ b/world/Traction.cpp @@ -474,7 +474,7 @@ double TTraction::VoltageGet(double u, double i) // 1. zasilacz psPower[0] z rezystancją fResistance[0] oraz jego wewnętrzną // 2. zasilacz psPower[1] z rezystancją fResistance[1] oraz jego wewnętrzną // 3. zasilacz psPowered z jego wewnętrzną rezystancją dla przęseł zasilanych bezpośrednio - double res = i != 0.0 ? u / i : 10000.0; + const double res = i != 0.0 ? u / i : 10000.0; if( psPowered != nullptr ) { // yB: dla zasilanego nie baw się w gwiazdy, tylko bierz bezpośrednio return res != 0.0 ? psPowered->CurrentGet(res) * res : 0.0; diff --git a/world/TractionPower.cpp b/world/TractionPower.cpp index 6ceac162..e70674ab 100644 --- a/world/TractionPower.cpp +++ b/world/TractionPower.cpp @@ -125,7 +125,7 @@ double TTractionPowerSource::CurrentGet(double res) } if (res > 0 || (res < 0 && (Recuperation || true))) TotalAdmitance += 1.0 / res; // połączenie równoległe rezystancji jest równoważne sumie admitancji - float NomVolt = TotalPreviousAdmitance < 0 ? NominalVoltage * 1.083 : NominalVoltage; + const float NomVolt = TotalPreviousAdmitance < 0 ? NominalVoltage * 1.083 : NominalVoltage; TotalCurrent = TotalPreviousAdmitance != 0.0 ? NomVolt / (InternalRes + 1.0 / TotalPreviousAdmitance) : 0.0; // napięcie dzielone przez sumę rezystancji wewnętrznej i obciążenia diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index b1884896..e01147be 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -51,7 +51,7 @@ TTrack * TTrackFollower::SetCurrentTrack(TTrack *pTrack, int end) { case tt_Switch: // jeśli zwrotnica, to przekładamy ją, aby uzyskać dobry segment { - int i = end ? pCurrentTrack->iNextDirection : pCurrentTrack->iPrevDirection; + const int i = end ? pCurrentTrack->iNextDirection : pCurrentTrack->iPrevDirection; if (i > 0) // jeżeli wjazd z ostrza pTrack->SwitchForced(i >> 1, Owner); // to przełożenie zwrotnicy - rozprucie! } diff --git a/world/station.cpp b/world/station.cpp index eae81d9e..5481d6e2 100644 --- a/world/station.cpp +++ b/world/station.cpp @@ -56,7 +56,7 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch if( parameters.LoadType.name == "passengers" ) { // NOTE: for the time being we're doing simple, random load change calculation // TODO: exchange driven by station parameters and time of the day - auto unloadcount = static_cast( + const auto unloadcount = static_cast( TestFlag( parameters.DamageFlag, dtrain_out ) ? parameters.LoadAmount : laststop ? parameters.LoadAmount : firststop ? 0 :