blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
73be87520f99097f7b613dd338e9392118686203
4c0aaa21705a9f1726133b5b524d6c3596aa9642
/DZ28.1/DZ28.1/dz28.1.cpp
9c1d8d13bb16d6b36f1fb309858a6a2981d0a31a
[]
no_license
mrjeck/cpp
407f3308ccea56e8d8546e331cce13bb60627af5
762993646ea3d89e662efe660b313cef6cdf66a8
refs/heads/master
2020-12-30T10:12:42.253606
2015-09-26T18:02:57
2015-09-26T18:02:57
34,620,448
0
0
null
null
null
null
UTF-8
C++
false
false
2,331
cpp
#include <vector> #include <string> #include <iostream> class Item { public: Item(const std::string &name, const std::string &own, const std::string &nphone, const std::string &bus) : firm_name(name), owner(own), phone(nphone), busines(bus) { } std::string GetFirmName() const { return firm_name.c_str(); } std::string GetOwnerName() const { return owner.c_str(); } std::string GetPhone() const { return phone.c_str(); } std::string GetBusines() const { return busines.c_str(); } private: std::string firm_name; std::string owner; std::string phone; std::string busines; }; class Handbook { public: void AddItem(const Item &i) { items.push_back(i); } void PrintAll(std::ostream &os) { for(std::vector<Item>::iterator it = items.begin(); it != items.end(); ++it) { os << it->GetFirmName() << "\n" << it->GetOwnerName() << "\n" << it->GetPhone() << "\n" << it->GetBusines() << "\n" << std::endl; } } Handbook FindByFirmName(const std::string &name) { Handbook h; for(std::vector<Item>::iterator it = items.begin(); it != items.end(); ++it) if(it->GetFirmName() == name) h.AddItem(*it); return h; } Handbook FindByOwner(const std::string &owner) { Handbook h; for(std::vector<Item>::iterator it = items.begin(); it != items.end(); ++it) if(it->GetOwnerName() == owner) h.AddItem(*it); return h; } Handbook FindByPhone(const std::string &phone) { Handbook h; for(std::vector<Item>::iterator it = items.begin(); it != items.end(); ++it) if(it->GetPhone() == phone) h.AddItem(*it); return h; } Handbook FindByBusines(const std::string &busines) { Handbook h; for(std::vector<Item>::iterator it = items.begin(); it != items.end(); ++it) if(it->GetBusines() == busines) h.AddItem(*it); return h; } private: std::vector<Item> items; }; int main() { return 0; }
[ "mr.jeck_88@mail.ru" ]
mr.jeck_88@mail.ru
a64df2d8acfa69263019ece39ea308900802b377
fe5bce6f5496c3ca66c1742fe53366cc3b2cd7fe
/llvm/lib/IR/DiagnosticInfo.cpp
8afb547971c729c94a3a4184fe9cde9969002664
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "NCSA" ]
permissive
lgq2015/SiriusObfuscator-SymbolExtractorAndRenamer
f3ce7d235343df4ec84eae26f6cc7b641aca02b6
bb45190d8dd92b795bfa0307da5e593eb4733d9a
refs/heads/master
2022-01-09T02:41:08.991909
2018-08-08T13:52:49
2018-08-08T13:52:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,599
cpp
//===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the different classes involved in low level diagnostics. // // Diagnostics reporting is still done as part of the LLVMContext. //===----------------------------------------------------------------------===// #include "llvm/IR/DiagnosticInfo.h" #include "LLVMContextImpl.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Regex.h" #include <atomic> #include <string> using namespace llvm; namespace { /// \brief Regular expression corresponding to the value given in one of the /// -pass-remarks* command line flags. Passes whose name matches this regexp /// will emit a diagnostic when calling the associated diagnostic function /// (emitOptimizationRemark, emitOptimizationRemarkMissed or /// emitOptimizationRemarkAnalysis). struct PassRemarksOpt { std::shared_ptr<Regex> Pattern; void operator=(const std::string &Val) { // Create a regexp object to match pass names for emitOptimizationRemark. if (!Val.empty()) { Pattern = std::make_shared<Regex>(Val); std::string RegexError; if (!Pattern->isValid(RegexError)) report_fatal_error("Invalid regular expression '" + Val + "' in -pass-remarks: " + RegexError, false); } } }; static PassRemarksOpt PassRemarksOptLoc; static PassRemarksOpt PassRemarksMissedOptLoc; static PassRemarksOpt PassRemarksAnalysisOptLoc; // -pass-remarks // Command line flag to enable emitOptimizationRemark() static cl::opt<PassRemarksOpt, true, cl::parser<std::string>> PassRemarks("pass-remarks", cl::value_desc("pattern"), cl::desc("Enable optimization remarks from passes whose name match " "the given regular expression"), cl::Hidden, cl::location(PassRemarksOptLoc), cl::ValueRequired, cl::ZeroOrMore); // -pass-remarks-missed // Command line flag to enable emitOptimizationRemarkMissed() static cl::opt<PassRemarksOpt, true, cl::parser<std::string>> PassRemarksMissed( "pass-remarks-missed", cl::value_desc("pattern"), cl::desc("Enable missed optimization remarks from passes whose name match " "the given regular expression"), cl::Hidden, cl::location(PassRemarksMissedOptLoc), cl::ValueRequired, cl::ZeroOrMore); // -pass-remarks-analysis // Command line flag to enable emitOptimizationRemarkAnalysis() static cl::opt<PassRemarksOpt, true, cl::parser<std::string>> PassRemarksAnalysis( "pass-remarks-analysis", cl::value_desc("pattern"), cl::desc( "Enable optimization analysis remarks from passes whose name match " "the given regular expression"), cl::Hidden, cl::location(PassRemarksAnalysisOptLoc), cl::ValueRequired, cl::ZeroOrMore); } int llvm::getNextAvailablePluginDiagnosticKind() { static std::atomic<int> PluginKindID(DK_FirstPluginKind); return ++PluginKindID; } const char *OptimizationRemarkAnalysis::AlwaysPrint = ""; DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I, const Twine &MsgStr, DiagnosticSeverity Severity) : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(0), MsgStr(MsgStr), Instr(&I) { if (const MDNode *SrcLoc = I.getMetadata("srcloc")) { if (SrcLoc->getNumOperands() != 0) if (const auto *CI = mdconst::dyn_extract<ConstantInt>(SrcLoc->getOperand(0))) LocCookie = CI->getZExtValue(); } } void DiagnosticInfoInlineAsm::print(DiagnosticPrinter &DP) const { DP << getMsgStr(); if (getLocCookie()) DP << " at line " << getLocCookie(); } void DiagnosticInfoResourceLimit::print(DiagnosticPrinter &DP) const { DP << getResourceName() << " limit"; if (getResourceLimit() != 0) DP << " of " << getResourceLimit(); DP << " exceeded (" << getResourceSize() << ") in " << getFunction(); } void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter &DP) const { DP << "ignoring debug info with an invalid version (" << getMetadataVersion() << ") in " << getModule(); } void DiagnosticInfoIgnoringInvalidDebugMetadata::print( DiagnosticPrinter &DP) const { DP << "ignoring invalid debug info in " << getModule().getModuleIdentifier(); } void DiagnosticInfoSampleProfile::print(DiagnosticPrinter &DP) const { if (!FileName.empty()) { DP << getFileName(); if (LineNum > 0) DP << ":" << getLineNum(); DP << ": "; } DP << getMsg(); } void DiagnosticInfoPGOProfile::print(DiagnosticPrinter &DP) const { if (getFileName()) DP << getFileName() << ": "; DP << getMsg(); } DiagnosticLocation::DiagnosticLocation(const DebugLoc &DL) { if (!DL) return; Filename = DL->getFilename(); Line = DL->getLine(); Column = DL->getColumn(); } DiagnosticLocation::DiagnosticLocation(const DISubprogram *SP) { if (!SP) return; Filename = SP->getFilename(); Line = SP->getScopeLine(); Column = 0; } void DiagnosticInfoWithLocationBase::getLocation(StringRef *Filename, unsigned *Line, unsigned *Column) const { *Filename = Loc.getFilename(); *Line = Loc.getLine(); *Column = Loc.getColumn(); } const std::string DiagnosticInfoWithLocationBase::getLocationStr() const { StringRef Filename("<unknown>"); unsigned Line = 0; unsigned Column = 0; if (isLocationAvailable()) getLocation(&Filename, &Line, &Column); return (Filename + ":" + Twine(Line) + ":" + Twine(Column)).str(); } DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, const Value *V) : Key(Key) { if (auto *F = dyn_cast<Function>(V)) { if (DISubprogram *SP = F->getSubprogram()) Loc = SP; } else if (auto *I = dyn_cast<Instruction>(V)) Loc = I->getDebugLoc(); // Only include names that correspond to user variables. FIXME: we should use // debug info if available to get the name of the user variable. if (isa<llvm::Argument>(V) || isa<GlobalValue>(V)) Val = GlobalValue::getRealLinkageName(V->getName()); else if (isa<Constant>(V)) { raw_string_ostream OS(Val); V->printAsOperand(OS, /*PrintType=*/false); } else if (auto *I = dyn_cast<Instruction>(V)) Val = I->getOpcodeName(); } DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, const Type *T) : Key(Key) { raw_string_ostream OS(Val); OS << *T; } DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, int N) : Key(Key), Val(itostr(N)) {} DiagnosticInfoOptimizationBase::Argument::Argument(StringRef Key, unsigned N) : Key(Key), Val(utostr(N)) {} void DiagnosticInfoOptimizationBase::print(DiagnosticPrinter &DP) const { DP << getLocationStr() << ": " << getMsg(); if (Hotness) DP << " (hotness: " << *Hotness << ")"; } OptimizationRemark::OptimizationRemark(const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion) : DiagnosticInfoIROptimization( DK_OptimizationRemark, DS_Remark, PassName, RemarkName, *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {} OptimizationRemark::OptimizationRemark(const char *PassName, StringRef RemarkName, Instruction *Inst) : DiagnosticInfoIROptimization(DK_OptimizationRemark, DS_Remark, PassName, RemarkName, *Inst->getParent()->getParent(), Inst->getDebugLoc(), Inst->getParent()) {} bool OptimizationRemark::isEnabled(StringRef PassName) { return PassRemarksOptLoc.Pattern && PassRemarksOptLoc.Pattern->match(PassName); } OptimizationRemarkMissed::OptimizationRemarkMissed( const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion) : DiagnosticInfoIROptimization( DK_OptimizationRemarkMissed, DS_Remark, PassName, RemarkName, *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {} OptimizationRemarkMissed::OptimizationRemarkMissed(const char *PassName, StringRef RemarkName, const Instruction *Inst) : DiagnosticInfoIROptimization(DK_OptimizationRemarkMissed, DS_Remark, PassName, RemarkName, *Inst->getParent()->getParent(), Inst->getDebugLoc(), Inst->getParent()) {} bool OptimizationRemarkMissed::isEnabled(StringRef PassName) { return PassRemarksMissedOptLoc.Pattern && PassRemarksMissedOptLoc.Pattern->match(PassName); } OptimizationRemarkAnalysis::OptimizationRemarkAnalysis( const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion) : DiagnosticInfoIROptimization( DK_OptimizationRemarkAnalysis, DS_Remark, PassName, RemarkName, *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {} OptimizationRemarkAnalysis::OptimizationRemarkAnalysis(const char *PassName, StringRef RemarkName, const Instruction *Inst) : DiagnosticInfoIROptimization(DK_OptimizationRemarkAnalysis, DS_Remark, PassName, RemarkName, *Inst->getParent()->getParent(), Inst->getDebugLoc(), Inst->getParent()) {} OptimizationRemarkAnalysis::OptimizationRemarkAnalysis( enum DiagnosticKind Kind, const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion) : DiagnosticInfoIROptimization(Kind, DS_Remark, PassName, RemarkName, *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {} bool OptimizationRemarkAnalysis::isEnabled(StringRef PassName) { return PassRemarksAnalysisOptLoc.Pattern && PassRemarksAnalysisOptLoc.Pattern->match(PassName); } void DiagnosticInfoMIRParser::print(DiagnosticPrinter &DP) const { DP << Diagnostic; } void llvm::emitOptimizationRemark(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg) { Ctx.diagnose(OptimizationRemark(PassName, Fn, Loc, Msg)); } void llvm::emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg) { Ctx.diagnose(OptimizationRemarkMissed(PassName, Fn, Loc, Msg)); } void llvm::emitOptimizationRemarkAnalysis(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg) { Ctx.diagnose(OptimizationRemarkAnalysis(PassName, Fn, Loc, Msg)); } void llvm::emitOptimizationRemarkAnalysisFPCommute( LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg) { Ctx.diagnose(OptimizationRemarkAnalysisFPCommute(PassName, Fn, Loc, Msg)); } void llvm::emitOptimizationRemarkAnalysisAliasing(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg) { Ctx.diagnose(OptimizationRemarkAnalysisAliasing(PassName, Fn, Loc, Msg)); } DiagnosticInfoOptimizationFailure::DiagnosticInfoOptimizationFailure( const char *PassName, StringRef RemarkName, const DiagnosticLocation &Loc, const Value *CodeRegion) : DiagnosticInfoIROptimization( DK_OptimizationFailure, DS_Warning, PassName, RemarkName, *cast<BasicBlock>(CodeRegion)->getParent(), Loc, CodeRegion) {} bool DiagnosticInfoOptimizationFailure::isEnabled() const { // Only print warnings. return getSeverity() == DS_Warning; } void DiagnosticInfoUnsupported::print(DiagnosticPrinter &DP) const { std::string Str; raw_string_ostream OS(Str); OS << getLocationStr() << ": in function " << getFunction().getName() << ' ' << *getFunction().getFunctionType() << ": " << Msg << '\n'; OS.flush(); DP << Str; } void DiagnosticInfoISelFallback::print(DiagnosticPrinter &DP) const { DP << "Instruction selection used fallback path for " << getFunction(); } DiagnosticInfoOptimizationBase &DiagnosticInfoOptimizationBase:: operator<<(StringRef S) { Args.emplace_back(S); return *this; } DiagnosticInfoOptimizationBase &DiagnosticInfoOptimizationBase:: operator<<(Argument A) { Args.push_back(std::move(A)); return *this; } DiagnosticInfoOptimizationBase &DiagnosticInfoOptimizationBase:: operator<<(setIsVerbose V) { IsVerbose = true; return *this; } DiagnosticInfoOptimizationBase &DiagnosticInfoOptimizationBase:: operator<<(setExtraArgs EA) { FirstExtraArgIndex = Args.size(); return *this; } std::string DiagnosticInfoOptimizationBase::getMsg() const { std::string Str; raw_string_ostream OS(Str); for (const DiagnosticInfoOptimizationBase::Argument &Arg : make_range(Args.begin(), FirstExtraArgIndex == -1 ? Args.end() : Args.begin() + FirstExtraArgIndex)) OS << Arg.Val; return OS.str(); }
[ "krzysztof.siejkowski@polidea.com" ]
krzysztof.siejkowski@polidea.com
a7194ce521dbf98de89240229a25d75854ca2aa2
242e399bc0a308a84580306b09b0a43ee6504988
/GameComponents/GraphicComponent/TextureFactory.cpp
c3fdbd33a063637c20faeedc62f49b949ab3b6b7
[]
no_license
randydom/Caesar-Game-Engine-2
499de5f6d0d0b35ad738af2511c2c80a3f625400
ea297697dcf09a47ac5d6e5ebb1bb1e32c03f089
refs/heads/master
2020-04-24T22:52:22.975241
2015-05-09T17:58:53
2015-05-09T17:58:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
749
cpp
#include "TextureFactory.h" #include "Resource.h" #include "BasicTexture.h" #include <Components.h> #include <GenerateGUID.h> std::string TextureFactory::Create(std::string texture) { std::string ID = CHL::GenerateGUID(); Components::Graphic->SubmitMessage([=]() { std::lock_guard<std::mutex> lock(Components::Graphic->Mutex()); std::shared_ptr<BasicTexture> newObject = BasicTexture::Spawn(texture); Resource::TextureList[ID] = newObject; return Message::Status::Complete; }); return ID; } void TextureFactory::Release(std::string ID) { Components::Graphic->SubmitMessage([=]() { std::lock_guard<std::mutex> lock(Components::Graphic->Mutex()); Resource::TextureList.erase(ID); return Message::Status::Complete; }); }
[ "mmajeed668@gmail.com" ]
mmajeed668@gmail.com
f838933564cdef869ee4e41102c84389d297db2b
55617991c3bb62f5c8a0122b7f8cd94374258749
/cube_files/random_led2.ino
af08fd86abe95ba9cee3349151ebb9a5fabe3233
[]
no_license
sergio-roldan/tesis
4489fcdc646bac8a948977c5c2849f61637d7df9
47c836a090b9d72d7b71fe18f8e188082930e94c
refs/heads/master
2021-01-16T23:18:48.892235
2017-03-02T23:55:32
2017-03-02T23:55:32
82,860,375
0
0
null
2017-03-02T23:55:33
2017-02-22T22:49:29
Java
UTF-8
C++
false
false
1,464
ino
#include <Rainbowduino.h> #include <util/delay.h> /** * Rainbowduino implements a second function to set a pixel in a given (Z,X,Y) * position with a desired colour. The difference with the function exposed * in the last exercise lies on the way the colour is introduced in the * function. This time, the colour is defined as a single 24-bit number where * the first 8 bits represent the level of R, the second 8 bits represent the * level of G and the last 8 bits the level of B. * * Rb.setPixelZXY(z, x, y, RGB); * * Develop a sketch to set 3 LEDs in the Cube every 2 seconds, in 3 random * positions and 3 different random colours using the function described * above. */ void setup() { Rb.init(); // Initialize the Rainbowduino driver } int z1,x1,y1; int z2,x2,y2; int z3,x3,y3; long rgb1; long rgb2; long rgb3; void loop() { // Random position 1 z1 = random(0,4); x1 = random(0,4); y1 = random(0,4); // Random position 2 z2 = random(0,4); x2 = random(0,4); y2 = random(0,4); // Random position 3 z3 = random(0,4); x3 = random(0,4); y3 = random(0,4); // Random colours rgb1 = random(0,0xFFFFFF); rgb2 = random(0,0xFFFFFF); rgb3 = random(0,0xFFFFFF); Rb.setPixelZXY(z1, x1, y1, rgb1); // Set the random LED1 Rb.setPixelZXY(z2, x2, y2, rgb2); // Set the random LED2 Rb.setPixelZXY(z3, x3, y3, rgb3); // Set the random LED3 _delay_ms(2000); // Introduce a delay of 2 seconds Rb.blankDisplay(); // Switch off the LEDs }
[ "sergio.roldan.gomez@gmail.com" ]
sergio.roldan.gomez@gmail.com
5f246d720a98b005f293ce5e78a4336f3f3f4541
4b6116116bb1195e916ae2d83f6fa8f654163d9f
/program/src/main/RabinGameSolver.cpp
8847c4c618cac0d699a39e1c4a9cf50b94fd2b9b
[]
no_license
filipbartek/rabin
42dffc0e543f05fd56cd3ec3c791b600ad00cb3f
7f6ea3edf4ff82226826c88d960cb95947e48dfd
refs/heads/master
2021-01-10T20:43:59.436856
2014-12-29T20:33:56
2014-12-29T20:33:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
#include "RabinGameSolver.hpp" #include <algorithm> // fill #include <vector> RabinGameSolver::RabinGameSolver() {} RabinGameSolver::RabinGameSolver(const RabinGame& game) : game_(game), winning_set_(n()), strategy_(n(), n()), winning_set_solved_(false), strategy_solved_(false) {} RabinGameSolver::~RabinGameSolver() {} void RabinGameSolver::game(const RabinGame& game) { game_ = game; winning_set_.resize(n()); strategy_.resize(n()); Unsolve(); } void RabinGameSolver::Unsolve() { winning_set_.reset(); winning_set_solved_ = false; fill(strategy_.begin(), strategy_.end(), n()); strategy_solved_ = false; update_game(); } const RabinGameSolver::BitsetType/*n*/& RabinGameSolver::winning_set() { if (!winning_set_solved_) Solve(true, false); return winning_set_; } const std::vector<RabinGameSolver::NType>/*n*/& RabinGameSolver::strategy() { if (!strategy_solved_) Solve(false, true); return strategy_; } RabinGameSolver::NType RabinGameSolver::n() const { return game_.n(); } RabinGameSolver::KType RabinGameSolver::k() const { return game_.k(); }
[ "filip.bartek@hotmail.com" ]
filip.bartek@hotmail.com
76362420ffbdee31539c64c31da1edf6630989a4
3b36d2e386310d322b456223ec27846cc8dd86e8
/Bai 1/Main.cpp
0a0d074f8c9341610f5d6889d16eaac571f3621c
[]
no_license
1712845/QuanLiDoiBong
14f3afb8d3fba97160a0894b1a38b41058326285
527948a2151113abf5870905aed563aed3e4eed7
refs/heads/master
2022-12-02T06:02:05.960776
2020-08-15T23:43:14
2020-08-15T23:43:14
287,842,194
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include"CauThu.h" int main() { cout << "An phim 0 de thoat!\n"; cout << "An phim 1 nhap va xuat ra doi hinh (Nhap 23 cau thu)\n "; cout << "An phim 2 de nhap va thong tin cau thu vao file txt (ten file = so ao cau thu)\n"; cout << "An phim 3 de doc thong tin cau thu da duoc luu va xuat ra doi hinh\n "; LuaChon(); system("pause"); return 0; }
[ "nntrung0403@gmail.com" ]
nntrung0403@gmail.com
0e1bb26770f392e4a140db664ac7c4bd1fd970a0
fe5e4748939432af1d691f9d5837206fbf6c6c2f
/C++/bi_color.cpp
63f69efa59f39c4a8c737d1b91fd6d5b7e67d674
[]
no_license
soadkhan/My-Code
e0ebe0898d68df983e8c41e56633780d6ac22c39
72fc258cdbf08d86f20a565afe371713e8e8bc39
refs/heads/master
2021-01-23T03:27:34.181019
2017-03-24T14:42:15
2017-03-24T14:42:15
86,077,758
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
#include<bits/stdc++.h> using namespace std; typedef long long int lld; typedef long int ld; map<ld,ld>visited; bool bfs(ld start,map<ld,vector<ld> >graph){ visited.clear(); queue<ld>lists; lists.push(start); visited[start] = 1; while(lists.empty()!=true){ ld hand = lists.front(); lists.pop(); ld l = graph[hand].size(); for(ld i =0;i<l;i++){ if(visited[graph[hand][i]] == 0){ if(visited[hand] == 1) visited[graph[hand][i]] = 2; if(visited[hand] == 2) visited[graph[hand][i]] = 1; lists.push(graph[hand][i]); } if(visited[hand] == visited[graph[hand][i]]) return false; } } return true ; } int main(){ //freopen("uva.txt","rt",stdin); //freopen("uva_out.txt","wt",stdout); ld n,l; while(cin>>n){ if(n==0) return 0; cin>>l; map<ld, vector<ld> > graph; while(l--){ ld a,b; cin>>a>>b; graph[a].push_back(b); graph[b].push_back(a); } if(bfs(0,graph)) cout<<"BICOLORABLE."<<endl; else cout<<"NOT BICOLORABLE."<<endl; } return 0; }
[ "khancse5914@gmail.com" ]
khancse5914@gmail.com
ad9025bab667e0aac64a199498190e9bcc5ae430
5902619843a0205a7031acb2c5ef03e382eb8384
/DES/RoundKeyGenerator.h
cbe89c2f26396560088247a77838aa46e107d322
[]
no_license
Meliser/DES
18dad90979dc04fab9ebf8a4baa7e5b7664211cc
9b791ec10eb5567a0ff17df54c80df63fe48b1f7
refs/heads/master
2020-06-12T08:34:28.895591
2019-06-28T09:31:42
2019-06-28T09:31:42
194,246,672
0
0
null
null
null
null
UTF-8
C++
false
false
580
h
#pragma once #include <bitset> #include <array> #include "desUtility.h" using std::bitset; using std::array; namespace des { class RoundKeyGenerator { public: void initializeC0D0(const bitset<keySize> &bits); void generateRoundKeys(size_t rounds); const bitset<roundKeySize>& getRoundKey(size_t index) const { return roundKeys[index]; } private: const static char PC1[PC1Size]; const static char PC2[PC2Size]; bitset<PC1Size / 2> c0; bitset<PC1Size / 2> d0; array<bitset<roundKeySize>, rounds> roundKeys; size_t countCurrentShift(size_t round); }; }
[ "mitya.korneev@mail.ru" ]
mitya.korneev@mail.ru
492c56b0763c7b3a9e2ae54cf79e09b673ae090f
384a3e35f780ec8af15ebc13fa9e5d6df84f59e9
/EPAF/debug/moc_connexionmainmenu.cpp
6c7546bcbcabf137581cf5f22b30f4cc7768729e
[]
no_license
EPAFprojet/Projet_V2
91071c0b57e9c2bebf34174d7e7fc1edddaa2f5d
19e223c5d922ccd5f9767510f4aa53884e4c7090
refs/heads/master
2021-01-19T11:14:42.804330
2017-04-13T13:27:16
2017-04-13T13:27:16
87,944,645
0
0
null
null
null
null
UTF-8
C++
false
false
2,820
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'connexionmainmenu.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../connexionmainmenu.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'connexionmainmenu.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.8.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_connexionmainmenu_t { QByteArrayData data[1]; char stringdata0[18]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_connexionmainmenu_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_connexionmainmenu_t qt_meta_stringdata_connexionmainmenu = { { QT_MOC_LITERAL(0, 0, 17) // "connexionmainmenu" }, "connexionmainmenu" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_connexionmainmenu[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void connexionmainmenu::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject connexionmainmenu::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_connexionmainmenu.data, qt_meta_data_connexionmainmenu, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *connexionmainmenu::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *connexionmainmenu::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_connexionmainmenu.stringdata0)) return static_cast<void*>(const_cast< connexionmainmenu*>(this)); return QMainWindow::qt_metacast(_clname); } int connexionmainmenu::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "naspirault@gmail.com" ]
naspirault@gmail.com
7684ebec7715ba991408febe5916273c0dce5ca4
975d3e1b3d347d5c74775e12d21a2865c118301d
/AdvantureIsland/GlobalParameter.h
dcbb999debecb8a6e15654672378a72d541fba87
[]
no_license
Frozenmad/AdvantureIsland
1818da160fed5744e724c2d0fcf586a552fdd618
41931d642f8e81eb7c927e7eae39c5f1f3bf73dd
refs/heads/master
2020-03-24T13:12:08.042589
2018-08-22T11:47:56
2018-08-22T11:47:56
142,738,354
0
0
null
null
null
null
UTF-8
C++
false
false
1,515
h
#pragma once #include <cstdlib> #include <mutex> #include <set> #include "PlaceBase.h" #include "PickupBase.h" #include "InteractiveBase.h" #include "land.h" using namespace std; enum EWeather { Sunny, Rainy, Windy }; template <class T> class SafeSet { private: mutex setKeeper; public: set<T> inner; SafeSet() :inner(), setKeeper() {} void AddElement(T ele); void RemoveElement(T ele); void _unsafe_add(T ele) { inner.insert(ele); } void _unsafe_remove(T ele) { inner.remove(inner.find(ele)); } void lockSet() { setKeeper.lock(); } void unlockSet() { setKeeper.unlock(); } ~SafeSet() { for (auto pointer : inner) delete pointer; } }; template<class T> inline void SafeSet<T>::AddElement(T ele) { setKeeper.lock(); inner.insert(ele); setKeeper.unlock(); } template<class T> inline void SafeSet<T>::RemoveElement(T ele) { setKeeper.lock(); auto It = inner.find(ele); if (It != inner.end()) inner.erase(It); setKeeper.unlock(); } static class GlobalParameter { public: static float SickHPDecreaseRate; static float HungryStateTurningRate; static float HungryRefreshRate; static float MaxHealthPoint; static float HealthyHPIncreaseRate; static EWeather GlobalWeather; static mutex OutputMutex; static void ChangeWeather(); static void OutputLock(); static void OutputUnLock(); static SafeSet<PlaceBase*> PlaceObjectVec; static SafeSet<PickupBase*> PickupObjectSet; static SafeSet<class InteractiveBase *> InteractiveObjectSet; static vector<vector<Land>> Map; } GlobalParam;
[ "Frozenmad2015@outlook.com" ]
Frozenmad2015@outlook.com
2bbd7752c2fca6b10fe66328d419743356e2eb8d
280b3a71a76defbc2a4df66db7f38b48eff9ba32
/3rdparty/dear-imgui/imgui.cpp
99e7d2b811b5f5d6d0ae7d645e35b20c9593782c
[ "MIT" ]
permissive
yangfengzzz/DigitalRender
46cc8956767bcc8db28eb3b3513e05af2c1b235a
c8220fe2e59b40d24fe3b33589b4b1c5de5cd3f2
refs/heads/main
2023-02-01T18:01:16.587795
2020-12-17T13:36:05
2020-12-17T13:36:05
309,258,567
1
0
null
null
null
null
UTF-8
C++
false
false
535,225
cpp
// dear imgui, v1.80 WIP // (main code and documentation) // Help: // - Read FAQ at http://dearimgui.org/faq // - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. // - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that. // Read imgui.cpp for details, links and comments. // Resources: // - FAQ http://dearimgui.org/faq // - Homepage & latest https://github.com/ocornut/imgui // - Releases & changelog https://github.com/ocornut/imgui/releases // - Gallery https://github.com/ocornut/imgui/issues/3488 (please post your screenshots/video there!) // - Glossary https://github.com/ocornut/imgui/wiki/Glossary // - Wiki https://github.com/ocornut/imgui/wiki // - Issues & support https://github.com/ocornut/imgui/issues // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // See LICENSE.txt for copyright and licensing details (standard MIT License). // This library is free but needs your support to sustain development and maintenance. // Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.org". // Individuals: you can support continued development via donations. See docs/README or web page. // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library. // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you // to a better solution or official support for them. /* Index of this file: DOCUMENTATION - MISSION STATEMENT - END-USER GUIDE - PROGRAMMER GUIDE - READ FIRST - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE - HOW A SIMPLE APPLICATION MAY LOOK LIKE - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ) - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer) CODE (search for "[SECTION]" in the code to find them) // [SECTION] INCLUDES // [SECTION] FORWARD DECLARATIONS // [SECTION] CONTEXT AND MEMORY ALLOCATORS // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) // [SECTION] MISC HELPERS/UTILITIES (Geometry functions) // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) // [SECTION] MISC HELPERS/UTILITIES (File functions) // [SECTION] MISC HELPERS/UTILITIES (ImText* functions) // [SECTION] MISC HELPERS/UTILITIES (Color functions) // [SECTION] ImGuiStorage // [SECTION] ImGuiTextFilter // [SECTION] ImGuiTextBuffer // [SECTION] ImGuiListClipper // [SECTION] STYLING // [SECTION] RENDER HELPERS // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) // [SECTION] ERROR CHECKING // [SECTION] LAYOUT // [SECTION] SCROLLING // [SECTION] TOOLTIPS // [SECTION] POPUPS // [SECTION] KEYBOARD/GAMEPAD NAVIGATION // [SECTION] DRAG AND DROP // [SECTION] LOGGING/CAPTURING // [SECTION] SETTINGS // [SECTION] PLATFORM DEPENDENT HELPERS // [SECTION] METRICS/DEBUGGER WINDOW */ //----------------------------------------------------------------------------- // DOCUMENTATION //----------------------------------------------------------------------------- /* MISSION STATEMENT ================= - Easy to use to create code-driven and data-driven tools. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. - Easy to hack and improve. - Minimize setup and maintenance. - Minimize state storage on user side. - Portable, minimize dependencies, run on target (consoles, phones, etc.). - Efficient runtime and memory consumption. Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes: - Doesn't look fancy, doesn't animate. - Limited layout features, intricate layouts are typically crafted in code. END-USER GUIDE ============== - Double-click on title bar to collapse window. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin(). - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents). - Click and drag on any empty space to move window. - TAB/SHIFT+TAB to cycle through keyboard editable fields. - CTRL+Click on a slider or drag box to input value as text. - Use mouse wheel to scroll. - Text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump. - CTRL+Shift+Left/Right to select words. - CTRL+A our Double-Click to select all. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/ - CTRL+Z,CTRL+Y to undo/redo. - ESCAPE to revert text to its original value. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) - Controls are automatically adjusted for OSX to match standard OSX text editing operations. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW PROGRAMMER GUIDE ================ READ FIRST ---------- - Remember to read the FAQ (https://www.dearimgui.org/faq) - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features. - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build. - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori). You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in the FAQ. - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances. For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI, where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches. - Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right. - This codebase is also optimized to yield decent performances with typical "Debug" builds settings. - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected). If you get an assert, read the messages and comments around the assert. - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that. However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!). HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI ---------------------------------------------- - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h) - Or maintain your own branch where you have imconfig.h modified. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. Please report any issue to the GitHub page! - Try to keep your copy of dear imgui reasonably up to date. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE --------------------------------------------------------------- - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. - In the majority of cases you should be able to use unmodified backends files available in the examples/ folder. - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system. It is recommended you build and statically link the .cpp files as part of your project and NOT as shared library (DLL). - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. All rendering information are stored into command-lists that you will retrieve after calling ImGui::Render(). - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code. - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder. HOW A SIMPLE APPLICATION MAY LOOK LIKE -------------------------------------- EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder). The sub-folders in examples/ contains examples applications following this structure. // Application init: create a dear imgui context, setup some options, load fonts ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. // TODO: Fill optional fields of the io structure later. // TODO: Load TTF/OTF fonts if you don't want to use the default font. // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp) ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Application main loop while (true) { // Feed inputs to dear imgui, start new frame ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); // Any application code here ImGui::Text("Hello, world!"); // Render dear imgui into screen ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); g_pSwapChain->Present(1, 0); } // Shutdown ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE // Application init: create a dear imgui context, setup some options, load fonts ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. // TODO: Fill optional fields of the io structure later. // TODO: Load TTF/OTF fonts if you don't want to use the default font. // Build and load the texture atlas into a texture // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer) int width, height; unsigned char* pixels = NULL; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // At this point you've got the texture data and you need to upload that your your graphic system: // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'. // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32) io.Fonts->TexID = (void*)texture; // Application main loop while (true) { // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc. // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends) io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds) io.DisplaySize.x = 1920.0f; // set the current display width io.DisplaySize.y = 1280.0f; // set the current display height here io.MousePos = my_mouse_pos; // set the mouse position io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states io.MouseDown[1] = my_mouse_buttons[1]; // Call NewFrame(), after this point you can use ImGui::* functions anytime // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use Dear ImGui everywhere) ImGui::NewFrame(); // Most of your application code here ImGui::Text("Hello, world!"); MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); MyGameRender(); // may use any Dear ImGui functions as well! // Render dear imgui, swap buffers // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code) ImGui::EndFrame(); ImGui::Render(); ImDrawData* draw_data = ImGui::GetDrawData(); MyImGuiRenderFunction(draw_data); SwapBuffers(); } // Shutdown ImGui::DestroyContext(); To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest your application, you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! Please read the FAQ and example applications for details about this! HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE --------------------------------------------- The backends in impl_impl_XXX.cpp files contains many working implementations of a rendering function. void void MyImGuiRenderFunction(ImDrawData* draw_data) { // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear ImGui for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { // The texture for the draw call is specified by pcmd->TextureId. // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization. MyEngineBindTexture((MyTexture*)pcmd->TextureId); // We are using scissoring to clip some objects. All low-level graphics API should supports it. // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches // (some elements visible outside their bounds) but you can fix that once everything else works! // - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize) // In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize. // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github), // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space. // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min) ImVec2 pos = draw_data->DisplayPos; MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y)); // Render 'pcmd->ElemCount/3' indexed triangles. // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer); } idx_buffer += pcmd->ElemCount; } } } USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS ------------------------------------------ - The gamepad/keyboard navigation is fairly functional and keeps being improved. - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse! - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. - Keyboard: - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from: - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used). - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions. Please reach out if you think the game vs navigation input sharing could be improved. - Gamepad: - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values: 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks. - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone. Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.). - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW. - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved. - Mouse: - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback. - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard. - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements. When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that. (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!) (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want to set a boolean to ignore your other external mouse positions until the external source is moved again.) API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix. Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code. When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API. - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/. - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018): - io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend - ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow) - ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) - ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT - ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT - removed redirecting functions names that were marked obsolete in 1.61 (May 2018): - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision. - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter. - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed). - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently). - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton. - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory. - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result. - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now! - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar(). replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags). worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions: - if you omitted the 'power' parameter (likely!), you are not affected. - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct. - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f. see https://github.com/ocornut/imgui/issues/3361 for all details. kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version were removed directly as they were most unlikely ever used. for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`. - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime. - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems. - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79] - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017. - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular(). - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more. - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead. - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value. - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017): - ShowTestWindow() -> use ShowDemoWindow() - IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow) - IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) - SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f) - GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing() - ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg - ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap - IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was the vaguely documented and rarely if ever used). Instead we added an explicit PrimUnreserve() API. - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it). - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency. - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency. - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017): - Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed - IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) - AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding() - SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f) - ImFont::Glyph -> use ImFontGlyph - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function. if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix. The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay). If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you. - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete). - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete). - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71. - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering. This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows. Please reach out if you are affected. - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete). - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrary small value! - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete). - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files. - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete). - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h. If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths. - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427) - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp. NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED. Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions. - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent). - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete). - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly). - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature. - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports. when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call. in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details. - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format. To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code. If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them. - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format", consistent with other functions. Kept redirection functions (will obsolete). - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value. - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch). - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now. - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums. - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment. - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display. - 2018/02/07 (1.60) - reorganized context handling to be more explicit, - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END. - removed Shutdown() function, as DestroyContext() serve this purpose. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts. - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete). - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete). - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData. - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete). - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame. - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete). - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete). - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete). - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete). - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete). - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed. - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up. Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency. - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting. IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly) IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow) IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior] - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead! - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete). - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete). - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)! - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete). - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete). - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))' - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color: ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. this necessary change will break your rendering function! the fix should be very easy. sorry for that :( - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. - the signature of the io.RenderDrawListsFn handler has changed! old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount' ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'. - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. - old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..]; - new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->TexId = YourTexIdentifier; you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation. - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes FREQUENTLY ASKED QUESTIONS (FAQ) ================================ Read all answers online: https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) Read all answers locally (with a text editor or ideally a Markdown viewer): docs/FAQ.md Some answers are copied down here to facilitate searching in code. Q&A: Basics =========== Q: Where is the documentation? A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++. - Run the examples/ and explore them. - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. - The demo covers most features of Dear ImGui, so you can read the code and see its output. - See documentation and comments at the top of imgui.cpp + effectively imgui.h. - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder to explain how to integrate Dear ImGui with your own engine/application. - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links. - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful. - Your programming IDE is your friend, find the type or function declaration to find comments associated to it. Q: What is this library called? Q: Which version should I get? >> This library is called "Dear ImGui", please don't call it "ImGui" :) >> See https://www.dearimgui.org/faq for details. Q&A: Integration ================ Q: How to get started? A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt. Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application? A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! >> See https://www.dearimgui.org/faq for fully detailed answer. You really want to read this. Q. How can I enable keyboard controls? Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) Q: I integrated Dear ImGui in my engine and little squares are showing instead of text.. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries.. >> See https://www.dearimgui.org/faq Q&A: Usage ---------- Q: Why is my widget not reacting when I click on it? Q: How can I have widgets with an empty label? Q: How can I have multiple widgets with the same label? Q: How can I display an image? What is ImTextureID, how does it works? Q: How can I use my own math types instead of ImVec2/ImVec4? Q: How can I interact with standard C++ types (such as std::string and std::vector)? Q: How can I display custom shapes? (using low-level ImDrawList API) >> See https://www.dearimgui.org/faq Q&A: Fonts, Text ================ Q: How should I handle DPI in my application? Q: How can I load a different font than the default? Q: How can I easily use icons in my application? Q: How can I load multiple fonts? Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md Q&A: Concerns ============= Q: Who uses Dear ImGui? Q: Can you create elaborate/serious tools with Dear ImGui? Q: Can you reskin the look of Dear ImGui? Q: Why using C++ (as opposed to C)? >> See https://www.dearimgui.org/faq Q&A: Community ============== Q: How can I help? A: - Businesses: please reach out to "contact AT dearimgui.org" if you work in a place using Dear ImGui! We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts. This is among the most useful thing you can do for Dear ImGui. With increased funding we can hire more people working on this project. - Individuals: you can support continued development via PayPal donations. See README. - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt and see how you want to help and can help! - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/3488). Visuals are ideal as they inspire other programmers. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately). */ //------------------------------------------------------------------------- // [SECTION] INCLUDES //------------------------------------------------------------------------- #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #ifndef IMGUI_DISABLE #ifndef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS #endif #include "imgui_internal.h" // System includes #include <ctype.h> // toupper #include <stdio.h> // vsnprintf, sscanf, printf #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif // [Windows] OS specific includes (optional) #if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) #define IMGUI_DISABLE_WIN32_FUNCTIONS #endif #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #ifndef __MINGW32__ #include <Windows.h> // _wfopen, OpenClipboard #else #include <windows.h> #endif #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions #define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS #define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS #endif #endif // [Apple] OS specific includes #if defined(__APPLE__) #include <TargetConditionals.h> #endif // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4201) // nonstandard extension used: nameless struct/union #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types #endif #endif // Clang/GCC warnings with -Weverything #if defined(__clang__) #if __has_warning("-Wunknown-warning-option") #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great! #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx' #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness #pragma clang diagnostic ignored "-Wformat-pedantic" // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type 'int' #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0 #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision #elif defined(__GNUC__) // We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false #pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif // Debug options #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window #define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower) // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend) static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow(). static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS //------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window); static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list); static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window); static ImRect GetViewportRect(); // Settings static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf); // Platform Dependents default implementation for IO functions static const char* GetClipboardTextFn_DefaultImpl(void* user_data); static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); namespace ImGui { // Navigation static void NavUpdate(); static void NavUpdateWindowing(); static void NavUpdateWindowingOverlay(); static void NavUpdateMoveResult(); static void NavUpdateInitResult(); static float NavUpdatePageUpPageDown(); static inline void NavUpdateAnyRequestFlag(); static void NavEndFrame(); static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand); static void NavApplyItemToResult(ImGuiNavMoveResult* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel); static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id); static ImVec2 NavCalcPreferredRefPos(); static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); static int FindWindowFocusIndex(ImGuiWindow* window); // Error Checking static void ErrorCheckNewFrameSanityChecks(); static void ErrorCheckEndFrameSanityChecks(); // Misc static void UpdateSettings(); static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateTabFocus(); static void UpdateDebugToolItemPicker(); static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect); static void RenderWindowOuterBorders(ImGuiWindow* window); static void 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); static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); } //----------------------------------------------------------------------------- // [SECTION] CONTEXT AND MEMORY ALLOCATORS //----------------------------------------------------------------------------- // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL. // ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext(). // 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call // SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading. // In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into. // 2) Important: Dear ImGui functions are not thread-safe because of this pointer. // If you want thread-safety to allow N threads to access N different contexts, you can: // - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h: // struct ImGuiContext; // extern thread_local ImGuiContext* MyImGuiTLS; // #define GImGui MyImGuiTLS // And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword. // - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace. #ifndef GImGui ImGuiContext* GImGui = NULL; #endif // Memory Allocator functions. Use SetAllocatorFunctions() to change them. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file. // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); } static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); } #else static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; } static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); } #endif static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper; static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper; static void* GImAllocatorUserData = NULL; //----------------------------------------------------------------------------- // [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) //----------------------------------------------------------------------------- ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. WindowMinSize = ImVec2(32,32); // Minimum window size WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left. ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). ScrollbarSize = 14.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected. ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows. DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. AntiAliasedFill = true; // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.). CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. CircleSegmentMaxError = 1.60f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry. // Default theme ImGui::StyleColorsDark(this); } // To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you. // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. void ImGuiStyle::ScaleAllSizes(float scale_factor) { WindowPadding = ImFloor(WindowPadding * scale_factor); WindowRounding = ImFloor(WindowRounding * scale_factor); WindowMinSize = ImFloor(WindowMinSize * scale_factor); ChildRounding = ImFloor(ChildRounding * scale_factor); PopupRounding = ImFloor(PopupRounding * scale_factor); FramePadding = ImFloor(FramePadding * scale_factor); FrameRounding = ImFloor(FrameRounding * scale_factor); ItemSpacing = ImFloor(ItemSpacing * scale_factor); ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor); TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor); IndentSpacing = ImFloor(IndentSpacing * scale_factor); ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor); ScrollbarSize = ImFloor(ScrollbarSize * scale_factor); ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor); TabRounding = ImFloor(TabRounding * scale_factor); TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX; DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); } ImGuiIO::ImGuiIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here. // Settings ConfigFlags = ImGuiConfigFlags_None; BackendFlags = ImGuiBackendFlags_None; DisplaySize = ImVec2(-1.0f, -1.0f); DeltaTime = 1.0f / 60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; for (int i = 0; i < ImGuiKey_COUNT; i++) KeyMap[i] = -1; KeyRepeatDelay = 0.275f; KeyRepeatRate = 0.050f; UserData = NULL; Fonts = NULL; FontGlobalScale = 1.0f; FontDefault = NULL; FontAllowUserScaling = false; DisplayFramebufferScale = ImVec2(1.0f, 1.0f); // Miscellaneous options MouseDrawCursor = false; #ifdef __APPLE__ ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag #else ConfigMacOSXBehaviors = false; #endif ConfigInputTextCursorBlink = true; ConfigWindowsResizeFromEdges = true; ConfigWindowsMoveFromTitleBarOnly = false; ConfigMemoryCompactTimer = 60.0f; // Platform Functions BackendPlatformName = BackendRendererName = NULL; BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL; GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ClipboardUserData = NULL; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; ImeWindowHandle = NULL; // Input (NB: we already have memset zero the entire structure!) MousePos = ImVec2(-FLT_MAX, -FLT_MAX); MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); MouseDragThreshold = 6.0f; for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f; } // Pass in translated ASCII characters for text input. // - with glfw you can get those from the callback set in glfwSetCharCallback() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(unsigned int c) { if (c != 0) InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID); } // UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so // we should save the high surrogate. void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c) { if (c == 0 && InputQueueSurrogate == 0) return; if ((c & 0xFC00) == 0xD800) // High surrogate, must save { if (InputQueueSurrogate != 0) InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID); InputQueueSurrogate = c; return; } ImWchar cp = c; if (InputQueueSurrogate != 0) { if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID); else if (IM_UNICODE_CODEPOINT_MAX == (0xFFFF)) // Codepoint will not fit in ImWchar (extra parenthesis around 0xFFFF somehow fixes -Wunreachable-code with Clang) cp = IM_UNICODE_CODEPOINT_INVALID; else cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000); InputQueueSurrogate = 0; } InputQueueCharacters.push_back(cp); } void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) { while (*utf8_chars != 0) { unsigned int c = 0; utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL); if (c != 0) InputQueueCharacters.push_back((ImWchar)c); } } void ImGuiIO::ClearInputCharacters() { InputQueueCharacters.resize(0); } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (Geometry functions) //----------------------------------------------------------------------------- ImVec2 ImBezierClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments) { IM_ASSERT(num_segments > 0); // Use ImBezierClosestPointCasteljau() ImVec2 p_last = p1; ImVec2 p_closest; float p_closest_dist2 = FLT_MAX; float t_step = 1.0f / (float)num_segments; for (int i_step = 1; i_step <= num_segments; i_step++) { ImVec2 p_current = ImBezierCalc(p1, p2, p3, p4, t_step * i_step); ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); float dist2 = ImLengthSqr(p - p_line); if (dist2 < p_closest_dist2) { p_closest = p_line; p_closest_dist2 = dist2; } p_last = p_current; } return p_closest; } // Closely mimics PathBezierToCasteljau() in imgui_draw.cpp static void BezierClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) { float dx = x4 - x1; float dy = y4 - y1; float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); d2 = (d2 >= 0) ? d2 : -d2; d3 = (d3 >= 0) ? d3 : -d3; if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy)) { ImVec2 p_current(x4, y4); ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p); float dist2 = ImLengthSqr(p - p_line); if (dist2 < p_closest_dist2) { p_closest = p_line; p_closest_dist2 = dist2; } p_last = p_current; } else if (level < 10) { float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f; float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f; float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f; float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f; float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f; float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f; BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1); BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1); } } // tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol // Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically. ImVec2 ImBezierClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol) { IM_ASSERT(tess_tol > 0.0f); ImVec2 p_last = p1; ImVec2 p_closest; float p_closest_dist2 = FLT_MAX; BezierClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0); return p_closest; } 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; if (dot < 0.0f) return a; 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; } 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; 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 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; out_u = 1.0f - out_v - out_w; } 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)); if (m == dist2_ab) return proj_ab; if (m == dist2_bc) return proj_bc; return proj_ca; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) //----------------------------------------------------------------------------- // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more. int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int ImStrnicmp(const char* str1, const char* str2, size_t count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } void ImStrncpy(char* dst, const char* src, size_t count) { if (count < 1) return; if (count > 1) strncpy(dst, src, count - 1); dst[count - 1] = 0; } char* ImStrdup(const char* str) { 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; if (dst_buf_size < src_size) { IM_FREE(dst); dst = (char*)IM_ALLOC(src_size); if (p_dst_size) *p_dst_size = src_size; } return (char*)memcpy(dst, (const void*)src, src_size); } const char* ImStrchrRange(const char* str, const char* str_end, char c) { const char* p = (const char*)memchr(str, (int)c, str_end - str); return p; } int ImStrlenW(const ImWchar* str) { //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit int n = 0; while (*str++) n++; return n; } // 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) { const char* p = (const char*)memchr(str, '\n', str_end - str); return p ? p : str_end; } const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line { while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') buf_mid_line--; return buf_mid_line; } const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { if (!needle_end) needle_end = needle + strlen(needle); const char un0 = (char)toupper(*needle); while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) { if (toupper(*haystack) == un0) { const char* b = needle + 1; for (const char* a = haystack + 1; b < needle_end; a++, b++) if (toupper(*a) != toupper(*b)) break; if (b == needle_end) return haystack; } haystack++; } return NULL; } // Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. void ImStrTrimBlanks(char* buf) { char* p = buf; while (p[0] == ' ' || p[0] == '\t') // Leading blanks p++; char* p_start = p; while (*p != 0) // Find end of string p++; while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks p--; if (p_start != buf) // Copy memory if we had leading blanks memmove(buf, p_start, p - p_start); buf[p - p_start] = 0; // Zero terminate } const char* ImStrSkipBlank(const char* str) { while (str[0] == ' ' || str[0] == '\t') str++; return str; } // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. // B) When buf==NULL vsnprintf() will return the output size. #ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h) // You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are // designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.) #ifdef IMGUI_USE_STB_SPRINTF #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h" #endif #if defined(_MSC_VER) && !defined(vsnprintf) #define vsnprintf _vsnprintf #endif int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) { va_list args; va_start(args, fmt); #ifdef IMGUI_USE_STB_SPRINTF int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); #else int w = vsnprintf(buf, buf_size, fmt, args); #endif va_end(args); if (buf == NULL) return w; if (w == -1 || w >= (int)buf_size) w = (int)buf_size - 1; buf[w] = 0; return w; } int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) { #ifdef IMGUI_USE_STB_SPRINTF int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); #else int w = vsnprintf(buf, buf_size, fmt, args); #endif if (buf == NULL) return w; if (w == -1 || w >= (int)buf_size) w = (int)buf_size - 1; buf[w] = 0; return w; } #endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // CRC32 needs a 1KB lookup table (not cache friendly) // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily: // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe. static const ImU32 GCrc32LookupTable[256] = { 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91, 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5, 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59, 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D, 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01, 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65, 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9, 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD, 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1, 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5, 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79, 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D, 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21, 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45, 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9, 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D, }; // Known size hash // It is ok to call ImHashData on a string with known length but the ### operator won't be supported. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed) { ImU32 crc = ~seed; const unsigned char* data = (const unsigned char*)data_p; const ImU32* crc32_lut = GCrc32LookupTable; while (data_size-- != 0) crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++]; return ~crc; } // Zero-terminated string hash, with support for ### to reset back to seed value // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. // Because this syntax is rarely used we are optimizing for the common case. // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build) // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed) { seed = ~seed; ImU32 crc = seed; const unsigned char* data = (const unsigned char*)data_p; const ImU32* crc32_lut = GCrc32LookupTable; if (data_size != 0) { while (data_size-- != 0) { unsigned char c = *data++; if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } else { while (unsigned char c = *data++) { if (c == '#' && data[0] == '#' && data[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } return ~crc; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (File functions) //----------------------------------------------------------------------------- // Default file functions #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS ImFileHandle ImFileOpen(const char* filename, const char* mode) { #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__) // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32! const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0); const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0); ImVector<ImWchar> buf; buf.resize(filename_wsize + mode_wsize); ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize); ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize); return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]); #else return fopen(filename, mode); #endif } // We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way. bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; } ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; } ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); } ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); } #endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Helper: Load file content into memory // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() // This can't really be used with "rt" because fseek size won't match read size. void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes) { IM_ASSERT(filename && mode); if (out_file_size) *out_file_size = 0; ImFileHandle f; if ((f = ImFileOpen(filename, mode)) == NULL) return NULL; size_t file_size = (size_t)ImFileGetSize(f); if (file_size == (size_t)-1) { ImFileClose(f); return NULL; } void* file_data = IM_ALLOC(file_size + padding_bytes); if (file_data == NULL) { ImFileClose(f); return NULL; } if (ImFileRead(file_data, 1, file_size, f) != file_size) { ImFileClose(f); IM_FREE(file_data); return NULL; } if (padding_bytes > 0) memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes); ImFileClose(f); if (out_file_size) *out_file_size = file_size; return file_data; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (ImText* functions) //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bit character, process single character input. // A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8). // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 }; static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 }; static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 }; static const int shiftc[] = { 0, 18, 12, 6, 0 }; static const int shifte[] = { 0, 6, 4, 2, 0 }; int len = lengths[*(const unsigned char*)in_text >> 3]; int wanted = len + !len; if (in_text_end == NULL) in_text_end = in_text + wanted; // Max length, nulls will be taken into account. // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here, // so it is fast even with excessive branching. unsigned char s[4]; s[0] = in_text + 0 < in_text_end ? in_text[0] : 0; s[1] = in_text + 1 < in_text_end ? in_text[1] : 0; s[2] = in_text + 2 < in_text_end ? in_text[2] : 0; s[3] = in_text + 3 < in_text_end ? in_text[3] : 0; // Assume a four-byte character and load four bytes. Unused bits are shifted out. *out_char = (uint32_t)(s[0] & masks[len]) << 18; *out_char |= (uint32_t)(s[1] & 0x3f) << 12; *out_char |= (uint32_t)(s[2] & 0x3f) << 6; *out_char |= (uint32_t)(s[3] & 0x3f) << 0; *out_char >>= shiftc[len]; // Accumulate the various error conditions. int e = 0; e = (*out_char < mins[len]) << 6; // non-canonical encoding e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half? e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range? e |= (s[1] & 0xc0) >> 2; e |= (s[2] & 0xc0) >> 4; e |= (s[3] ) >> 6; e ^= 0x2a; // top two bits of each tail byte correct? e >>= shifte[len]; if (e) { // No bytes are consumed when *in_text == 0 || in_text == in_text_end. // One byte is consumed in case of invalid first byte of in_text. // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s. wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]); *out_char = IM_UNICODE_CODEPOINT_INVALID; } return wanted; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; *buf_out++ = (ImWchar)c; } *buf_out = 0; if (in_text_remaining) *in_text_remaining = in_text; return (int)(buf_out - buf); } int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) { int char_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; char_count++; } return char_count; } // Based on stb_to_utf8() from github.com/nothings/stb/ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (c < 0x80) { buf[0] = (char)c; return 1; } if (c < 0x800) { if (buf_size < 2) return 0; buf[0] = (char)(0xc0 + (c >> 6)); buf[1] = (char)(0x80 + (c & 0x3f)); return 2; } if (c < 0x10000) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c ) & 0x3f)); return 3; } if (c <= 0x10FFFF) { if (buf_size < 4) return 0; buf[0] = (char)(0xf0 + (c >> 18)); buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[3] = (char)(0x80 + ((c ) & 0x3f)); return 4; } // Invalid code point, the max unicode is 0x10FFFF return 0; } // Not optimal but we very rarely use this function. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end) { unsigned int unused = 0; return ImTextCharFromUtf8(&unused, in_text, in_text_end); } static inline int ImTextCountUtf8BytesFromChar(unsigned int c) { if (c < 0x80) return 1; if (c < 0x800) return 2; if (c < 0x10000) return 3; if (c <= 0x10FFFF) return 4; return 3; } int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) { char* buf_out = buf; const char* buf_end = buf + buf_size; while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c); } *buf_out = 0; return (int)(buf_out - buf); } int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) { int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) bytes_count++; else bytes_count += ImTextCountUtf8BytesFromChar(c); } return bytes_count; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (Color functions) // Note: The Convert functions are early design which are not consistent with other API. //----------------------------------------------------------------------------- IMGUI_API ImU32 ImAlphaBlendColors(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); return IM_COL32(r, g, b, 0xFF); } ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) { float s = 1.0f / 255.0f; return ImVec4( ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); } ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) { ImU32 out; out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; return out; } // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) { float K = 0.f; if (g < b) { ImSwap(g, b); K = -1.f; } if (r < g) { ImSwap(r, g); K = -2.f / 6.f - K; } const float chroma = r - (g < b ? g : b); out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f)); out_s = chroma / (r + 1e-20f); out_v = r; } // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 // also http://en.wikipedia.org/wiki/HSL_and_HSV void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) { if (s == 0.0f) { // gray out_r = out_g = out_b = v; return; } h = 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)); switch (i) { case 0: out_r = v; out_g = t; out_b = p; break; case 1: out_r = q; out_g = v; out_b = p; break; case 2: out_r = p; out_g = v; out_b = t; break; case 3: out_r = p; out_g = q; out_b = v; break; case 4: out_r = t; out_g = p; out_b = v; break; case 5: default: out_r = v; out_g = p; out_b = q; break; } } //----------------------------------------------------------------------------- // [SECTION] ImGuiStorage // Helper: Key->value storage //----------------------------------------------------------------------------- // std::lower_bound but without the bullshit static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key) { ImGuiStorage::ImGuiStoragePair* first = data.Data; ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size; size_t count = (size_t)(last - first); while (count > 0) { size_t count2 = count >> 1; ImGuiStorage::ImGuiStoragePair* mid = first + count2; if (mid->key < key) { first = ++mid; count -= count2 + 1; } else { count = count2; } } return first; } // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. void ImGuiStorage::BuildSortByKey() { struct StaticFunc { static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs) { // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1; if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1; return 0; } }; if (Data.Size > 1) ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID); } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; } bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const { return GetInt(key, default_val ? 1 : 0) != 0; } float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; } void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; } // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_i; } bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) { return (bool*)GetIntRef(key, default_val ? 1 : 0); } float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, ImGuiStoragePair(key, default_val)); return &it->val_p; } // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImGuiID key, int val) { ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, ImGuiStoragePair(key, val)); return; } it->val_i = val; } void ImGuiStorage::SetBool(ImGuiID key, bool val) { SetInt(key, val ? 1 : 0); } void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, ImGuiStoragePair(key, val)); return; } it->val_f = val; } void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImGuiStoragePair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, ImGuiStoragePair(key, val)); return; } it->val_p = val; } void ImGuiStorage::SetAllInt(int v) { for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } //----------------------------------------------------------------------------- // [SECTION] ImGuiTextFilter //----------------------------------------------------------------------------- // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) { if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); Build(); } else { InputBuf[0] = 0; CountGrep = 0; } } bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); if (value_changed) Build(); return value_changed; } void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const { out->resize(0); const char* wb = b; const char* we = wb; while (we < e) { if (*we == separator) { out->push_back(ImGuiTextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) out->push_back(ImGuiTextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf)); input_range.split(',', &Filters); CountGrep = 0; for (int i = 0; i != Filters.Size; i++) { ImGuiTextRange& f = Filters[i]; while (f.b < f.e && ImCharIsBlankA(f.b[0])) f.b++; while (f.e > f.b && ImCharIsBlankA(f.e[-1])) f.e--; if (f.empty()) continue; if (Filters[i].b[0] != '-') CountGrep += 1; } } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) return true; if (text == NULL) text = ""; for (int i = 0; i != Filters.Size; i++) { const ImGuiTextRange& f = Filters[i]; if (f.empty()) continue; if (f.b[0] == '-') { // Subtract if (ImStristr(text, text_end, f.b + 1, f.e) != NULL) return false; } else { // Grep if (ImStristr(text, text_end, f.b, f.e) != NULL) return true; } } // Implicit * grep if (CountGrep == 0) return true; return false; } //----------------------------------------------------------------------------- // [SECTION] ImGuiTextBuffer //----------------------------------------------------------------------------- // On some platform vsnprintf() takes va_list by reference and modifies it. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. #ifndef va_copy #if defined(__GNUC__) || defined(__clang__) #define va_copy(dest, src) __builtin_va_copy(dest, src) #else #define va_copy(dest, src) (dest = src) #endif #endif char ImGuiTextBuffer::EmptyString[1] = { 0 }; void ImGuiTextBuffer::append(const char* str, const char* str_end) { int len = str_end ? (int)(str_end - str) : (int)strlen(str); // Add zero-terminator the first time const int write_off = (Buf.Size != 0) ? Buf.Size : 1; const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { int new_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); } Buf.resize(needed_sz); memcpy(&Buf[write_off - 1], str, (size_t)len); Buf[write_off - 1 + len] = 0; } void ImGuiTextBuffer::appendf(const char* fmt, ...) { va_list args; va_start(args, fmt); appendfv(fmt, args); va_end(args); } // Helper: Text buffer for logging/accumulating text 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. if (len <= 0) { va_end(args_copy); return; } // Add zero-terminator the first time const int write_off = (Buf.Size != 0) ? Buf.Size : 1; const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { int new_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); } Buf.resize(needed_sz); ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy); va_end(args_copy); } //----------------------------------------------------------------------------- // [SECTION] ImGuiListClipper // This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed // the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO) //----------------------------------------------------------------------------- // Helper to calculate coarse clipping of large list of evenly sized items. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.LogEnabled) { // If logging is active, do not perform any clipping *out_items_display_start = 0; *out_items_display_end = items_count; return; } if (window->SkipItems) { *out_items_display_start = *out_items_display_end = 0; return; } // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect ImRect unclipped_rect = window->ClipRect; if (g.NavMoveRequest) unclipped_rect.Add(g.NavScoringRect); if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId) unclipped_rect.Add(ImRect(window->Pos + window->NavRectRel[0].Min, window->Pos + window->NavRectRel[0].Max)); const ImVec2 pos = window->DC.CursorPos; int start = (int)((unclipped_rect.Min.y - pos.y) / items_height); int end = (int)((unclipped_rect.Max.y - pos.y) / items_height); // When performing a navigation request, ensure we have one item extra in the direction we are moving to if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up) start--; if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down) end++; start = ImClamp(start, 0, items_count); end = ImClamp(end + 1, start, items_count); *out_items_display_start = start; *out_items_display_end = end; } static void SetCursorPosYAndSetupForPrevLine(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; ImGuiWindow* window = g.CurrentWindow; window->DC.CursorPos.y = pos_y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y); window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. if (ImGuiOldColumns* columns = window->DC.CurrentColumns) columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } ImGuiListClipper::ImGuiListClipper() { memset(this, 0, sizeof(*this)); ItemsCount = -1; } ImGuiListClipper::~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1 && "Forgot to call End(), or to Step() until false?"); } // Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1 // Use case B: Begin() called from constructor with items_height>0 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. void ImGuiListClipper::Begin(int items_count, float items_height) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; StartPosY = window->DC.CursorPos.y; ItemsHeight = items_height; ItemsCount = items_count; StepNo = 0; DisplayStart = -1; DisplayEnd = 0; } void ImGuiListClipper::End() { if (ItemsCount < 0) // Already ended return; // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX && DisplayStart >= 0) SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); ItemsCount = -1; StepNo = 3; } bool ImGuiListClipper::Step() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Reached end of list if (DisplayEnd >= ItemsCount || window->SkipItems) { End(); return false; } // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) if (StepNo == 0) { StartPosY = window->DC.CursorPos.y; if (ItemsHeight <= 0.0f) { // Submit the first item so we can measure its height (generally it is 0..1) DisplayStart = 0; DisplayEnd = 1; StepNo = 1; return true; } // Already has item height (given by user in Begin): skip to calculating step DisplayStart = DisplayEnd; StepNo = 2; } // Step 1: the clipper infer height from first element if (StepNo == 1) { IM_ASSERT(ItemsHeight <= 0.0f); ItemsHeight = window->DC.CursorPos.y - StartPosY; IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!"); StepNo = 2; } // Step 2: calculate the actual range of elements to display, and position the cursor before the first element if (StepNo == 2) { IM_ASSERT(ItemsHeight > 0.0f); int already_submitted = DisplayEnd; ImGui::CalcListClipping(ItemsCount - already_submitted, ItemsHeight, &DisplayStart, &DisplayEnd); DisplayStart += already_submitted; DisplayEnd += already_submitted; // Seek cursor if (DisplayStart > already_submitted) SetCursorPosYAndSetupForPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); StepNo = 3; return true; } // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), // Advance the cursor to the end of the list and then returns 'false' to end the loop. if (StepNo == 3) { // Seek cursor if (ItemsCount < INT_MAX) SetCursorPosYAndSetupForPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; return false; } IM_ASSERT(0); return false; } //----------------------------------------------------------------------------- // [SECTION] STYLING //----------------------------------------------------------------------------- ImGuiStyle& ImGui::GetStyle() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); return GImGui->Style; } ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) { ImGuiStyle& style = GImGui->Style; ImVec4 c = style.Colors[idx]; c.w *= style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); } ImU32 ImGui::GetColorU32(const ImVec4& col) { ImGuiStyle& style = GImGui->Style; ImVec4 c = col; c.w *= style.Alpha; return ColorConvertFloat4ToU32(c); } const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx) { ImGuiStyle& style = GImGui->Style; return style.Colors[idx]; } ImU32 ImGui::GetColorU32(ImU32 col) { ImGuiStyle& style = GImGui->Style; if (style.Alpha >= 1.0f) return col; ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } // FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col) { ImGuiContext& g = *GImGui; ImGuiColorMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorStack.push_back(backup); g.Style.Colors[idx] = ColorConvertU32ToFloat4(col); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { ImGuiContext& g = *GImGui; ImGuiColorMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorStack.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColorMod& backup = g.ColorStack.back(); g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorStack.pop_back(); count--; } } struct ImGuiStyleVarInfo { ImGuiDataType Type; ImU32 Count; ImU32 Offset; void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); } }; static const ImGuiStyleVarInfo GStyleVarInfo[] = { { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign }; static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT); return &GStyleVarInfo[idx]; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) { ImGuiContext& g = *GImGui; float* pvar = (float*)var_info->GetVarPtr(&g.Style); g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!"); } void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) { ImGuiContext& g = *GImGui; ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!"); } void ImGui::PopStyleVar(int count) { ImGuiContext& g = *GImGui; 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.StyleVarStack.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]; } else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } g.StyleVarStack.pop_back(); count--; } } const char* ImGui::GetStyleColorName(ImGuiCol idx) { // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; switch (idx) { case ImGuiCol_Text: return "Text"; case ImGuiCol_TextDisabled: return "TextDisabled"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildBg: return "ChildBg"; case ImGuiCol_PopupBg: return "PopupBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgActive: return "TitleBgActive"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; case ImGuiCol_MenuBarBg: return "MenuBarBg"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; case ImGuiCol_CheckMark: return "CheckMark"; case ImGuiCol_SliderGrab: return "SliderGrab"; case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; case ImGuiCol_Button: return "Button"; case ImGuiCol_ButtonHovered: return "ButtonHovered"; case ImGuiCol_ButtonActive: return "ButtonActive"; case ImGuiCol_Header: return "Header"; case ImGuiCol_HeaderHovered: return "HeaderHovered"; case ImGuiCol_HeaderActive: return "HeaderActive"; case ImGuiCol_Separator: return "Separator"; case ImGuiCol_SeparatorHovered: return "SeparatorHovered"; case ImGuiCol_SeparatorActive: return "SeparatorActive"; case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; case ImGuiCol_Tab: return "Tab"; case ImGuiCol_TabHovered: return "TabHovered"; case ImGuiCol_TabActive: return "TabActive"; case ImGuiCol_TabUnfocused: return "TabUnfocused"; case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; case ImGuiCol_NavHighlight: return "NavHighlight"; case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg"; case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg"; } IM_ASSERT(0); return "Unknown"; } //----------------------------------------------------------------------------- // [SECTION] RENDER HELPERS // Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, // we need a nicer separation between low-level functions and high-level functions relying on the ImGui context. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context. //----------------------------------------------------------------------------- const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) { const char* text_display_end = text; if (!text_end) text_end = (const char*)-1; while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) text_display_end++; return text_display_end; } // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { text_display_end = FindRenderedTextEnd(text, text_end); } else { if (!text_end) text_end = text + strlen(text); // FIXME-OPT text_display_end = text_end; } if (text != text_display_end) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) LogRenderedText(&pos, text, text_display_end); } } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!text_end) text_end = text + strlen(text); // FIXME-OPT if (text != text_end) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); if (g.LogEnabled) LogRenderedText(&pos, text, text_end); } } // Default clip_rect uses (pos_min,pos_max) // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { // Perform CPU side clipping for single clipped element to avoid using scissor state ImVec2 pos = pos_min; const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); // Render if (need_clipping) { ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); } else { draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); } } void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { // Hide anything after a '##' string const char* text_display_end = FindRenderedTextEnd(text, text_end); const int text_len = (int)(text_display_end - text); if (text_len == 0) return; ImGuiContext& g = *GImGui; ImGuiWindow* window = 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); } // Another overly complex function until we reorganize everything into a nice all-in-one helper. // This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display. // 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; 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); //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255)); //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255)); //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255)); // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels. if (text_size.x > pos_max.x - pos_min.x) { // Hello wo... // | | | // min max ellipsis_max // <-> this is generally some padding value const ImFont* font = draw_list->_Data->Font; const float font_size = draw_list->_Data->FontSize; const char* text_end_ellipsis = NULL; ImWchar ellipsis_char = font->EllipsisChar; int ellipsis_char_count = 1; if (ellipsis_char == (ImWchar)-1) { ellipsis_char = (ImWchar)'.'; ellipsis_char_count = 3; } const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char); float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis if (ellipsis_char_count > 1) { // Full ellipsis size without free spacing after it. const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize); ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots; ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots; } // We can now claim the space between pos_max.x and ellipsis_max.x const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f); float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x; if (text == text_end_ellipsis && text_end_ellipsis < text_end_full) { // Always display at least 1 character if there's no room for character + ellipsis text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full); text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x; } while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1])) { // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text) text_end_ellipsis--; text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte } // Render text, render ellipsis RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); float ellipsis_x = pos_min.x + text_size_clipped_x; if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x) for (int i = 0; i < ellipsis_char_count; i++) { font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char); ellipsis_x += ellipsis_glyph_width; } } else { RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f)); } if (g.LogEnabled) LogRenderedText(&pos_min, text, text_end_full); } // 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; window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); const float border_size = g.Style.FrameBorderSize; if (border && border_size > 0.0f) { window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const float border_size = g.Style.FrameBorderSize; if (border_size > 0.0f) { window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags) { ImGuiContext& g = *GImGui; if (id != g.NavId) return; if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw)) return; ImGuiWindow* window = g.CurrentWindow; if (window->DC.NavHideHighlightOneFrame) return; float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; ImRect display_rect = bb; display_rect.ClipWith(window->ClipRect); if (flags & ImGuiNavHighlightFlags_TypeDefault) { 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); 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); if (!fully_visible) window->DrawList->PopClipRect(); } if (flags & ImGuiNavHighlightFlags_TypeThin) { window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f); } } //----------------------------------------------------------------------------- // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) //----------------------------------------------------------------------------- // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL) { memset(this, 0, sizeof(*this)); Name = ImStrdup(name); NameBufLen = (int)strlen(name) + 1; ID = ImHashStr(name); IDStack.push_back(ID); MoveId = GetID("#MOVE"); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); AutoFitFramesX = AutoFitFramesY = -1; AutoPosLastDirection = ImGuiDir_None; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; LastTimeActive = -1.0f; FontWindowScale = 1.0f; SettingsOffset = -1; DrawList = &DrawListInst; DrawList->_Data = &context->DrawListSharedData; DrawList->_OwnerName = Name; } ImGuiWindow::~ImGuiWindow() { IM_ASSERT(DrawList == &DrawListInst); IM_DELETE(Name); for (int i = 0; i != ColumnsStorage.Size; i++) ColumnsStorage[i].~ImGuiOldColumns(); } 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); ImGui::KeepAliveID(id); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiContext& g = *GImGui; IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end); #endif return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); ImGui::KeepAliveID(id); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiContext& g = *GImGui; IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr); #endif return id; } ImGuiID ImGuiWindow::GetID(int n) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashData(&n, sizeof(n), seed); ImGui::KeepAliveID(id); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiContext& g = *GImGui; IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n); #endif return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiContext& g = *GImGui; IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end); #endif return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiContext& g = *GImGui; IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr); #endif return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashData(&n, sizeof(n), seed); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiContext& g = *GImGui; IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n); #endif return id; } // 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 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); ImGui::KeepAliveID(id); return id; } static void SetCurrentWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.CurrentWindow = window; if (window) g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } void ImGui::GcCompactTransientMiscBuffers() { ImGuiContext& g = *GImGui; g.ItemFlagsStack.clear(); g.GroupStack.clear(); } // Free up/compact internal window buffers, we can use this when a window becomes unused. // Not freed: // - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data) // This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window) { window->MemoryCompacted = true; window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity; window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity; window->IDStack.clear(); window->DrawList->_ClearFreeMemory(); window->DC.ChildWindows.clear(); window->DC.ItemWidthStack.clear(); window->DC.TextWrapPosStack.clear(); } void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window) { // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening. // The other buffers tends to amortize much faster. window->MemoryCompacted = false; window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity); window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity); window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0; } void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.ActiveIdIsJustActivated = (g.ActiveId != id); if (g.ActiveIdIsJustActivated) { g.ActiveIdTimer = 0.0f; g.ActiveIdHasBeenPressedBefore = false; g.ActiveIdHasBeenEditedBefore = false; if (id != 0) { g.LastActiveId = id; g.LastActiveIdTimer = 0.0f; } } g.ActiveId = id; g.ActiveIdAllowOverlap = false; g.ActiveIdNoClearOnFocusLoss = false; g.ActiveIdWindow = window; g.ActiveIdHasBeenEditedThisFrame = false; if (id) { g.ActiveIdIsAlive = id; g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse; } // Clear declaration of inputs claimed by the widget // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet) g.ActiveIdUsingNavDirMask = 0x00; g.ActiveIdUsingNavInputMask = 0x00; g.ActiveIdUsingKeyInputMask = 0x00; } void ImGui::ClearActiveID() { SetActiveID(0, NULL); // g.ActiveId = 0; } void ImGui::SetHoveredID(ImGuiID id) { ImGuiContext& g = *GImGui; g.HoveredId = id; g.HoveredIdAllowOverlap = false; if (id != 0 && g.HoveredIdPreviousFrame != id) g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f; } ImGuiID ImGui::GetHoveredID() { ImGuiContext& g = *GImGui; return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame; } void ImGui::KeepAliveID(ImGuiID id) { ImGuiContext& g = *GImGui; if (g.ActiveId == id) g.ActiveIdIsAlive = id; if (g.ActiveIdPreviousFrame == id) g.ActiveIdPreviousFrameIsAlive = true; } void ImGui::MarkItemEdited(ImGuiID id) { // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit(). // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data. ImGuiContext& g = *GImGui; IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive); IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); g.ActiveIdHasBeenEditedThisFrame = true; g.ActiveIdHasBeenEditedBefore = true; g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited; } static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags) { // 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; if (g.NavWindow) if (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" // NB: The order of those two tests is important because Modal windows are also Popups. if (focused_root_window->Flags & ImGuiWindowFlags_Modal) return false; if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup)) return false; } return true; } // This is roughly matching the behavior of internal-facing ItemHoverable() // - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() // - 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; ImGuiWindow* window = g.CurrentWindow; if (g.NavDisableMouseHover && !g.NavDisableHighlight) return IsItemFocused(); // Test for bounding box overlap, as updated as ItemAdd() if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function // Test if we are hovering the right window (our window could be behind another window) // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself. // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while. //if (g.HoveredWindow != window) // return false; if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped)) return false; // Test if another item is active (e.g. being dragged) if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId) return false; // Test if interactions on this window are blocked by an active popup or modal. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. if (!IsWindowContentHoverable(window, flags)) return false; // Test if the item is disabled if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) return false; // Special handling for calling after Begin() which represent the title bar or tab. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed) return false; return true; } // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) { ImGuiContext& g = *GImGui; if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap) return false; ImGuiWindow* window = g.CurrentWindow; if (g.HoveredWindow != window) return false; if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) return false; if (!IsMouseHoveringRect(bb.Min, bb.Max)) return false; if (g.NavDisableMouseHover) return false; if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None) || (window->DC.ItemFlags & ImGuiItemFlags_Disabled)) { g.HoveredIdDisabled = true; return false; } // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level // hover test in widgets code. We could also decide to split this function is two. if (id != 0) { SetHoveredID(id); // [DEBUG] Item Picker tool! // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered // items if we perform the test in ItemAdd(), but that would incur a small runtime cost. // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd(). if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id) GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255)); if (g.DebugItemPickerBreakId == id) IM_DEBUG_BREAK(); } return true; } bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!bb.Overlaps(window->ClipRect)) if (id == 0 || (id != g.ActiveId && id != g.NavId)) if (clip_even_when_logged || !g.LogEnabled) return true; return false; } // This is also inlined in ItemAdd() // Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect! void ImGui::SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags item_flags, const ImRect& item_rect) { window->DC.LastItemId = item_id; window->DC.LastItemStatusFlags = item_flags; window->DC.LastItemRect = item_rect; } // Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) { ImGuiContext& g = *GImGui; // Increment counters const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0; window->DC.FocusCounterRegular++; if (is_tab_stop) window->DC.FocusCounterTabStop++; // Process TAB/Shift-TAB to tab *OUT* of the currently focused item. // (Note that we can always TAB out of a widget that doesn't allow tabbing in) if (g.ActiveId == id && g.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL) { g.FocusRequestNextWindow = window; g.FocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. } // Handle focus requests if (g.FocusRequestCurrWindow == window) { if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular) return true; if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop) { g.NavJustTabbedId = id; return true; } // If another item is about to be focused, we clear our own active id if (g.ActiveId == id) ClearActiveID(); } return false; } void ImGui::FocusableItemUnregister(ImGuiWindow* window) { window->DC.FocusCounterRegular--; window->DC.FocusCounterTabStop--; } float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) return 0.0f; ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (wrap_pos_x == 0.0f) { // We could decide to setup a default wrapping max point for auto-resizing windows, // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) // wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x); //else wrap_pos_x = window->WorkRect.Max.x; } else if (wrap_pos_x > 0.0f) { wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space } return ImMax(wrap_pos_x - pos.x, 1.0f); } // IM_ALLOC() == ImGui::MemAlloc() void* ImGui::MemAlloc(size_t size) { if (ImGuiContext* ctx = GImGui) ctx->IO.MetricsActiveAllocations++; return GImAllocatorAllocFunc(size, GImAllocatorUserData); } // IM_FREE() == ImGui::MemFree() void ImGui::MemFree(void* ptr) { if (ptr) if (ImGuiContext* ctx = GImGui) ctx->IO.MetricsActiveAllocations--; return GImAllocatorFreeFunc(ptr, GImAllocatorUserData); } const char* ImGui::GetClipboardText() { ImGuiContext& g = *GImGui; return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { ImGuiContext& g = *GImGui; if (g.IO.SetClipboardTextFn) g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text); } const char* ImGui::GetVersion() { return IMGUI_VERSION; } // Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module ImGuiContext* ImGui::GetCurrentContext() { return GImGui; } void ImGui::SetCurrentContext(ImGuiContext* ctx) { #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. #else GImGui = ctx; #endif } void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data) { GImAllocatorAllocFunc = alloc_func; GImAllocatorFreeFunc = free_func; GImAllocatorUserData = user_data; } ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas) { ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas); if (GImGui == NULL) SetCurrentContext(ctx); Initialize(ctx); return ctx; } void ImGui::DestroyContext(ImGuiContext* ctx) { if (ctx == NULL) ctx = GImGui; Shutdown(ctx); if (GImGui == ctx) SetCurrentContext(NULL); IM_DELETE(ctx); } // No specific ordering/dependency support, will see as needed void ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook) { ImGuiContext& g = *ctx; IM_ASSERT(hook->Callback != NULL); g.Hooks.push_back(*hook); } // Call context hooks (used by e.g. test engine) // We assume a small number of hooks so all stored in same array void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type) { ImGuiContext& g = *ctx; for (int n = 0; n < g.Hooks.Size; n++) if (g.Hooks[n].Type == hook_type) g.Hooks[n].Callback(&g, &g.Hooks[n]); } ImGuiIO& ImGui::GetIO() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); return GImGui->IO; } // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { ImGuiContext& g = *GImGui; return g.DrawData.Valid ? &g.DrawData : NULL; } double ImGui::GetTime() { return GImGui->Time; } int ImGui::GetFrameCount() { return GImGui->FrameCount; } ImDrawList* ImGui::GetBackgroundDrawList() { return &GImGui->BackgroundDrawList; } ImDrawList* ImGui::GetForegroundDrawList() { return &GImGui->ForegroundDrawList; } ImDrawListSharedData* ImGui::GetDrawListSharedData() { return &GImGui->DrawListSharedData; } void ImGui::StartMouseMovingWindow(ImGuiWindow* window) { // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. // This is because we want ActiveId to be set even when the window is not permitted to move. ImGuiContext& g = *GImGui; FocusWindow(window); SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; g.ActiveIdNoClearOnFocusLoss = true; g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; bool can_move_window = true; if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) can_move_window = false; if (can_move_window) g.MovingWindow = window; } // Handle mouse moving window // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() // FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId. // This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs, // but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other. void ImGui::UpdateMouseMovingWindowNewFrame() { ImGuiContext& g = *GImGui; if (g.MovingWindow != NULL) { // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency. KeepAliveID(g.ActiveId); IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow); ImGuiWindow* moving_window = g.MovingWindow->RootWindow; if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos)) { ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y) { MarkIniSettingsDirty(moving_window); SetWindowPos(moving_window, pos, ImGuiCond_Always); } FocusWindow(g.MovingWindow); } else { ClearActiveID(); g.MovingWindow = NULL; } } else { // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId) { KeepAliveID(g.ActiveId); if (!g.IO.MouseDown[0]) ClearActiveID(); } } } // Initiate moving window when clicking on empty space or title bar. // Handle left-click and right-click focus. void ImGui::UpdateMouseMovingWindowEndFrame() { ImGuiContext& g = *GImGui; if (g.ActiveId != 0 || g.HoveredId != 0) return; // Unless we just made a window/popup appear if (g.NavWindow && g.NavWindow->Appearing) return; // Click on empty space to focus window and start moving (after we're done with all our widgets) if (g.IO.MouseClicked[0]) { // Handle the edge case of a popup being closed while clicking in its empty space. // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. ImGuiWindow* root_window = g.HoveredRootWindow; const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel); if (root_window != NULL && !is_closed_popup) { StartMouseMovingWindow(g.HoveredWindow); //-V595 // Cancel moving if clicked outside of title bar if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar)) if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already) if (g.HoveredIdDisabled) g.MovingWindow = NULL; } else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL) { // Clicking on void disable focus FocusWindow(NULL); } } // With right mouse button we close popups without changing focus based on where the mouse is aimed // Instead, focus will be restored to the window under the bottom-most closed popup. // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger) if (g.IO.MouseClicked[1]) { // Find the top-most window between HoveredWindow and the top-most Modal Window. // This is where we can trim the popup stack. ImGuiWindow* modal = GetTopMostPopupModal(); bool hovered_window_above_modal = g.HoveredWindow && IsWindowAbove(g.HoveredWindow, modal); ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true); } } static bool IsWindowActiveAndVisible(ImGuiWindow* window) { return (window->Active) && (!window->Hidden); } static void ImGui::UpdateMouseInputs() { ImGuiContext& g = *GImGui; // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) if (IsMousePosValid(&g.IO.MousePos)) g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos); // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev)) g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; else g.IO.MouseDelta = ImVec2(0.0f, 0.0f); if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f) g.NavDisableMouseHover = false; g.IO.MousePosPrev = g.IO.MousePos; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; g.IO.MouseDoubleClicked[i] = false; if (g.IO.MouseClicked[i]) { if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime) { ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" so the third click isn't turned into a double-click } else { g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i]; g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; } else if (g.IO.MouseDown[i]) { // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos)); g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x); g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y); } if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i]) g.IO.MouseDownWasDoubleClick[i] = false; if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation g.NavDisableMouseHover = false; } } static void StartLockWheelingWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.WheelingWindow == window) return; g.WheelingWindow = window; g.WheelingWindowRefMousePos = g.IO.MousePos; g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER; } void ImGui::UpdateMouseWheel() { ImGuiContext& g = *GImGui; // Reset the locked window if we move the mouse or after the timer elapses if (g.WheelingWindow != NULL) { g.WheelingWindowTimer -= g.IO.DeltaTime; if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold) g.WheelingWindowTimer = 0.0f; if (g.WheelingWindowTimer <= 0.0f) { g.WheelingWindow = NULL; g.WheelingWindowTimer = 0.0f; } } if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f) return; ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow; if (!window || window->Collapsed) return; // Zoom / Scale window // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) { StartLockWheelingWindow(window); const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); const float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) { const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; SetWindowPos(window, window->Pos + offset, 0); window->Size = ImFloor(window->Size * scale); window->SizeFull = ImFloor(window->SizeFull * scale); } return; } // Mouse wheel scrolling // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent // Vertical Mouse Wheel scrolling const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; if (wheel_y != 0.0f && !g.IO.KeyCtrl) { StartLockWheelingWindow(window); while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) 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)); SetScrollY(window, window->Scroll.y - wheel_y * scroll_step); } } // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; if (wheel_x != 0.0f && !g.IO.KeyCtrl) { StartLockWheelingWindow(window); while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs)))) 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)); SetScrollX(window, window->Scroll.x - wheel_x * scroll_step); } } } void ImGui::UpdateTabFocus() { ImGuiContext& g = *GImGui; // Pressing TAB activate widget focus g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)); if (g.ActiveId == 0 && g.FocusTabPressed) { // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also // manipulate the Next fields even, even though they will be turned into Curr fields by the code below. g.FocusRequestNextWindow = g.NavWindow; g.FocusRequestNextCounterRegular = INT_MAX; if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); else g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0; } // Turn queued focus request into current one g.FocusRequestCurrWindow = NULL; g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX; if (g.FocusRequestNextWindow != NULL) { ImGuiWindow* window = g.FocusRequestNextWindow; g.FocusRequestCurrWindow = window; if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1) g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1); if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1) g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1); g.FocusRequestNextWindow = NULL; g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = INT_MAX; } g.NavIdTabCounter = INT_MAX; } // The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) void ImGui::UpdateHoveredWindowAndCaptureFlags() { ImGuiContext& g = *GImGui; // Find the window hovered by mouse: // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. bool clear_hovered_windows = false; FindHoveredWindow(); // Modal windows prevents mouse from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) clear_hovered_windows = true; // Disabled mouse? if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) clear_hovered_windows = true; // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward. int mouse_earliest_button_down = -1; bool mouse_any_down = false; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (g.OpenPopupStack.Size > 0); mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down]) mouse_earliest_button_down = i; } const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) clear_hovered_windows = true; if (clear_hovered_windows) g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app) if (g.WantCaptureMouseNextFrame != -1) g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0); else g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.OpenPopupStack.Size > 0); // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app) if (g.WantCaptureKeyboardNextFrame != -1) g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0); else g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL); if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)) g.IO.WantCaptureKeyboard = true; // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } ImGuiKeyModFlags ImGui::GetMergedKeyModFlags() { ImGuiContext& g = *GImGui; ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None; if (g.IO.KeyCtrl) { key_mod_flags |= ImGuiKeyModFlags_Ctrl; } if (g.IO.KeyShift) { key_mod_flags |= ImGuiKeyModFlags_Shift; } if (g.IO.KeyAlt) { key_mod_flags |= ImGuiKeyModFlags_Alt; } if (g.IO.KeySuper) { key_mod_flags |= ImGuiKeyModFlags_Super; } return key_mod_flags; } void ImGui::NewFrame() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); ImGuiContext& g = *GImGui; CallContextHooks(&g, ImGuiContextHookType_NewFramePre); // Check and assert for various common IO and Configuration mistakes ErrorCheckNewFrameSanityChecks(); // Load settings on first frame, save settings when modified (after a delay) UpdateSettings(); g.Time += g.IO.DeltaTime; g.WithinFrameScope = true; g.FrameCount += 1; g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; g.MenusIdSubmittedThisFrame.resize(0); // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX; // Setup current font and draw list shared data g.IO.Fonts->Locked = true; SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError); g.DrawListSharedData.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines)) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; g.BackgroundDrawList._ResetForNewFrame(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); g.ForegroundDrawList._ResetForNewFrame(); g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.ForegroundDrawList.PushClipRectFullScreen(); // Mark rendering data as invalid to prevent user who may have a handle on it to use it. g.DrawData.Clear(); // Drag and drop keep the source ID alive so even if the source disappear our state is consistent if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId) KeepAliveID(g.DragDropPayload.SourceId); // Update HoveredId data if (!g.HoveredIdPreviousFrame) g.HoveredIdTimer = 0.0f; if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId)) g.HoveredIdNotActiveTimer = 0.0f; if (g.HoveredId) g.HoveredIdTimer += g.IO.DeltaTime; if (g.HoveredId && g.ActiveId != g.HoveredId) g.HoveredIdNotActiveTimer += g.IO.DeltaTime; g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; g.HoveredIdDisabled = false; // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore) if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) ClearActiveID(); if (g.ActiveId) g.ActiveIdTimer += g.IO.DeltaTime; g.LastActiveIdTimer += g.IO.DeltaTime; g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow; g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore; g.ActiveIdIsAlive = 0; g.ActiveIdHasBeenEditedThisFrame = false; g.ActiveIdPreviousFrameIsAlive = false; g.ActiveIdIsJustActivated = false; if (g.TempInputId != 0 && g.ActiveId != g.TempInputId) g.TempInputId = 0; if (g.ActiveId == 0) { g.ActiveIdUsingNavDirMask = 0x00; g.ActiveIdUsingNavInputMask = 0x00; g.ActiveIdUsingKeyInputMask = 0x00; } // Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; g.DragDropAcceptIdCurr = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropWithinSource = false; g.DragDropWithinTarget = false; g.DragDropHoldJustPressedId = 0; // Update keyboard input state // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools g.IO.KeyMods = GetMergedKeyModFlags(); memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Update gamepad/keyboard navigation NavUpdate(); // Update mouse input state UpdateMouseInputs(); // Find hovered window // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame) UpdateHoveredWindowAndCaptureFlags(); // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) UpdateMouseMovingWindowNewFrame(); // Background darkening/whitening if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f); else g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f); g.MouseCursor = ImGuiMouseCursor_Arrow; g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1; g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default // Mouse wheel scrolling, scale UpdateMouseWheel(); // Update legacy TAB focus UpdateTabFocus(); // Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; window->WasActive = window->Active; window->BeginCount = 0; window->Active = false; window->WriteAccessed = false; // Garbage collect transient buffers of recently unused windows if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time) GcCompactTransientWindowBuffers(window); } if (g.GcCompactAll) GcCompactTransientMiscBuffers(); g.GcCompactAll = false; // Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow && !g.NavWindow->WasActive) FocusTopMostWindowUnderOne(NULL, NULL); // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); g.BeginPopupStack.resize(0); g.ItemFlagsStack.resize(0); g.ItemFlagsStack.push_back(ImGuiItemFlags_Default_); g.GroupStack.resize(0); ClosePopupsOverWindow(g.NavWindow, false); // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. UpdateDebugToolItemPicker(); // Create implicit/fallback window - which we will only render it if the user has added something to it. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. // This fallback is particularly important as it avoid ImGui:: calls from crashing. g.WithinFrameScopeWithImplicitWindow = true; SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true); CallContextHooks(&g, ImGuiContextHookType_NewFramePost); } // [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack. void ImGui::UpdateDebugToolItemPicker() { ImGuiContext& g = *GImGui; g.DebugItemPickerBreakId = 0; if (g.DebugItemPickerActive) { const ImGuiID hovered_id = g.HoveredIdPreviousFrame; ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); if (ImGui::IsKeyPressedMap(ImGuiKey_Escape)) g.DebugItemPickerActive = false; if (ImGui::IsMouseClicked(0) && hovered_id) { g.DebugItemPickerBreakId = hovered_id; g.DebugItemPickerActive = false; } ImGui::SetNextWindowBgAlpha(0.60f); ImGui::BeginTooltip(); ImGui::Text("HoveredId: 0x%08X", hovered_id); ImGui::Text("Press ESC to abort picking."); ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!"); ImGui::EndTooltip(); } } void ImGui::Initialize(ImGuiContext* context) { ImGuiContext& g = *context; IM_ASSERT(!g.Initialized && !g.SettingsLoaded); // Add .ini handle for ImGuiWindow type { ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Window"; ini_handler.TypeHash = ImHashStr("Window"); ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll; ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen; ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine; ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll; ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll; g.SettingsHandlers.push_back(ini_handler); } #ifdef IMGUI_HAS_TABLE // Add .ini handle for ImGuiTable type { ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Table"; ini_handler.TypeHash = ImHashStr("Table"); ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen; ini_handler.ReadLineFn = TableSettingsHandler_ReadLine; ini_handler.WriteAllFn = TableSettingsHandler_WriteAll; g.SettingsHandlers.push_back(ini_handler); } #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK #endif // #ifdef IMGUI_HAS_DOCK g.Initialized = true; } // This function is merely here to free heap allocations. void ImGui::Shutdown(ImGuiContext* context) { // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) ImGuiContext& g = *context; if (g.IO.Fonts && g.FontAtlasOwnedByContext) { g.IO.Fonts->Locked = false; IM_DELETE(g.IO.Fonts); } g.IO.Fonts = NULL; // Cleanup of other data are conditional on actually having initialized Dear ImGui. if (!g.Initialized) return; // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file) if (g.SettingsLoaded && g.IO.IniFilename != NULL) { ImGuiContext* backup_context = GImGui; SetCurrentContext(&g); SaveIniSettingsToDisk(g.IO.IniFilename); SetCurrentContext(backup_context); } CallContextHooks(&g, ImGuiContextHookType_Shutdown); // Clear everything else for (int i = 0; i < g.Windows.Size; i++) IM_DELETE(g.Windows[i]); g.Windows.clear(); g.WindowsFocusOrder.clear(); g.WindowsTempSortBuffer.clear(); g.CurrentWindow = NULL; g.CurrentWindowStack.clear(); g.WindowsById.Clear(); g.NavWindow = NULL; g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL; g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; g.MovingWindow = NULL; g.ColorStack.clear(); g.StyleVarStack.clear(); g.FontStack.clear(); g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); g.BackgroundDrawList._ClearFreeMemory(); g.ForegroundDrawList._ClearFreeMemory(); g.TabBars.Clear(); g.CurrentTabBarStack.clear(); g.ShrinkWidthBuffer.clear(); g.ClipboardHandlerData.clear(); g.MenusIdSubmittedThisFrame.clear(); g.InputTextState.ClearFreeMemory(); g.SettingsWindows.clear(); g.SettingsHandlers.clear(); if (g.LogFile) { #ifndef IMGUI_DISABLE_TTY_FUNCTIONS if (g.LogFile != stdout) #endif ImFileClose(g.LogFile); g.LogFile = NULL; } g.LogBuffer.clear(); g.Initialized = false; } // FIXME: Add a more explicit sort order in the window structure. 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)) return d; if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; return (a->BeginOrderWithinParent - b->BeginOrderWithinParent); } static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window) { out_sorted_windows->push_back(window); if (window->Active) { 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++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Active) AddWindowToSortBuffer(out_sorted_windows, child); } } } static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list) { // Remove trailing command if unused. // Technically we could return directly instead of popping, but this make things looks neat in Metrics/Debugger window as well. draw_list->_PopUnusedDrawCmd(); if (draw_list->CmdBuffer.Size == 0) return; // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. // May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset)) IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) // If this assert triggers because you are drawing lots of stuff manually: // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds. // Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents. // - If you want large meshes with more than 64K vertices, you can either: // (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. // Most example backends already support this from 1.71. Pre-1.71 backends won't. // Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them. // (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. // Most example backends already support this. For example, the OpenGL example code detect index size at compile-time: // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); // Your own engine or render API may use different parameters or function calls to specify index sizes. // 2 and 4 bytes indices are generally supported by most graphics API. // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching // the 64K limit to split your draw commands in multiple draw lists. if (sizeof(ImDrawIdx) == 2) IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above"); out_list->push_back(draw_list); } static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.IO.MetricsRenderWindows++; AddDrawListToDrawData(out_render_list, window->DrawList); for (int i = 0; i < window->DC.ChildWindows.Size; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active AddWindowToDrawData(out_render_list, child); } } // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu) static void AddRootWindowToDrawData(ImGuiWindow* window) { ImGuiContext& g = *GImGui; int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0; AddWindowToDrawData(&g.DrawDataBuilder.Layers[layer], window); } void ImDrawDataBuilder::FlattenIntoSingleLayer() { int n = Layers[0].Size; int size = n; for (int i = 1; i < IM_ARRAYSIZE(Layers); i++) size += Layers[i].Size; Layers[0].resize(size); for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++) { ImVector<ImDrawList*>& layer = Layers[layer_n]; if (layer.empty()) continue; memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); n += layer.Size; layer.resize(0); } } static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data) { 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; draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; draw_data->DisplayPos = ImVec2(0.0f, 0.0f); draw_data->DisplaySize = io.DisplaySize; draw_data->FramebufferScale = io.DisplayFramebufferScale; for (int n = 0; n < draw_lists->Size; n++) { draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size; draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size; } } // Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. // - When using this function it is sane to ensure that float are perfectly rounded to integer values, // so that e.g. (int)(max.x-min.x) in user's render produce correct result. // - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect(): // some frequently called functions which to modify both channels and clipping simultaneously tend to use the // more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); window->ClipRect = window->DrawList->_ClipRectStack.back(); } void ImGui::PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PopClipRect(); window->ClipRect = window->DrawList->_ClipRectStack.back(); } // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. void ImGui::EndFrame() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); // Don't process EndFrame() multiple times. if (g.FrameCountEnded == g.FrameCount) return; IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?"); CallContextHooks(&g, ImGuiContextHookType_EndFramePre); ErrorCheckEndFrameSanityChecks(); // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f)) { g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y); g.PlatformImeLastPos = g.PlatformImePos; } // Hide implicit/fallback "Debug" window if it hasn't been used g.WithinFrameScopeWithImplicitWindow = false; if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed) g.CurrentWindow->Active = false; End(); // Update navigation: CTRL+Tab, wrap-around requests NavEndFrame(); // 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)); if (is_delivered || is_elapsed) ClearDragDrop(); } // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { g.DragDropWithinSource = true; SetTooltip("..."); g.DragDropWithinSource = false; } // End frame g.WithinFrameScope = false; g.FrameCountEnded = g.FrameCount; // Initiate moving window + handle left-click and right-click focus UpdateMouseMovingWindowEndFrame(); // Sort the window list so that all child windows are after their parent // We cannot do that on FocusWindow() because children may not exist yet g.WindowsTempSortBuffer.resize(0); g.WindowsTempSortBuffer.reserve(g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it continue; AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window); } // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size); g.Windows.swap(g.WindowsTempSortBuffer); g.IO.MetricsActiveWindows = g.WindowsActiveCount; // Unlock font atlas g.IO.Fonts->Locked = false; // Clear Input data for next frame g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f; g.IO.InputQueueCharacters.resize(0); memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs)); CallContextHooks(&g, ImGuiContextHookType_EndFramePost); } void ImGui::Render() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); if (g.FrameCountEnded != g.FrameCount) EndFrame(); g.FrameCountRendered = g.FrameCount; g.IO.MetricsRenderWindows = 0; g.DrawDataBuilder.Clear(); CallContextHooks(&g, ImGuiContextHookType_RenderPre); // Add background ImDrawList if (!g.BackgroundDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList); // Add ImDrawList to render ImGuiWindow* windows_to_render_top_most[2]; windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL); for (int n = 0; n != g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1]) AddRootWindowToDrawData(window); } for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++) if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window AddRootWindowToDrawData(windows_to_render_top_most[n]); g.DrawDataBuilder.FlattenIntoSingleLayer(); // Draw software mouse cursor if requested if (g.IO.MouseDrawCursor) RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48)); // Add foreground ImDrawList if (!g.ForegroundDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList); // Setup ImDrawData structure for end-user SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData); g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount; g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount; CallContextHooks(&g, ImGuiContextHookType_RenderPost); } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, g.FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; if (text == text_display_end) return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Round text_size.x = IM_FLOOR(text_size.x + 0.95f); return text_size; } // Find window given position, search front-to-back // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is // called, aka before the next Begin(). Moving window isn't affected. static void FindHoveredWindow() { ImGuiContext& g = *GImGui; ImGuiWindow* hovered_window = NULL; ImGuiWindow* hovered_window_ignoring_moving_window = NULL; 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; for (int i = g.Windows.Size - 1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; if (!window->Active || window->Hidden) continue; if (window->Flags & ImGuiWindowFlags_NoMouseInputs) continue; // Using the clipped AABB, a child window will typically be clipped by its parent (not always) ImRect bb(window->OuterRectClipped); if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) bb.Expand(padding_regular); else bb.Expand(padding_for_resize_from_edges); if (!bb.Contains(g.IO.MousePos)) continue; // Support for one rectangular hole in any given window // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) if (window->HitTestHoleSize.x != 0) { ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y); ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y); if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos)) continue; } if (hovered_window == NULL) hovered_window = window; if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow)) hovered_window_ignoring_moving_window = window; if (hovered_window && hovered_window_ignoring_moving_window) break; } g.HoveredWindow = hovered_window; g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window; } // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { ImGuiContext& g = *GImGui; // Clip ImRect rect_clipped(r_min, r_max); if (clip) rect_clipped.ClipWith(g.CurrentWindow->ClipRect); // Expand for touch input const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); if (!rect_for_touch.Contains(g.IO.MousePos)) return false; return true; } int ImGui::GetKeyIndex(ImGuiKey imgui_key) { IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); ImGuiContext& g = *GImGui; return g.IO.KeyMap[imgui_key]; } // Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]! // Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]! bool ImGui::IsKeyDown(int user_key_index) { if (user_key_index < 0) return false; ImGuiContext& g = *GImGui; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); return g.IO.KeysDown[user_key_index]; } // t0 = previous time (e.g.: g.Time - g.IO.DeltaTime) // t1 = current time (e.g.: g.Time) // An event is triggered at: // t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate) { if (t1 == 0.0f) return 1; if (t0 >= t1) return 0; if (repeat_rate <= 0.0f) return (t0 < repeat_delay) && (t1 >= repeat_delay); const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate); const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate); const int count = count_t1 - count_t0; return count; } int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate) { ImGuiContext& g = *GImGui; if (key_index < 0) return 0; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[key_index]; return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate); } bool ImGui::IsKeyPressed(int user_key_index, bool repeat) { ImGuiContext& g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[user_key_index]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; return false; } bool ImGui::IsKeyReleased(int user_key_index) { ImGuiContext& g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index]; } bool ImGui::IsMouseDown(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDown[button]; } bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) { // 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 = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f); if (amount > 0) return true; } return false; } bool ImGui::IsMouseReleased(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseReleased[button]; } bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } // Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame. // [Internal] This doesn't test if the button is pressed bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; } bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) return false; return IsMouseDragPastThreshold(button, lock_threshold); } ImVec2 ImGui::GetMousePos() { ImGuiContext& g = *GImGui; return g.IO.MousePos; } // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.BeginPopupStack.Size > 0) return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos; return g.IO.MousePos; } // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) { // The assert is only to silence a false-positive in XCode Static Analysis. // 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; return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID; } bool ImGui::IsAnyMouseDown() { ImGuiContext& g = *GImGui; for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++) if (g.IO.MouseDown[n]) return true; return false; } // Return the delta from the initial clicking position while the mouse button is clicked or was just released. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once. // NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window. ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; if (g.IO.MouseDown[button] || g.IO.MouseReleased[button]) if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button])) return g.IO.MousePos - g.IO.MouseClickedPos[button]; return ImVec2(0.0f, 0.0f); } void ImGui::ResetMouseDragDelta(ImGuiMouseButton button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; } ImGuiMouseCursor ImGui::GetMouseCursor() { return GImGui->MouseCursor; } void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) { GImGui->MouseCursor = cursor_type; } void ImGui::CaptureKeyboardFromApp(bool capture) { GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0; } void ImGui::CaptureMouseFromApp(bool capture) { GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0; } bool ImGui::IsItemActive() { ImGuiContext& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = g.CurrentWindow; return g.ActiveId == window->DC.LastItemId; } return false; } bool ImGui::IsItemActivated() { ImGuiContext& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = g.CurrentWindow; if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId) return true; } return false; } bool ImGui::IsItemDeactivated() { ImGuiContext& g = *GImGui; 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); } bool ImGui::IsItemDeactivatedAfterEdit() { ImGuiContext& g = *GImGui; return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore)); } // == GetItemID() == GetFocusID() bool ImGui::IsItemFocused() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavId != window->DC.LastItemId || g.NavId == 0) return false; return true; } bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button) { return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None); } bool ImGui::IsItemToggledOpen() { ImGuiContext& g = *GImGui; return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false; } bool ImGui::IsItemToggledSelection() { ImGuiContext& g = *GImGui; return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false; } bool ImGui::IsAnyItemHovered() { ImGuiContext& g = *GImGui; return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0; } bool ImGui::IsAnyItemActive() { ImGuiContext& g = *GImGui; return g.ActiveId != 0; } bool ImGui::IsAnyItemFocused() { ImGuiContext& g = *GImGui; return g.NavId != 0 && !g.NavDisableHighlight; } bool ImGui::IsItemVisible() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(window->DC.LastItemRect); } bool ImGui::IsItemEdited() { ImGuiWindow* window = GetCurrentWindowRead(); return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0; } // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. void ImGui::SetItemAllowOverlap() { ImGuiContext& g = *GImGui; if (g.HoveredId == g.CurrentWindow->DC.LastItemId) g.HoveredIdAllowOverlap = true; if (g.ActiveId == g.CurrentWindow->DC.LastItemId) g.ActiveIdAllowOverlap = true; } ImVec2 ImGui::GetItemRectMin() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } static ImRect GetViewportRect() { ImGuiContext& g = *GImGui; return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow; flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag // Size const ImVec2 content_avail = GetContentRegionAvail(); ImVec2 size = ImFloor(size_arg); const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00); if (size.x <= 0.0f) size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) if (size.y <= 0.0f) size.y = ImMax(content_avail.y + size.y, 4.0f); SetNextWindowSize(size); // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value. char title[256]; if (name) ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id); else ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id); const float backup_border_size = g.Style.ChildBorderSize; if (!border) g.Style.ChildBorderSize = 0.0f; bool ret = Begin(title, NULL, flags); g.Style.ChildBorderSize = backup_border_size; ImGuiWindow* child_window = g.CurrentWindow; child_window->ChildId = id; child_window->AutoFitChildAxises = (ImS8)auto_fit_axises; // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually. // While this is not really documented/defined, it seems that the expected thing to do. if (child_window->BeginCount == 1) parent_window->DC.CursorPos = child_window->Pos; // Process navigation-in immediately so NavInit can run on first frame if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll)) { FocusWindow(child_window); NavInitWindow(child_window, false); SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item g.ActiveIdSource = ImGuiInputSource_Nav; } return ret; } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); } bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { IM_ASSERT(id != 0); return BeginChildEx(NULL, id, size_arg, border, extra_flags); } void ImGui::EndChild() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.WithinEndChild == false); IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls g.WithinEndChild = true; if (window->BeginCount > 1) { End(); } else { ImVec2 sz = window->Size; if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f sz.x = ImMax(4.0f, sz.x); if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y)) sz.y = ImMax(4.0f, sz.y); End(); ImGuiWindow* parent_window = g.CurrentWindow; 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)) { ItemAdd(bb, window->ChildId); RenderNavHighlight(bb, window->ChildId); // When browsing a window that has no activable items (scroll only) we keep a highlight on the child if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow) RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); } else { // Not navigable into ItemAdd(bb, 0); } } g.WithinEndChild = false; } // Helper to create a child window / scrolling region that looks like a normal widget frame. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; 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); PopStyleVar(3); PopStyleColor(); return ret; } void ImGui::EndChildFrame() { EndChild(); } static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled) { window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags); window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags); window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags); } ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) { ImGuiContext& g = *GImGui; return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id); } ImGuiWindow* ImGui::FindWindowByName(const char* name) { ImGuiID id = ImHashStr(name); return FindWindowByID(id); } static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings) { window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y)); if (settings->Size.x > 0 && settings->Size.y > 0) window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y)); window->Collapsed = settings->Collapsed; } static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags); // Create window the first time ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name); window->Flags = flags; g.WindowsById.SetVoidPtr(window->ID, window); // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. window->Pos = ImVec2(60, 60); // 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)) { // Retrieve settings from .ini file window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); ApplyWindowSettings(window, settings); } window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { window->AutoFitFramesX = window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } else { if (window->Size.x <= 0.0f) window->AutoFitFramesX = 2; if (window->Size.y <= 0.0f) window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); } g.WindowsFocusOrder.push_back(window); if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) g.Windows.push_front(window); // Quite slow but rare and only once else g.Windows.push_back(window); return window; } static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) { 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; 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) { ImGuiSizeCallbackData data; data.UserData = g.NextWindowData.SizeCallbackUserData; data.Pos = window->Pos; data.CurrentSize = window->SizeFull; data.DesiredSize = new_size; g.NextWindowData.SizeCallback(&data); new_size = data.DesiredSize; } new_size.x = IM_FLOOR(new_size.x); new_size.y = IM_FLOOR(new_size.y); } // Minimum size if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) { ImGuiWindow* window_for_height = window; new_size = ImMax(new_size, g.Style.WindowMinSize); new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows } return new_size; } static ImVec2 CalcWindowContentSize(ImGuiWindow* window) { if (window->Collapsed) if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) return window->ContentSize; if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0) return window->ContentSize; ImVec2 sz; sz.x = IM_FLOOR((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); sz.y = IM_FLOOR((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); return sz; } static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; ImVec2 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; if (window->Flags & ImGuiWindowFlags_Tooltip) { // Tooltip always resize return size_desired; } else { // Maximum window size is determined by the viewport size or monitor size const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0; const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0; ImVec2 size_min = style.WindowMinSize; if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) size_min = ImMin(size_min, ImVec2(4.0f, 4.0f)); ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f)); // 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); if (will_have_scrollbar_x) size_auto_fit.y += style.ScrollbarSize; if (will_have_scrollbar_y) size_auto_fit.x += style.ScrollbarSize; return size_auto_fit; } } 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); return size_final; } static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags) { if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) return ImGuiCol_PopupBg; if (flags & ImGuiWindowFlags_ChildWindow) return ImGuiCol_ChildBg; return ImGuiCol_WindowBg; } 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); *out_pos = pos_min; if (corner_norm.x == 0.0f) out_pos->x -= (size_constrained.x - size_expected.x); if (corner_norm.y == 0.0f) out_pos->y -= (size_constrained.y - size_expected.y); *out_size = size_constrained; } struct ImGuiResizeGripDef { ImVec2 CornerPosN; ImVec2 InnerDir; int AngleMin12, AngleMax12; }; static const ImGuiResizeGripDef resize_grip_def[4] = { { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 }, // Lower-right { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 }, // Lower-left { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 }, // Upper-left (Unused) { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }, // Upper-right (Unused) }; struct ImGuiResizeBorderDef { ImVec2 InnerDir; ImVec2 CornerPosN1, CornerPosN2; float OuterAngle; }; static const ImGuiResizeBorderDef resize_border_def[4] = { { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Top { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }, // Bottom { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f } // Left }; static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) { ImRect rect = window->Rect(); if (thickness == 0.0f) rect.Max -= ImVec2(1, 1); if (border_n == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom if (border_n == 3) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); } // Left IM_ASSERT(0); return ImRect(); } // 0..3: corners (Lower-right, Lower-left, Unused, Unused) // 4..7: borders (Top, Right, Bottom, Left) ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n) { IM_ASSERT(n >= 0 && n <= 7); ImGuiID id = window->ID; id = ImHashStr("#RESIZE", 0, id); id = ImHashData(&n, sizeof(int), id); return id; } // Handle resize for: Resize Grips, Borders, Gamepad // Return true when using auto-fit (double click on resize grip) static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) return false; if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window. return false; bool ret_auto_fit = false; const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0; const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f); const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f; ImVec2 pos_target(FLT_MAX, FLT_MAX); ImVec2 size_target(FLT_MAX, FLT_MAX); // Resize grips and borders are on layer 1 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; // Manual resize grips PushID("#RESIZE"); for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) { const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size); if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x); if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y); bool hovered, held; ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); if (hovered || held) g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE; if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0) { // Manual auto-fit when double-clicking size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit); ret_auto_fit = true; ClearActiveID(); } else if (held) { // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX); ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX); corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); } for (int border_n = 0; border_n < resize_border_count; border_n++) { bool hovered, held; ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); ButtonBehavior(border_rect, window->GetID(border_n + 4), &hovered, &held, ImGuiButtonFlags_FlattenChildren); //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held) { g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; if (held) *border_held = border_n; } if (held) { ImVec2 border_target = window->Pos; ImVec2 border_posn; if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX); ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX); border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } PopID(); // Restore nav layer window->DC.NavLayerCurrent = ImGuiNavLayer_Main; // Navigation resize (keyboard/gamepad) if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window) { ImVec2 nav_resize_delta; if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavInputSource == ImGuiInputSource_NavGamepad) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down); if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f) { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck. size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta); } } // Apply back modified position/size to window if (size_target.x != FLT_MAX) { window->SizeFull = size_target; MarkIniSettingsDirty(window); } if (pos_target.x != FLT_MAX) { window->Pos = ImFloor(pos_target); MarkIniSettingsDirty(window); } window->Size = window->SizeFull; return ret_auto_fit; } static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect) { ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = window->Size; if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) size_for_clamping.y = window->TitleBarHeight(); window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { ImGuiContext& g = *GImGui; float rounding = window->WindowRounding; 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; if (border_held != -1) { const ImGuiResizeBorderDef& def = resize_border_def[border_held]; 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; 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); } } // Draw background and borders // Draw and handle scrollbars 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; // Ensure that ScrollBar doesn't read last frame's SkipItems IM_ASSERT(window->BeginCount == 0); window->SkipItems = false; // 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. const float window_rounding = window->WindowRounding; const float window_border_size = window->WindowBorderSize; if (window->Collapsed) { // Title bar only 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); RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); g.Style.FrameBorderSize = backup_border_size; } else { // Window background if (!(flags & ImGuiWindowFlags_NoBackground)) { ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); bool override_alpha = false; float alpha = 1.0f; if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) { alpha = g.NextWindowData.BgAlphaVal; override_alpha = true; } if (override_alpha) bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); } // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { 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); } // Menu bar if (flags & ImGuiWindowFlags_MenuBar) { ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } // Scrollbars if (window->ScrollbarX) Scrollbar(ImGuiAxis_X); if (window->ScrollbarY) Scrollbar(ImGuiAxis_Y); // Render resize grips (after their input handling so we don't have a frame of latency) if (!(flags & ImGuiWindowFlags_NoResize)) { for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) { const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size))); window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size))); window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]); } } // Borders RenderWindowOuterBorders(window); } } // Render title text, collapse button, close button 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 bool has_close_button = (p_open != NULL); const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None); // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; // Layout buttons // 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; ImVec2 close_button_pos; ImVec2 collapse_button_pos; if (has_close_button) { pad_r += button_sz; close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y); } if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right) { pad_r += button_sz; collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y); } if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left) { collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y); pad_l += button_sz; } // Collapse button (submitting first so it gets priority when choosing a navigation init fallback) if (has_collapse_button) if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos)) window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function // Close button if (has_close_button) if (CloseButton(window->GetID("#CLOSE"), close_button_pos)) *p_open = false; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.ItemFlags = item_flags_backup; // 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.. const char* 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); // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, // while uncentered title text will still reach edges correct. if (pad_l > style.FramePadding.x) pad_l += g.Style.ItemInnerSpacing.x; if (pad_r > style.FramePadding.x) 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); 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); //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); ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f)); RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r); } } void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) { window->ParentWindow = parent_window; window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) window->RootWindow = parent_window->RootWindow; if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened) { IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL); window->RootWindowForNav = window->RootWindowForNav->ParentWindow; } } // Push a new Dear ImGui window to add widgets to. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required IM_ASSERT(g.WithinFrameScope); // Forgot to call ImGui::NewFrame() IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet // Find or create ImGuiWindow* window = FindWindowByName(name); const bool window_just_created = (window == NULL); if (window_just_created) window = CreateNewWindow(name, flags); // Automatically disable manual moving/resizing when NoInputs is set if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; if (flags & ImGuiWindowFlags_NavFlattened) IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow); const int current_frame = g.FrameCount; const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow); // Update the Appearing flag bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0); if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed window_just_activated_by_user |= (window != popup_ref.Window); } window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); // Update Flags, LastFrameActive, BeginOrderXXX fields if (first_begin_of_the_frame) { window->Flags = (ImGuiWindowFlags)flags; window->LastFrameActive = current_frame; window->LastTimeActive = (float)g.Time; window->BeginOrderWithinParent = 0; window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++); } else { flags = window->Flags; } // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back(); ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); // We allow window memory to be compacted so recreate the base stack when needed. if (window->IDStack.Size == 0) window->IDStack.push_back(window->ID); // Add to stack // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow() g.CurrentWindowStack.push_back(window); g.CurrentWindow = window; window->DC.StackSizesOnBegin.SetToCurrentState(); g.CurrentWindow = NULL; if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; popup_ref.Window = window; g.BeginPopupStack.push_back(popup_ref); window->PopupId = popup_ref.PopupId; } if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow)) window->NavLastIds[0] = 0; // Update ->RootWindow and others pointers (before any possible call to FocusWindow) if (first_begin_of_the_frame) UpdateWindowParentAndRootLinks(window, flags, parent_window); // Process SetNextWindow***() calls // (FIXME: Consider splitting the HasXXX flags into X/Y components bool window_pos_set_by_api = false; bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) { window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) { // May be processed on the next frame if this is our first frame and we are measuring size // FIXME: Look into removing the branch so everything can go through this same code path for consistency. window->SetWindowPosVal = g.NextWindowData.PosVal; window->SetWindowPosPivot = g.NextWindowData.PosPivotVal; window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); } else { SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); } } if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) { window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); } if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll) { if (g.NextWindowData.ScrollVal.x >= 0.0f) { window->ScrollTarget.x = g.NextWindowData.ScrollVal.x; window->ScrollTargetCenterRatio.x = 0.0f; } if (g.NextWindowData.ScrollVal.y >= 0.0f) { window->ScrollTarget.y = g.NextWindowData.ScrollVal.y; window->ScrollTargetCenterRatio.y = 0.0f; } } if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize) window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal; else if (first_begin_of_the_frame) window->ContentSizeExplicit = ImVec2(0.0f, 0.0f); if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed) SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus) FocusWindow(window); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); // When reusing window again multiple times a frame, just append content (don't need to setup again) if (first_begin_of_the_frame) { // Initialize const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) window->Active = true; window->HasCloseButton = (p_open != NULL); window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX); window->IDStack.resize(1); window->DrawList->_ResetForNewFrame(); // Restore buffer capacity when woken from a compacted state, to avoid if (window->MemoryCompacted) GcAwakeTransientWindowBuffers(window); // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. bool window_title_visible_elsewhere = false; if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB window_title_visible_elsewhere = true; if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) { size_t buf_len = (size_t)window->NameBufLen; window->Name = ImStrdupcpy(window->Name, &buf_len, name); window->NameBufLen = (int)buf_len; } // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS // Update contents size from last frame for auto-fitting (or use explicit size) window->ContentSize = CalcWindowContentSize(window); if (window->HiddenFramesCanSkipItems > 0) window->HiddenFramesCanSkipItems--; if (window->HiddenFramesCannotSkipItems > 0) window->HiddenFramesCannotSkipItems--; // Hide new windows for one frame until they calculate their size if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api)) window->HiddenFramesCannotSkipItems = 1; // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0) { window->HiddenFramesCannotSkipItems = 1; if (flags & ImGuiWindowFlags_AlwaysAutoResize) { if (!window_size_x_set_by_api) window->Size.x = window->SizeFull.x = 0.f; if (!window_size_y_set_by_api) window->Size.y = window->SizeFull.y = 0.f; window->ContentSize = ImVec2(0.f, 0.f); } } // SELECT VIEWPORT // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style) SetCurrentWindow(window); // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) if (flags & ImGuiWindowFlags_ChildWindow) window->WindowBorderSize = style.ChildBorderSize; else window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; window->WindowPadding = style.WindowPadding; if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f) window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size. window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) { // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar. ImRect title_bar_rect = window->TitleBarRect(); if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) window->WantCollapseToggle = true; if (window->WantCollapseToggle) { window->Collapsed = !window->Collapsed; MarkIniSettingsDirty(window); FocusWindow(window); } } else { window->Collapsed = false; } window->WantCollapseToggle = false; // SIZE // Calculate auto-fit size, handle automatic resize const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSize); bool use_current_size_for_scrollbar_x = window_just_created; bool use_current_size_for_scrollbar_y = window_just_created; if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) { // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. if (!window_size_x_set_by_api) { window->SizeFull.x = size_auto_fit.x; use_current_size_for_scrollbar_x = true; } if (!window_size_y_set_by_api) { window->SizeFull.y = size_auto_fit.y; use_current_size_for_scrollbar_y = true; } } else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) { // Auto-fit may only grow window during the first few frames // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0) { window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; use_current_size_for_scrollbar_x = true; } if (!window_size_y_set_by_api && window->AutoFitFramesY > 0) { window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; use_current_size_for_scrollbar_y = true; } if (!window->Collapsed) MarkIniSettingsDirty(window); } // Apply minimum/maximum window size constraints and final size window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull); window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; // Decoration size const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // POSITION // Popup latch its initial position, will position itself when it appears next frame if (window_just_activated_by_user) { window->AutoPosLastDirection = ImGuiDir_None; if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos() window->Pos = g.BeginPopupStack.back().OpenPopupPos; } // Position child window if (flags & ImGuiWindowFlags_ChildWindow) { IM_ASSERT(parent_window && parent_window->Active); window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size; parent_window->DC.ChildWindows.push_back(window); if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = parent_window->DC.CursorPos; } const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); if (window_pos_with_pivot) SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering) else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = FindBestWindowPosForPopup(window); // Calculate the range of allowed position for that window (to be movable and visible past safe area padding) // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect. ImRect viewport_rect(GetViewportRect()); ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); ImRect visibility_rect(viewport_rect.Min + visibility_padding, viewport_rect.Max - visibility_padding); // Clamp position/size so window stays visible within its viewport or monitor // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f) ClampWindowRect(window, visibility_rect); window->Pos = ImFloor(window->Pos); // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) // Large values tend to lead to variety of artifacts and are not recommended. window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts. //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar)) // window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f); // Apply window focus (new and reactivated windows are moved to front) bool want_focus = false; if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) { if (flags & ImGuiWindowFlags_Popup) want_focus = true; else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0) want_focus = true; } // Handle manual resize: Resize Grips, Borders, Gamepad int border_held = -1; ImU32 resize_grip_col[4] = {}; const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it. const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f)); if (!window->Collapsed) if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect)) use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true; window->ResizeBorderHeld = (signed char)border_held; // SCROLLBAR VISIBILITY // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). if (!window->Collapsed) { // When reading the current size we need to read it after size constraints have been applied. // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again. ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height); ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes; ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f; float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x; float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y; //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons? window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); if (window->ScrollbarX && !window->ScrollbarY) window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); } // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) // Update various regions. Variables they depends on should be set above in this function. // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. // Outer rectangle // Not affected by window border size. Used by: // - FindHoveredWindow() (w/ extra padding when border resize is enabled) // - Begin() initial clipping rect for drawing window background and borders. // - Begin() clipping whole child const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect; const ImRect outer_rect = window->Rect(); const ImRect title_bar_rect = window->TitleBarRect(); window->OuterRectClipped = outer_rect; window->OuterRectClipped.ClipWith(host_rect); // Inner rectangle // Not affected by window border size. Used by: // - InnerClipRect // - ScrollToBringRectIntoView() // - NavUpdatePageUpPageDown() // - Scrollbar() window->InnerRect.Min.x = window->Pos.x; window->InnerRect.Min.y = window->Pos.y + decoration_up_height; window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x; window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y; // Inner clipping rectangle. // Will extend a little bit outside the normal work region. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. // Affected by window/frame border size. Used by: // - Begin() initial clip rect float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize)); window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size); window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize)); window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize); window->InnerClipRect.ClipWithFull(host_rect); // Default item width. Make it proportional to window size if window manually resizes if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f); else window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f); // SCROLLING // Lock down maximum scrolling // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate // for right/bottom aligned items without creating a scrollbar. window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth()); window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight()); // Apply scrolling window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window); window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); // DRAWING // Setup draw list and outer clipping rectangle IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); PushClipRect(host_rect.Min, host_rect.Max, false); // Draw modal window background (darkens what is behind them, all viewports) const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0; const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow); if (dim_bg_for_modal || dim_bg_for_window_list) { const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col); } // Draw navigation selection/windowing rectangle background if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim) { ImRect bb = window->Rect(); bb.Expand(g.FontSize); if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding); } // Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call. // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. // We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child. // We also disabled this when we have dimming overlay behind this specific one child. // FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected. { bool render_decorations_in_parent = false; if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0) render_decorations_in_parent = true; if (render_decorations_in_parent) window->DrawList = parent_window->DrawList; // Handle title bar, scrollbar, resize grips and resize borders const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size); if (render_decorations_in_parent) window->DrawList = &window->DrawListInst; } // Draw navigation selection/windowing rectangle border if (g.NavWindowingTargetAnim == window) { float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding); ImRect bb = window->Rect(); bb.Expand(g.FontSize); if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward { bb.Expand(-g.FontSize - 1.0f); rounding = window->WindowRounding; } window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f); } // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) // Work rectangle. // Affected by window padding and border size. Used by: // - Columns() for right-most edge // - TreeNode(), CollapsingHeader() for right-most edge // - BeginTabBar() for right-most edge const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar); const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar); const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x)); const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y)); window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize)); window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize)); window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x; window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y; window->ParentWorkRect = window->WorkRect; // [LEGACY] Content Region // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. // Used by: // - Mouse wheel scrolling + many other things window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height; window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x)); window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y)); // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; window->DC.GroupOffset.x = 0.0f; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + window->WindowPadding.y - window->Scroll.y); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; window->DC.NavHideHighlightOneFrame = false; window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f); window->DC.MenuBarAppending = false; window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); window->DC.TreeDepth = 0; window->DC.TreeJumpToParentOnPopMask = 0x00; window->DC.ChildWindows.resize(0); window->DC.StateStorage = &window->StateStorage; window->DC.CurrentColumns = NULL; window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1; window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.ItemWidthStack.resize(0); window->DC.TextWrapPosStack.resize(0); if (window->AutoFitFramesX > 0) window->AutoFitFramesX--; if (window->AutoFitFramesY > 0) window->AutoFitFramesY--; // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) if (want_focus) { FocusWindow(window); NavInitWindow(window, false); } // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) RenderWindowTitleBarContents(window, title_bar_rect, name, p_open); // Clear hit test shape every frame window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0; // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. // Maybe we can support CTRL+C on every element? /* if (g.ActiveId == move_id) if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) LogToClipboard(); */ // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). // This is useful to allow creating context menus on title bar only, etc. SetLastItemData(window, window->MoveId, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect); #ifdef IMGUI_ENABLE_TEST_ENGINE if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId); #endif } else { // Append SetCurrentWindow(window); } // Pull/inherit current state window->DC.ItemFlags = g.ItemFlagsStack.back(); // Inherit from shared stack window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // Inherit from parent only // -V595 PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) window->WriteAccessed = false; window->BeginCount++; g.NextWindowData.ClearFlags(); // Update visibility if (first_begin_of_the_frame) { if (flags & ImGuiWindowFlags_ChildWindow) { // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) window->HiddenFramesCanSkipItems = 1; // Hide along with parent or if parent is collapsed if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0)) window->HiddenFramesCanSkipItems = 1; if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0)) window->HiddenFramesCannotSkipItems = 1; } // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) if (style.Alpha <= 0.0f) window->HiddenFramesCanSkipItems = 1; // Update the Hidden flag window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); // Update the SkipItems flag, used to early out of all items functions (no layout required) bool skip_items = false; if (window->Collapsed || !window->Active || window->Hidden) if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) skip_items = true; window->SkipItems = skip_items; } return !window->SkipItems; } void ImGui::End() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Error checking: verify that user hasn't called End() too many times! if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow) { IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!"); return; } IM_ASSERT(g.CurrentWindowStack.Size > 0); // Error checking: verify that user doesn't directly call End() on a child window. if (window->Flags & ImGuiWindowFlags_ChildWindow) IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!"); // Close anything that is open if (window->DC.CurrentColumns) EndColumns(); PopClipRect(); // Inner window clip rectangle // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging LogFinish(); // Pop from window stack g.CurrentWindowStack.pop_back(); if (window->Flags & ImGuiWindowFlags_Popup) g.BeginPopupStack.pop_back(); window->DC.StackSizesOnBegin.CompareWithCurrentState(); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } void ImGui::BringWindowToFocusFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.WindowsFocusOrder.back() == window) return; for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window if (g.WindowsFocusOrder[i] == window) { memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*)); g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window; break; } } void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; ImGuiWindow* current_front_window = g.Windows.back(); if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better) return; for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window if (g.Windows[i] == window) { memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*)); g.Windows[g.Windows.Size - 1] = window; break; } } void ImGui::BringWindowToDisplayBack(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.Windows[0] == window) return; for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i] == window) { memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*)); g.Windows[0] = window; break; } } // Moving window to front of display and set focus (which happens to be back of our sorted list) void ImGui::FocusWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.NavWindow != window) { g.NavWindow = window; if (window && g.NavDisableMouseHover) g.NavMousePosDirty = true; g.NavInitRequest = false; g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId g.NavFocusScopeId = 0; g.NavIdIsAlive = false; g.NavLayer = ImGuiNavLayer_Main; //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL); } // Close popups if any ClosePopupsOverWindow(window, false); // Move the root window to the top of the pile IM_ASSERT(window == NULL || window->RootWindow != NULL); ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; // Steal active widgets. Some of the cases it triggers includes: // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run. // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId) if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window) if (!g.ActiveIdNoClearOnFocusLoss) ClearActiveID(); // Passing NULL allow to disable keyboard focus if (!window) return; // Bring to front BringWindowToFocusFront(focus_front_window); if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0) BringWindowToDisplayFront(display_front_window); } void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window) { ImGuiContext& g = *GImGui; int start_idx = g.WindowsFocusOrder.Size - 1; if (under_this_window != NULL) { int under_this_window_idx = FindWindowFocusIndex(under_this_window); if (under_this_window_idx != -1) start_idx = under_this_window_idx - 1; } for (int i = start_idx; i >= 0; i--) { // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. ImGuiWindow* window = g.WindowsFocusOrder[i]; if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow)) if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) { ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window); FocusWindow(focus_window); return; } } FocusWindow(NULL); } void ImGui::SetCurrentFont(ImFont* font) { ImGuiContext& g = *GImGui; IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; g.FontBaseSize = 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; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; g.DrawListSharedData.TexUvLines = atlas->TexUvLines; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; if (!font) font = GetDefaultFont(); SetCurrentFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); } void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiItemFlags item_flags = window->DC.ItemFlags; IM_ASSERT(item_flags == g.ItemFlagsStack.back()); if (enabled) item_flags |= option; else item_flags &= ~option; window->DC.ItemFlags = item_flags; g.ItemFlagsStack.push_back(item_flags); } void ImGui::PopItemFlag() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack. g.ItemFlagsStack.pop_back(); window->DC.ItemFlags = g.ItemFlagsStack.back(); } // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { PopItemFlag(); } void ImGui::PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } void ImGui::PopButtonRepeat() { PopItemFlag(); } void ImGui::PushTextWrapPos(float wrap_pos_x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPos = wrap_pos_x; window->DC.TextWrapPosStack.push_back(wrap_pos_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPosStack.pop_back(); window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent) { if (window->RootWindow == potential_parent) return true; while (window != NULL) { if (window == potential_parent) return true; window = window->ParentWindow; } return false; } bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below) { ImGuiContext& g = *GImGui; for (int i = g.Windows.Size - 1; i >= 0; i--) { ImGuiWindow* candidate_window = g.Windows[i]; if (candidate_window == potential_above) return true; if (candidate_window == potential_below) return false; } return false; } bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) { IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function ImGuiContext& g = *GImGui; if (flags & ImGuiHoveredFlags_AnyWindow) { if (g.HoveredWindow == NULL) return false; } else { switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) { case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows: if (g.HoveredRootWindow != g.CurrentWindow->RootWindow) return false; break; case ImGuiHoveredFlags_RootWindow: if (g.HoveredWindow != g.CurrentWindow->RootWindow) return false; break; case ImGuiHoveredFlags_ChildWindows: if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow)) return false; break; default: if (g.HoveredWindow != g.CurrentWindow) return false; break; } } if (!IsWindowContentHoverable(g.HoveredWindow, flags)) return false; if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId) return false; return true; } bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) { ImGuiContext& g = *GImGui; if (flags & ImGuiFocusedFlags_AnyWindow) return g.NavWindow != NULL; IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End() switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows)) { case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows: return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow; case ImGuiFocusedFlags_RootWindow: return g.NavWindow == g.CurrentWindow->RootWindow; case ImGuiFocusedFlags_ChildWindows: return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow); default: return g.NavWindow == g.CurrentWindow; } } // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically. // If you want a window to never be focused, you may use the e.g. NoInputs flag. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) { return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); } float ImGui::GetWindowWidth() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.x; } float ImGui::GetWindowHeight() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.y; } ImVec2 ImGui::GetWindowPos() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; return window->Pos; } void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX); // Set const ImVec2 old_pos = window->Pos; window->Pos = ImFloor(pos); 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; } void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond) { ImGuiWindow* window = GetCurrentWindowRead(); SetWindowPos(window, pos, cond); } void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowPos(window, pos, cond); } ImVec2 ImGui::GetWindowSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Size; } void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) return; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); // Set if (size.x > 0.0f) { window->AutoFitFramesX = 0; window->SizeFull.x = IM_FLOOR(size.x); } else { window->AutoFitFramesX = 2; window->AutoFitOnlyGrows = false; } if (size.y > 0.0f) { window->AutoFitFramesY = 0; window->SizeFull.y = IM_FLOOR(size.y); } else { window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond) { SetWindowSize(GImGui->CurrentWindow, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowSize(window, size, cond); } void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); // Set window->Collapsed = collapsed; } void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size) { IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters window->HitTestHoleSize = ImVec2ih(size); window->HitTestHoleOffset = ImVec2ih(pos - window->Pos); } void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) { SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); } bool ImGui::IsWindowCollapsed() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Collapsed; } bool ImGui::IsWindowAppearing() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Appearing; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowCollapsed(window, collapsed, cond); } void ImGui::SetWindowFocus() { FocusWindow(GImGui->CurrentWindow); } void ImGui::SetWindowFocus(const char* name) { if (name) { if (ImGuiWindow* window = FindWindowByName(name)) FocusWindow(window); } else { FocusWindow(NULL); } } void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos; g.NextWindowData.PosVal = pos; g.NextWindowData.PosPivotVal = pivot; g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize; g.NextWindowData.SizeVal = size; g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data) { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint; g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); g.NextWindowData.SizeCallback = custom_callback; g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; } // Content size = inner scrollable rectangle, padded with WindowPadding. // SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item. void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize; g.NextWindowData.ContentSizeVal = size; } void ImGui::SetNextWindowScroll(const ImVec2& scroll) { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll; g.NextWindowData.ScrollVal = scroll; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed; g.NextWindowData.CollapsedVal = collapsed; g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowFocus() { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus; } void ImGui::SetNextWindowBgAlpha(float alpha) { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha; g.NextWindowData.BgAlphaVal = alpha; } ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } ImFont* ImGui::GetFont() { return GImGui->Font; } float ImGui::GetFontSize() { return GImGui->FontSize; } ImVec2 ImGui::GetFontTexUvWhitePixel() { return GImGui->DrawListSharedData.TexUvWhitePixel; } void ImGui::SetWindowFontScale(float scale) { IM_ASSERT(scale > 0.0f); ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } void ImGui::ActivateItem(ImGuiID id) { ImGuiContext& g = *GImGui; g.NavNextActivateId = id; } void ImGui::PushFocusScope(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent); window->DC.NavFocusScopeIdCurrent = id; } void ImGui::PopFocusScope() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ? window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back(); g.FocusScopeStack.pop_back(); } void ImGui::SetKeyboardFocusHere(int offset) { IM_ASSERT(offset >= -1); // -1 is allowed but not below ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; g.FocusRequestNextWindow = window; g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset; g.FocusRequestNextCounterTabStop = INT_MAX; } void ImGui::SetItemDefaultFocus() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!window->Appearing) return; if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent) { g.NavInitRequest = false; g.NavInitResultId = g.NavWindow->DC.LastItemId; g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos); NavUpdateAnyRequestFlag(); if (!IsItemVisible()) SetScrollHereY(); } } void ImGui::SetStateStorage(ImGuiStorage* tree) { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.StateStorage = tree ? tree : &window->StateStorage; } ImGuiStorage* ImGui::GetStateStorage() { ImGuiWindow* window = GImGui->CurrentWindow; return window->DC.StateStorage; } void ImGui::PushID(const char* str_id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiID id = window->GetIDNoKeepAlive(str_id); window->IDStack.push_back(id); } void ImGui::PushID(const char* str_id_begin, const char* str_id_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end); window->IDStack.push_back(id); } void ImGui::PushID(const void* ptr_id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiID id = window->GetIDNoKeepAlive(ptr_id); window->IDStack.push_back(id); } void ImGui::PushID(int int_id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiID id = window->GetIDNoKeepAlive(int_id); window->IDStack.push_back(id); } // Push a given id value ignoring the ID stack as a seed. void ImGui::PushOverrideID(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->IDStack.push_back(id); } // Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call // (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level. // for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed) { ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); ImGui::KeepAliveID(id); #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiContext& g = *GImGui; IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end); #endif return id; } void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window? window->IDStack.pop_back(); } ImGuiID ImGui::GetID(const char* str_id) { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(str_id); } ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(str_id_begin, str_id_end); } ImGuiID ImGui::GetID(const void* ptr_id) { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(ptr_id); } bool ImGui::IsRectVisible(const ImVec2& size) { 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; return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } //----------------------------------------------------------------------------- // [SECTION] ERROR CHECKING //----------------------------------------------------------------------------- // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui. // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code // may see different structures than what imgui.cpp sees, which is problematic. // We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui. bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) { bool error = false; if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); } if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); } if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); } if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); } if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); } if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); } if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); } return !error; } static void ImGui::ErrorCheckNewFrameSanityChecks() { ImGuiContext& g = *GImGui; // Check user IM_ASSERT macro // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means you assert macro is incorrectly defined! // If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block. // This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.) // #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong! // #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct! if (true) IM_ASSERT(1); else IM_ASSERT(0); // Check user data // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) IM_ASSERT(g.Initialized); IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?"); IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()?"); IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.CircleSegmentMaxError > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right); for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP) if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) g.IO.ConfigWindowsResizeFromEdges = false; } static void ImGui::ErrorCheckEndFrameSanityChecks() { ImGuiContext& g = *GImGui; // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame() // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame(). // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs. // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0), // while still correctly asserting on mid-frame key press events. const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags(); IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); IM_UNUSED(key_mod_flags); // Recover from errors //ErrorCheckEndFrameRecover(); // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API). if (g.CurrentWindowStack.Size != 1) { if (g.CurrentWindowStack.Size > 1) { IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?"); while (g.CurrentWindowStack.Size > 1) End(); } else { IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?"); } } IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!"); } // Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls. // Must be called during or before EndFrame(). // This is generally flawed as we are not necessarily End/Popping things in the right order. // FIXME: Can't recover from inside BeginTabItem/EndTabItem yet. // FIXME: Can't recover from interleaved BeginTabBar/Begin void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data) { // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations" ImGuiContext& g = *GImGui; while (g.CurrentWindowStack.Size > 0) { #ifdef IMGUI_HAS_TABLE while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow)) { if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name); EndTable(); } #endif ImGuiWindow* window = g.CurrentWindow; while (g.CurrentTabBar != NULL) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name); EndTabBar(); } while (g.CurrentWindow->DC.TreeDepth > 0) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name); TreePop(); } while (g.GroupStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfGroupStack) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name); EndGroup(); } while (g.CurrentWindow->IDStack.Size > 1) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name); PopID(); } while (g.ColorStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfColorStack) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col)); PopStyleColor(); } while (g.StyleVarStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfStyleVarStack) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name); PopStyleVar(); } while (g.FocusScopeStack.Size > g.CurrentWindow->DC.StackSizesOnBegin.SizeOfFocusScopeStack) //-V1044 { if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name); PopFocusScope(); } if (g.CurrentWindowStack.Size == 1) { IM_ASSERT(g.CurrentWindow->IsFallbackWindow); break; } if (g.CurrentWindow->Flags & ImGuiWindowFlags_ChildWindow) { if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name); EndChild(); } else { if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name); End(); } } } // Save current stack sizes for later compare void ImGuiStackSizes::SetToCurrentState() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; SizeOfIDStack = (short)window->IDStack.Size; SizeOfColorStack = (short)g.ColorStack.Size; SizeOfStyleVarStack = (short)g.StyleVarStack.Size; SizeOfFontStack = (short)g.FontStack.Size; SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size; SizeOfGroupStack = (short)g.GroupStack.Size; SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size; } // Compare to detect usage errors void ImGuiStackSizes::CompareWithCurrentState() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Window stacks // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!"); // Global stacks // 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. IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!"); IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!"); IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!"); IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!"); IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!"); IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!"); } //----------------------------------------------------------------------------- // [SECTION] LAYOUT //----------------------------------------------------------------------------- // - ItemSize() // - ItemAdd() // - SameLine() // - GetCursorScreenPos() // - SetCursorScreenPos() // - GetCursorPos(), GetCursorPosX(), GetCursorPosY() // - SetCursorPos(), SetCursorPosX(), SetCursorPosY() // - GetCursorStartPos() // - Indent() // - Unindent() // - SetNextItemWidth() // - PushItemWidth() // - PushMultiItemsWidths() // - PopItemWidth() // - CalcItemWidth() // - CalcItemSize() // - GetTextLineHeight() // - GetTextLineHeightWithSpacing() // - GetFrameHeight() // - GetFrameHeightWithSpacing() // - GetContentRegionMax() // - GetContentRegionMaxAbs() [Internal] // - GetContentRegionAvail(), // - GetWindowContentRegionMin(), GetWindowContentRegionMax() // - GetWindowContentRegionWidth() // - BeginGroup() // - EndGroup() // Also see in imgui_widgets: tab bars, columns. //----------------------------------------------------------------------------- // Advance cursor given item size for layout. // Register minimum needed size so it can extend the bounding box used for auto-fit calculation. // See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different. void ImGui::ItemSize(const ImVec2& size, float text_baseline_y) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return; // We increase the height in this function to accommodate for baseline offset. // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor, // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect. const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f; const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y); // Always align ourselves on pixel boundaries //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG] window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x; window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y; window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y); //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG] window->DC.PrevLineSize.y = line_height; window->DC.CurrLineSize.y = 0.0f; window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y); window->DC.CurrLineTextBaseOffset = 0.0f; // Horizontal layout mode if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) SameLine(); } void ImGui::ItemSize(const ImRect& bb, float text_baseline_y) { ItemSize(bb.GetSize(), text_baseline_y); } // Declare item bounding box for clipping and interaction. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface // declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction. bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (id != 0) { // Navigation processing runs prior to clipping early-out // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests // unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of // thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able // to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null. // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere. window->DC.NavLayerActiveMaskNext |= (1 << window->DC.NavLayerCurrent); if (g.NavId == id || g.NavAnyRequest) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id); // [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd() #ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX if (id == g.DebugItemPickerBreakId) { IM_DEBUG_BREAK(); g.DebugItemPickerBreakId = 0; } #endif } // Equivalent to calling SetLastItemData() window->DC.LastItemId = id; window->DC.LastItemRect = bb; window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None; g.NextItemData.Flags = ImGuiNextItemDataFlags_None; #ifdef IMGUI_ENABLE_TEST_ENGINE if (id != 0) IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id); #endif // Clipping test const bool is_clipped = IsClippedEx(bb, id, false); if (is_clipped) return false; //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them) if (IsMouseHoveringRect(bb.Min, bb.Max)) window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect; return true; } // Gets back to previous line and continue with horizontal layout // offset_from_start_x == 0 : follow right after previous item // offset_from_start_x != 0 : align to specified x position (relative to window/group left) // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 // spacing_w >= 0 : enforce spacing amount void ImGui::SameLine(float offset_from_start_x, float spacing_w) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; if (offset_from_start_x != 0.0f) { if (spacing_w < 0.0f) spacing_w = 0.0f; window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } else { if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } window->DC.CurrLineSize = window->DC.PrevLineSize; window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; } ImVec2 ImGui::GetCursorScreenPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos; } void ImGui::SetCursorScreenPos(const ImVec2& pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = window->Pos - window->Scroll + local_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } ImVec2 ImGui::GetCursorStartPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorStartPos - window->Pos; } void ImGui::Indent(float indent_w) { 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; } void ImGui::Unindent(float indent_w) { 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; } // Affect large frame+labels widgets only. void ImGui::SetNextItemWidth(float item_width) { ImGuiContext& g = *GImGui; g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth; g.NextItemData.Width = item_width; } void ImGui::PushItemWidth(float item_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; } void ImGui::PushMultiItemsWidths(int components, float w_full) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiStyle& style = g.Style; const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); window->DC.ItemWidthStack.push_back(w_item_last); for (int i = 0; i < components - 1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidthStack.pop_back(); window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(). // The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() float ImGui::CalcItemWidth() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float w; if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth) w = g.NextItemData.Width; else w = window->DC.ItemWidth; if (w < 0.0f) { float region_max_x = GetContentRegionMaxAbs().x; w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); } w = IM_FLOOR(w); return w; } // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. // Note that only CalcItemWidth() is publicly exposed. // 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; ImVec2 region_max; if (size.x < 0.0f || size.y < 0.0f) region_max = GetContentRegionMaxAbs(); if (size.x == 0.0f) size.x = default_w; else if (size.x < 0.0f) size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x); if (size.y == 0.0f) size.y = default_h; else if (size.y < 0.0f) size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y); return size; } float ImGui::GetTextLineHeight() { ImGuiContext& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } float ImGui::GetFrameHeight() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f; } float ImGui::GetFrameHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; } // FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience! // FIXME: This is in window space (not screen space!). ImVec2 ImGui::GetContentRegionMax() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImVec2 mx = window->ContentRegionRect.Max - window->Pos; if (window->DC.CurrentColumns) mx.x = window->WorkRect.Max.x - window->Pos.x; return mx; } // [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; ImVec2 mx = window->ContentRegionRect.Max; if (window->DC.CurrentColumns) mx.x = window->WorkRect.Max.x; return mx; } ImVec2 ImGui::GetContentRegionAvail() { ImGuiWindow* window = GImGui->CurrentWindow; return GetContentRegionMaxAbs() - window->DC.CursorPos; } // In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentRegionRect.Min - window->Pos; } ImVec2 ImGui::GetWindowContentRegionMax() { ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentRegionRect.Max - window->Pos; } float ImGui::GetWindowContentRegionWidth() { ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentRegionRect.GetWidth(); } // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) // Groups are currently a mishmash of functionalities which should perhaps be clarified and separated. void ImGui::BeginGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; g.GroupStack.resize(g.GroupStack.Size + 1); ImGuiGroupData& group_data = g.GroupStack.back(); group_data.WindowID = window->ID; group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.BackupIndent = window->DC.Indent; group_data.BackupGroupOffset = window->DC.GroupOffset; group_data.BackupCurrLineSize = window->DC.CurrLineSize; group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset; group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; group_data.EmitItem = true; window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; window->DC.Indent = window->DC.GroupOffset; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); if (g.LogEnabled) g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return } void ImGui::EndGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = g.GroupStack.back(); IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window? 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); window->DC.Indent = group_data.BackupIndent; window->DC.GroupOffset = group_data.BackupGroupOffset; window->DC.CurrLineSize = group_data.BackupCurrLineSize; window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset; if (g.LogEnabled) g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return if (!group_data.EmitItem) { g.GroupStack.pop_back(); return; } window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ItemSize(group_bb.GetSize()); ItemAdd(group_bb, 0); // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. // Also if you grep for LastItemId you'll notice it is only used in that context. // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.) const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId; const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true); if (group_contains_curr_active_id) window->DC.LastItemId = g.ActiveId; else if (group_contains_prev_active_id) window->DC.LastItemId = g.ActiveIdPreviousFrame; window->DC.LastItemRect = group_bb; // Forward Edited flag if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame) window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited; // Forward Deactivated flag window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated; if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame) window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated; g.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] } //----------------------------------------------------------------------------- // [SECTION] SCROLLING //----------------------------------------------------------------------------- // Helper to snap on edges when aiming at an item very close to the edge, // So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. // When we refactor the scrolling API this may be configurable with a flag? // Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio) { if (target <= snap_min + snap_threshold) return ImLerp(snap_min, target, center_ratio); if (target >= snap_max - snap_threshold) return ImLerp(target, snap_max, center_ratio); return target; } static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) { ImVec2 scroll = window->Scroll; if (window->ScrollTarget.x < FLT_MAX) { float center_x_ratio = window->ScrollTargetCenterRatio.x; float scroll_target_x = window->ScrollTarget.x; float snap_x_min = 0.0f; float snap_x_max = window->ScrollMax.x + window->Size.x; if (window->ScrollTargetEdgeSnapDist.x > 0.0f) scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio); scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - window->ScrollbarSizes.x); } if (window->ScrollTarget.y < FLT_MAX) { float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); float center_y_ratio = window->ScrollTargetCenterRatio.y; float scroll_target_y = window->ScrollTarget.y; float snap_y_min = 0.0f; float snap_y_max = window->ScrollMax.y + window->Size.y - decoration_up_height; if (window->ScrollTargetEdgeSnapDist.y > 0.0f) scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio); scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - window->ScrollbarSizes.y - decoration_up_height); } scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f)); scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f)); if (!window->Collapsed && !window->SkipItems) { scroll.x = ImMin(scroll.x, window->ScrollMax.x); scroll.y = ImMin(scroll.y, window->ScrollMax.y); } return scroll; } // 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)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] ImVec2 delta_scroll; if (!window_rect.Contains(item_rect)) { if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x - g.Style.ItemSpacing.x, 0.0f); else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f); if (item_rect.Min.y < window_rect.Min.y) SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f); 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); delta_scroll = next_scroll - window->Scroll; } // Also scroll parent window to keep us into view if necessary if (window->Flags & ImGuiWindowFlags_ChildWindow) delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll)); return delta_scroll; } float ImGui::GetScrollX() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Scroll.x; } float ImGui::GetScrollY() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Scroll.y; } float ImGui::GetScrollMaxX() { ImGuiWindow* window = GImGui->CurrentWindow; return window->ScrollMax.x; } float ImGui::GetScrollMaxY() { ImGuiWindow* window = GImGui->CurrentWindow; return window->ScrollMax.y; } void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x) { window->ScrollTarget.x = scroll_x; window->ScrollTargetCenterRatio.x = 0.0f; window->ScrollTargetEdgeSnapDist.x = 0.0f; } void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y) { window->ScrollTarget.y = scroll_y; window->ScrollTargetCenterRatio.y = 0.0f; window->ScrollTargetEdgeSnapDist.y = 0.0f; } void ImGui::SetScrollX(float scroll_x) { ImGuiContext& g = *GImGui; SetScrollX(g.CurrentWindow, scroll_x); } void ImGui::SetScrollY(float scroll_y) { ImGuiContext& g = *GImGui; SetScrollY(g.CurrentWindow, scroll_y); } // Note that a local position will vary depending on initial scroll value, // This is a little bit confusing so bear with us: // - local_pos = (absolution_pos - window->Pos) // - So local_x/local_y are 0.0f for a position at the upper-left corner of a window, // and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area. // - They mostly exists because of legacy API. // Following the rules above, when trying to work with scrolling code, consider that: // - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect! // - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense // We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio) { IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset window->ScrollTargetCenterRatio.x = center_x_ratio; window->ScrollTargetEdgeSnapDist.x = 0.0f; } void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio) { IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset window->ScrollTargetCenterRatio.y = center_y_ratio; window->ScrollTargetEdgeSnapDist.y = 0.0f; } void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) { ImGuiContext& g = *GImGui; SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio); } void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) { 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; float spacing_x = g.Style.ItemSpacing.x; float target_pos_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio); SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos // Tweak: snap on edges when aiming at an item very close to the edge window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x); } // 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; float spacing_y = g.Style.ItemSpacing.y; float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio); SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos // Tweak: snap on edges when aiming at an item very close to the edge window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y); } //----------------------------------------------------------------------------- // [SECTION] TOOLTIPS //----------------------------------------------------------------------------- void ImGui::BeginTooltip() { BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None); } void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags) { ImGuiContext& g = *GImGui; if (g.DragDropWithinSource || g.DragDropWithinTarget) { // 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); 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 :( tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip; } char window_name[16]; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount); if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip) if (ImGuiWindow* window = FindWindowByName(window_name)) if (window->Active) { // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. window->Hidden = true; 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; Begin(window_name, NULL, flags | extra_flags); } void ImGui::EndTooltip() { IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls End(); } void ImGui::SetTooltipV(const char* fmt, va_list args) { BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip); TextV(fmt, args); EndTooltip(); } void ImGui::SetTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); SetTooltipV(fmt, args); va_end(args); } //----------------------------------------------------------------------------- // [SECTION] POPUPS //----------------------------------------------------------------------------- // Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; if (popup_flags & ImGuiPopupFlags_AnyPopupId) { // Return true if any popup is open at the current BeginPopup() level of the popup stack // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level. IM_ASSERT(id == 0); if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) return g.OpenPopupStack.Size > 0; else return g.OpenPopupStack.Size > g.BeginPopupStack.Size; } else { if (popup_flags & ImGuiPopupFlags_AnyPopupLevel) { // Return true if the popup is open anywhere in the popup stack for (int n = 0; n < g.OpenPopupStack.Size; n++) if (g.OpenPopupStack[n].PopupId == id) return true; return false; } else { // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query) return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; } } } bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id); if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0) IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally return IsPopupOpen(id, popup_flags); } ImGuiWindow* ImGui::GetTopMostPopupModal() { 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) return popup; return NULL; } void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags); } // Mark popup as open (toggle toward open state). // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; const int current_stack_size = g.BeginPopupStack.Size; if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup) if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId)) return; 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; popup_ref.SourceWindow = g.NavWindow; popup_ref.OpenFrameCount = g.FrameCount; popup_ref.OpenParentId = parent_window->IDStack.back(); popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id); if (g.OpenPopupStack.Size < current_stack_size + 1) { g.OpenPopupStack.push_back(popup_ref); } else { // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) { g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount; } else { // Close child popups if any, then flag popup for open/reopen ClosePopupToLevel(current_stack_size, false); g.OpenPopupStack.push_back(popup_ref); } // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). // This is equivalent to what ClosePopupToLevel() does. //if (g.OpenPopupStack[current_stack_size].PopupId == id) // FocusWindow(parent_window); } } // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. // This function closes any popups that are over 'ref_window'. void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size == 0) return; // Don't close our own child popup windows. int popup_count_to_keep = 0; if (ref_window) { // 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]; if (!popup.Window) continue; IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) continue; // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow) // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3: // Window -> Popup1 -> Popup2 -> Popup3 // - Each popups may contain child windows, which is why we compare ->RootWindow! // Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child bool ref_window_is_descendent_of_popup = false; for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++) if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window) if (popup_window->RootWindow == ref_window->RootWindow) { ref_window_is_descendent_of_popup = true; break; } if (!ref_window_is_descendent_of_popup) break; } } if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below { IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep); ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup); } } void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup); IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); // Trim open popup stack ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow; ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window; g.OpenPopupStack.resize(remaining); if (restore_focus_to_window_under_popup) { if (focus_window && !focus_window->WasActive && popup_window) { // Fallback FocusTopMostWindowUnderOne(popup_window, NULL); } else { if (g.NavLayer == ImGuiNavLayer_Main && focus_window) focus_window = NavRestoreLastChildNavWindow(focus_window); FocusWindow(focus_window); } } } // Close the popup we have begin-ed into. void ImGui::CloseCurrentPopup() { ImGuiContext& g = *GImGui; int popup_idx = g.BeginPopupStack.Size - 1; if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) return; // 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; bool close_parent = false; if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu)) if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal)) close_parent = true; if (!close_parent) break; popup_idx--; } IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); ClosePopupToLevel(popup_idx, true); // A common pattern is to close a popup when selecting a menu item/selectable that will open another window. // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window. // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic. if (ImGuiWindow* window = g.NavWindow) window->DC.NavHideHighlightOneFrame = true; } // Attention! BeginPopup() adds default flags which BeginPopupEx()! bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; if (!IsPopupOpen(id, ImGuiPopupFlags_None)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } char name[20]; if (flags & ImGuiWindowFlags_ChildMenu) ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth else ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame flags |= ImGuiWindowFlags_Popup; bool is_open = Begin(name, NULL, flags); if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) EndPopup(); return is_open; } bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags); } // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. // Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(name); if (!IsPopupOpen(id, ImGuiPopupFlags_None)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } // Center modal windows by default for increased visibility // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves) // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0) SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse; const bool is_open = Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { EndPopup(); if (is_open) ClosePopupToLevel(g.BeginPopupStack.Size, true); return false; } return is_open; } void ImGui::EndPopup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls IM_ASSERT(g.BeginPopupStack.Size > 0); // Make all menus and popups wrap around for now, may need to expose that policy. if (g.NavWindow == window) NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY); // Child-popups don't need to be laid out IM_ASSERT(g.WithinEndChild == false); if (window->Flags & ImGuiWindowFlags_ChildWindow) g.WithinEndChild = true; End(); g.WithinEndChild = false; } // Helper to open a popup if mouse button is released over the item // - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); 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! 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, popup_flags); } } // This is a helper to handle the simplest case of associating one named popup to one given widget. // - You can pass a NULL str_id to use the identifier of the last item. // - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // - This is essentially the same as calling OpenPopupOnItemClick() + BeginPopup() but written to avoid // computing the ID twice because BeginPopupContextXXX functions may be called very frequently. bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags) { 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! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "window_context"; ImGuiID id = window->GetID(str_id); int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered()) OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags) { ImGuiWindow* window = GImGui->CurrentWindow; if (!str_id) str_id = "void_context"; ImGuiID id = window->GetID(str_id); int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) if (GetTopMostPopupModal() == NULL) OpenPopupEx(id, popup_flags); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings); } // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) // 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); //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)); // Combo Box policy (we want a connecting edge) if (policy == ImGuiPopupPositionPolicy_ComboBox) { const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) { const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; ImVec2 pos; if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default) if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left if (!r_outer.Contains(ImRect(pos, pos + size))) continue; *last_dir = dir; return pos; } } // Tooltip and Default popup policy // (Always first try the direction we used on the last frame, if any) if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default) { const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) { const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; 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 there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width) if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right)) continue; if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down)) continue; ImVec2 pos; pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; // Clamp top-left corner of popup pos.x = ImMax(pos.x, r_outer.Min.x); pos.y = ImMax(pos.y, r_outer.Min.y); *last_dir = dir; return pos; } } // Fallback when not enough room: *last_dir = ImGuiDir_None; // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. if (policy == ImGuiPopupPositionPolicy_Tooltip) return ref_pos + ImVec2(2, 2); // Otherwise try to keep within display ImVec2 pos = ref_pos; pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); return pos; } ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window) { IM_UNUSED(window); 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; } ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) { ImGuiContext& g = *GImGui; 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). ImRect r_avoid; if (parent_window->DC.MenuBarAppending) r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field else r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default); } if (window->Flags & ImGuiWindowFlags_Popup) { ImRect 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, ImGuiPopupPositionPolicy_Default); } if (window->Flags & ImGuiWindowFlags_Tooltip) { // Position tooltip (always follows mouse) float sc = g.Style.MouseCursorScale; 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); else r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important. return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip); } IM_ASSERT(0); return window->Pos; } //----------------------------------------------------------------------------- // [SECTION] KEYBOARD/GAMEPAD NAVIGATION //----------------------------------------------------------------------------- // FIXME-NAV: The existence of SetNavID vs SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing, // and needs some explanation or serious refactoring. void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindow); IM_ASSERT(nav_layer == 0 || nav_layer == 1); g.NavId = id; g.NavFocusScopeId = focus_scope_id; g.NavWindow->NavLastIds[nav_layer] = id; } void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel) { ImGuiContext& g = *GImGui; SetNavID(id, nav_layer, focus_scope_id); g.NavWindow->NavRectRel[nav_layer] = rect_rel; g.NavMousePosDirty = true; g.NavDisableHighlight = false; g.NavDisableMouseHover = true; } void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; IM_ASSERT(id != 0); // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid. // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text) const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent; if (g.NavWindow != window) g.NavInitRequest = false; g.NavWindow = window; g.NavId = id; g.NavLayer = nav_layer; g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent; window->NavLastIds[nav_layer] = id; if (window->DC.LastItemId == id) window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos); if (g.ActiveIdSource == ImGuiInputSource_Nav) g.NavDisableMouseHover = true; else g.NavDisableHighlight = true; } ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy) { if (ImFabs(dx) > ImFabs(dy)) return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left; return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up; } static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1) { if (a1 < b0) return a1 - b0; if (b1 < a0) return a0 - b1; return 0.0f; } static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect) { if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) { r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y); r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y); } else { r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x); r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x); } } // Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057 static bool ImGui::NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavLayer != window->DC.NavLayerCurrent) return false; const ImRect& curr = g.NavScoringRect; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width) g.NavScoringCount++; // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring if (window->ParentWindow == g.NavWindow) { IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened); if (!window->ClipRect.Overlaps(cand)) return false; cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window } // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items) // For example, this ensure that items in one column are not reached when moving vertically from items in another column. NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect); // 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 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); // 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) // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance ImGuiDir quadrant; float dax = 0.0f, day = 0.0f, dist_axial = 0.0f; if (dbx != 0.0f || dby != 0.0f) { // For non-overlapping boxes, use distance between boxes dax = dbx; day = dby; dist_axial = dist_box; quadrant = ImGetDirQuadrantFromDelta(dbx, dby); } else if (dcx != 0.0f || dcy != 0.0f) { // For overlapping boxes with different centers, use distance between centers dax = dcx; day = dcy; dist_axial = dist_center; quadrant = ImGetDirQuadrantFromDelta(dcx, dcy); } else { // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right; } #if IMGUI_DEBUG_NAV_SCORING char buf[128]; if (IsMouseHoveringRect(cand.Min, cand.Max)) { ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]); ImDrawList* draw_list = GetForegroundDrawList(window); draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100)); draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200)); draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150)); draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf); } else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate. { if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; } if (quadrant == g.NavMoveDir) { ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center); ImDrawList* draw_list = GetForegroundDrawList(window); draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200)); draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf); } } #endif // Is it in the quadrant we're interesting in moving to? bool new_best = false; if (quadrant == g.NavMoveDir) { // Does it beat the current best candidate? if (dist_box < result->DistBox) { result->DistBox = dist_box; result->DistCenter = dist_center; return true; } if (dist_box == result->DistBox) { // Try using distance between center points to break ties if (dist_center < result->DistCenter) { result->DistCenter = dist_center; new_best = true; } else if (dist_center == result->DistCenter) { // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance new_best = true; } } } // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f)) { result->DistAxial = dist_axial; new_best = true; } return new_best; } static void ImGui::NavApplyItemToResult(ImGuiNavMoveResult* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel) { result->Window = window; result->ID = id; result->FocusScopeId = window->DC.NavFocusScopeIdCurrent; result->RectRel = nav_bb_rel; } // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id) { ImGuiContext& g = *GImGui; //if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag. // return; const ImGuiItemFlags item_flags = window->DC.ItemFlags; const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos); // Process Init Request if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent) { // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0) { g.NavInitResultId = id; g.NavInitResultRectRel = nav_bb_rel; } if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus)) { g.NavInitRequest = false; // Found a match, clear request NavUpdateAnyRequestFlag(); } } // Process Move Request (scoring for navigation) // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy) if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav))) { ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; #if IMGUI_DEBUG_NAV_SCORING // [DEBUG] Score all items in NavWindow at all times if (!g.NavMoveRequest) g.NavMoveDir = g.NavMoveDirLast; bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest; #else bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); #endif if (new_best) NavApplyItemToResult(result, window, id, nav_bb_rel); // Features like PageUp/PageDown need to maintain a separate score for the visible set of items. const float VISIBLE_RATIO = 0.70f; if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb)) if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb)) NavApplyItemToResult(&g.NavMoveResultLocalVisibleSet, window, id, nav_bb_rel); } // Update window-relative bounding box of navigated item if (g.NavId == id) { g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window. g.NavLayer = window->DC.NavLayerCurrent; g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent; g.NavIdIsAlive = true; g.NavIdTabCounter = window->DC.FocusCounterTabStop; window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position) } } bool ImGui::NavMoveRequestButNoResultYet() { ImGuiContext& g = *GImGui; return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0; } void ImGui::NavMoveRequestCancel() { ImGuiContext& g = *GImGui; g.NavMoveRequest = false; NavUpdateAnyRequestFlag(); } void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None); NavMoveRequestCancel(); g.NavMoveDir = move_dir; g.NavMoveClipDir = clip_dir; g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; g.NavMoveRequestFlags = move_flags; g.NavWindow->NavRectRel[g.NavLayer] = bb_rel; } void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags) { ImGuiContext& g = *GImGui; // Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire // popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. g.NavWrapRequestWindow = window; g.NavWrapRequestFlags = move_flags; } // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). // This way we could find the last focused window among our children. It would be much less confusing this way? static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window) { ImGuiWindow* parent = nav_window; while (parent && (parent->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) parent = parent->ParentWindow; if (parent && parent != nav_window) parent->NavLastChildNavWindow = nav_window; } // Restore the last focused child. // Call when we are expected to land on the Main Layer (0) after FocusWindow() static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window) { if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive) return window->NavLastChildNavWindow; return window; } static void NavRestoreLayer(ImGuiNavLayer layer) { ImGuiContext& g = *GImGui; g.NavLayer = layer; if (layer == 0) g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow); ImGuiWindow* window = g.NavWindow; if (layer == 0 && window->NavLastIds[0] != 0) ImGui::SetNavIDWithRectRel(window->NavLastIds[0], layer, 0, window->NavRectRel[0]); else ImGui::NavInitWindow(window, true); } static inline void ImGui::NavUpdateAnyRequestFlag() { ImGuiContext& g = *GImGui; g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL); if (g.NavAnyRequest) IM_ASSERT(g.NavWindow != NULL); } // This needs to be called before we submit any widget (aka in or before Begin) void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) { ImGuiContext& g = *GImGui; IM_ASSERT(window == g.NavWindow); bool init_for_nav = false; if (!(window->Flags & ImGuiWindowFlags_NoNavInputs)) if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) init_for_nav = true; IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer); if (init_for_nav) { SetNavID(0, g.NavLayer, 0); g.NavInitRequest = true; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; g.NavInitResultRectRel = ImRect(); NavUpdateAnyRequestFlag(); } else { g.NavId = window->NavLastIds[0]; g.NavFocusScopeId = 0; } } static ImVec2 ImGui::NavCalcPreferredRefPos() { ImGuiContext& g = *GImGui; if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow) { // Mouse (we need a fallback in case the mouse becomes invalid after being used) if (IsMousePosValid(&g.IO.MousePos)) return g.IO.MousePos; return g.LastValidMousePos; } else { // 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(); return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta. } } float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode) { ImGuiContext& g = *GImGui; if (mode == ImGuiInputReadMode_Down) return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user) const float t = g.IO.NavInputsDownDuration[n]; if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f); if (t < 0.0f) return 0.0f; if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input. return (t == 0.0f) ? 1.0f : 0.0f; if (mode == ImGuiInputReadMode_Repeat) return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f); if (mode == ImGuiInputReadMode_RepeatSlow) return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f); if (mode == ImGuiInputReadMode_RepeatFast) return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f); return 0.0f; } ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor) { ImVec2 delta(0.0f, 0.0f); if (dir_sources & ImGuiNavDirSourceFlags_Keyboard) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode)); if (dir_sources & ImGuiNavDirSourceFlags_PadDPad) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode)); if (dir_sources & ImGuiNavDirSourceFlags_PadLStick) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode)); if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow)) delta *= slow_factor; if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast)) delta *= fast_factor; return delta; } static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; io.WantSetMousePos = false; g.NavWrapRequestWindow = NULL; g.NavWrapRequestFlags = ImGuiNavMoveFlags_None; #if 0 if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); #endif // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard) // (do it before we map Keyboard input!) bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_NavGamepad) { if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f || io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f) g.NavInputSource = ImGuiInputSource_NavGamepad; } // Update Keyboard->Nav inputs mapping if (nav_keyboard_active) { #define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(io.KeyMap[_KEY])) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } } while (0) NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate ); NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input ); NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel ); NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ ); NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_); NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ ); NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ ); if (io.KeyCtrl) io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; if (io.KeyShift) io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; if (io.KeyAlt && !io.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu. io.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; #undef NAV_MAP_KEY } memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f; // Process navigation init request (select first/default focus) if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove)) NavUpdateInitResult(); g.NavInitRequest = false; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; g.NavJustMovedToId = 0; // Process navigation move request if (g.NavMoveRequest) NavUpdateMoveResult(); // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive) { IM_ASSERT(g.NavMoveRequest); if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0) g.NavDisableHighlight = false; g.NavMoveRequestForward = ImGuiNavForward_None; } // Apply application mouse position movement, after we had a chance to process move request result. if (g.NavMousePosDirty && g.NavIdIsAlive) { // Set mouse position given our knowledge of the navigated item position from last frame if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) { if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow) { io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos(); io.WantSetMousePos = true; } } g.NavMousePosDirty = false; } g.NavIdIsAlive = false; g.NavJustTabbedId = 0; IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1); // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0 if (g.NavWindow) NavSaveLastChildNavWindowIntoParent(g.NavWindow); if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main) g.NavWindow->NavLastChildNavWindow = NULL; // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.) NavUpdateWindowing(); // Set output flags for user application io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL); // Process NavCancel input (to close a popup, get back to parent, clear focus) if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed)) { IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n"); if (g.ActiveId != 0) { if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel)) ClearActiveID(); } 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; ImGuiWindow* parent_window = g.NavWindow->ParentWindow; IM_ASSERT(child_window->ChildId != 0); FocusWindow(parent_window); SetNavID(child_window->ChildId, 0, 0); // Reassigning with same value, we're being explicit here. g.NavIdIsAlive = false; // -V1048 if (g.NavDisableMouseHover) g.NavMousePosDirty = true; } else if (g.OpenPopupStack.Size > 0) { // Close open popup/menu if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal)) ClosePopupToLevel(g.OpenPopupStack.Size - 1, true); } else if (g.NavLayer != ImGuiNavLayer_Main) { // Leave the "menu" layer NavRestoreLayer(ImGuiNavLayer_Main); } else { // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow))) g.NavWindow->NavLastIds[0] = 0; g.NavId = g.NavFocusScopeId = 0; } } // Process manual activation request 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 && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed); if (g.ActiveId == 0 && activate_pressed) g.NavActivateId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down) g.NavActivateDownId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed) g.NavActivatePressedId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed)) g.NavInputId = g.NavId; } if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) g.NavDisableHighlight = true; if (g.NavActivateId != 0) IM_ASSERT(g.NavActivateDownId == g.NavActivateId); g.NavMoveRequest = false; // Process programmatic activation request if (g.NavNextActivateId != 0) g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId; g.NavNextActivateId = 0; // Initiate directional inputs request if (g.NavMoveRequestForward == ImGuiNavForward_None) { g.NavMoveDir = ImGuiDir_None; g.NavMoveRequestFlags = ImGuiNavMoveFlags_None; if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) { const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat; if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; } if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; } if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; } if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; } } g.NavMoveClipDir = g.NavMoveDir; } else { // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window) // (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function) IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None); IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued); IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir); g.NavMoveRequestForward = ImGuiNavForward_ForwardActive; } // Update PageUp/PageDown/Home/End scroll // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag? float nav_scoring_rect_offset_y = 0.0f; if (nav_keyboard_active) nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(); // If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match if (g.NavMoveDir != ImGuiDir_None) { g.NavMoveRequest = true; g.NavMoveRequestKeyMods = io.KeyMods; g.NavMoveDirLast = g.NavMoveDir; } if (g.NavMoveRequest && g.NavId == 0) { IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer); g.NavInitRequest = g.NavInitRequestFromMove = true; // Reassigning with same value, we're being explicit here. g.NavInitResultId = 0; // -V1048 g.NavDisableHighlight = false; } NavUpdateAnyRequestFlag(); // Scrolling if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget) { // *Fallback* manual-scroll with Nav directional keys when window has no navigable item ImGuiWindow* window = g.NavWindow; const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest) { if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) SetScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); } // *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); if (scroll_dir.x != 0.0f && window->ScrollbarX) SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); if (scroll_dir.y != 0.0f) SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); } // Reset search results g.NavMoveResultLocal.Clear(); g.NavMoveResultLocalVisibleSet.Clear(); g.NavMoveResultOther.Clear(); // When using gamepad, we project the reference nav bounding box into window visible area. // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative // (can't focus a visible object like we can with the mouse). if (g.NavMoveRequest && g.NavInputSource == ImGuiInputSource_NavGamepad && g.NavLayer == ImGuiNavLayer_Main) { ImGuiWindow* window = g.NavWindow; 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])) { IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel\n"); 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].ClipWithFull(window_rect_rel); g.NavId = g.NavFocusScopeId = 0; } } // 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] : ImRect(0, 0, 0, 0); g.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y); g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x); g.NavScoringRect.Max.x = g.NavScoringRect.Min.x; IM_ASSERT(!g.NavScoringRect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem(). //GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG] g.NavScoringCount = 0; #if IMGUI_DEBUG_NAV_RECTS if (g.NavWindow) { ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow); if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } } #endif } static void ImGui::NavUpdateInitResult() { // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) ImGuiContext& g = *GImGui; if (!g.NavWindow) return; // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name); if (g.NavInitRequestFromMove) SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel); else SetNavID(g.NavInitResultId, g.NavLayer, 0); g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; } // Apply result from previous frame navigation directional move request static void ImGui::NavUpdateMoveResult() { ImGuiContext& g = *GImGui; if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0) { // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) if (g.NavId != 0) { g.NavDisableHighlight = false; g.NavDisableMouseHover = true; } return; } // Select which result to use ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId) result = &g.NavMoveResultLocalVisibleSet; // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter)) result = &g.NavMoveResultOther; IM_ASSERT(g.NavWindow && result->Window); // Scroll to keep newly navigated item fully into view. if (g.NavLayer == ImGuiNavLayer_Main) { ImVec2 delta_scroll; if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge) { 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 { ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs); } // Offset our result position so mouse position can be applied immediately after in NavUpdate() result->RectRel.TranslateX(-delta_scroll.x); result->RectRel.TranslateY(-delta_scroll.y); } ClearActiveID(); g.NavWindow = result->Window; if (g.NavId != result->ID) { // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId) g.NavJustMovedToId = result->ID; g.NavJustMovedToFocusScopeId = result->FocusScopeId; g.NavJustMovedToKeyMods = g.NavMoveRequestKeyMods; } IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name); SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel); } // Handle PageUp/PageDown/Home/End keys static float ImGui::NavUpdatePageUpPageDown() { ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL) return 0.0f; if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != ImGuiNavLayer_Main) return 0.0f; ImGuiWindow* window = g.NavWindow; const bool page_up_held = IsKeyDown(io.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp); const bool page_down_held = IsKeyDown(io.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown); const bool home_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home); const bool end_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End); if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed { if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true)) SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true)) SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); else if (home_pressed) SetScrollY(window, 0.0f); else if (end_pressed) SetScrollY(window, window->ScrollMax.y); } else { ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); float nav_scoring_rect_offset_y = 0.0f; if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true)) { nav_scoring_rect_offset_y = -page_offset_y; g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Up; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true)) { nav_scoring_rect_offset_y = +page_offset_y; g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Down; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } else if (home_pressed) { // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result. // Preserve current horizontal position if we have any. nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y; if (nav_rect_rel.IsInverted()) nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f; g.NavMoveDir = ImGuiDir_Down; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge; } else if (end_pressed) { nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y; if (nav_rect_rel.IsInverted()) nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f; g.NavMoveDir = ImGuiDir_Up; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge; } return nav_scoring_rect_offset_y; } } return 0.0f; } static void ImGui::NavEndFrame() { ImGuiContext& g = *GImGui; // Show CTRL+TAB list window if (g.NavWindowingTarget != NULL) NavUpdateWindowingOverlay(); // Perform wrap-around in menus ImGuiWindow* window = g.NavWrapRequestWindow; ImGuiNavMoveFlags move_flags = g.NavWrapRequestFlags; if (window != NULL && g.NavWindow == window && NavMoveRequestButNoResultYet() && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == ImGuiNavLayer_Main) { IM_ASSERT(move_flags != 0); // No points calling this with no wrapping ImRect bb_rel = window->NavRectRel[0]; ImGuiDir clip_dir = g.NavMoveDir; if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) { bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x; if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) { bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x; if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) { bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y; if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) { bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y; if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } } } static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--) if (g.WindowsFocusOrder[i] == window) return i; return -1; } static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir) if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i])) return g.WindowsFocusOrder[i]; return NULL; } static void NavUpdateWindowingHighlightWindow(int focus_change_dir) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindowingTarget); if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal) return; const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget); ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir); if (!window_target) window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir); if (window_target) // Don't reset windowing target if there's a single window in the list g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target; g.NavWindowingToggleLayer = false; } // Windowing management mode // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer) // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) static void ImGui::NavUpdateWindowing() { ImGuiContext& g = *GImGui; ImGuiWindow* apply_focus_window = NULL; bool apply_toggle_layer = false; ImGuiWindow* modal_window = GetTopMostPopupModal(); bool allow_windowing = (modal_window == NULL); if (!allow_windowing) g.NavWindowingTarget = NULL; // Fade out if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL) { g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f); if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f) g.NavWindowingTargetAnim = NULL; } // Start CTRL-TAB or Square+L/R window selection bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); bool start_windowing_with_keyboard = allow_windowing && !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)) { g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // FIXME-DOCK: Will need to use RootWindowDockStop g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true; g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad; } // Gamepad update g.NavWindowingTimer += g.IO.DeltaTime; if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad) { // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // Select window to focus const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow); if (focus_change_dir != 0) { NavUpdateWindowingHighlightWindow(focus_change_dir); g.NavWindowingHighlightAlpha = 1.0f; } // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) if (!IsNavInputDown(ImGuiNavInput_Menu)) { g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if (g.NavWindowingToggleLayer && g.NavWindow) apply_toggle_layer = true; else if (!g.NavWindowingToggleLayer) apply_focus_window = g.NavWindowingTarget; g.NavWindowingTarget = NULL; } } // Keyboard: Focus if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard) { // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f if (IsKeyPressedMap(ImGuiKey_Tab, true)) NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1); if (!g.IO.KeyCtrl) apply_focus_window = g.NavWindowingTarget; } // Keyboard: Press and Release ALT to toggle menu layer // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of backend clearing releases all keys on ALT-TAB if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed)) g.NavWindowingToggleLayer = true; if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released)) if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev)) apply_toggle_layer = true; // Move window if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove)) { ImVec2 move_delta; if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavInputSource == ImGuiInputSource_NavGamepad) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down); if (move_delta.x != 0.0f || move_delta.y != 0.0f) { const float NAV_MOVE_SPEED = 800.0f; const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow; SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always); MarkIniSettingsDirty(moving_window); g.NavDisableMouseHover = true; } } // Apply final focus if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)) { ClearActiveID(); g.NavDisableHighlight = false; g.NavDisableMouseHover = true; apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window); ClosePopupsOverWindow(apply_focus_window, false); FocusWindow(apply_focus_window); if (apply_focus_window->NavLastIds[0] == 0) NavInitWindow(apply_focus_window, false); // If the window only has a menu layer, select it directly if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu)) g.NavLayer = ImGuiNavLayer_Menu; } if (apply_focus_window) g.NavWindowingTarget = NULL; // Apply menu/layer toggle if (apply_toggle_layer && g.NavWindow) { // Move to parent menu if necessary ImGuiWindow* new_nav_window = g.NavWindow; while (new_nav_window->ParentWindow && (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) new_nav_window = new_nav_window->ParentWindow; if (new_nav_window != g.NavWindow) { ImGuiWindow* old_nav_window = g.NavWindow; FocusWindow(new_nav_window); new_nav_window->NavLastChildNavWindow = old_nav_window; } g.NavDisableHighlight = false; g.NavDisableMouseHover = true; // When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID. const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main; NavRestoreLayer(new_nav_layer); } } // Window has already passed the IsWindowNavFocusable() static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window) { if (window->Flags & ImGuiWindowFlags_Popup) return "(Popup)"; if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0) return "(Main menu bar)"; return "(Untitled)"; } // Overlay displayed when using CTRL+TAB. Called by EndFrame(). void ImGui::NavUpdateWindowingOverlay() { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindowingTarget != NULL); if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) return; if (g.NavWindowingListWindow == NULL) g.NavWindowingListWindow = FindWindowByName("###NavWindowingList"); SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) { ImGuiWindow* window = g.WindowsFocusOrder[n]; if (!IsWindowNavFocusable(window)) continue; const char* label = window->Name; if (label == FindRenderedTextEnd(label)) label = GetFallbackWindowNameForWindowingList(window); Selectable(label, g.NavWindowingTarget == window); } End(); PopStyleVar(); } //----------------------------------------------------------------------------- // [SECTION] DRAG AND DROP //----------------------------------------------------------------------------- void ImGui::ClearDragDrop() { ImGuiContext& g = *GImGui; g.DragDropActive = false; g.DragDropPayload.Clear(); g.DragDropAcceptFlags = ImGuiDragDropFlags_None; g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropAcceptFrameCount = -1; g.DragDropPayloadBufHeap.clear(); memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); } // Call when current ID is active. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; bool source_drag_active = false; ImGuiID source_id = 0; ImGuiID source_parent_id = 0; ImGuiMouseButton mouse_button = ImGuiMouseButton_Left; if (!(flags & ImGuiDragDropFlags_SourceExtern)) { source_id = window->DC.LastItemId; if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case return false; if (g.IO.MouseDown[mouse_button] == false) return false; if (source_id == 0) { // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID)) { IM_ASSERT(0); return false; } // Early out if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window)) return false; // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image() // We build a throwaway ID based on current ID stack + relative AABB of items in window. // 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); if (is_hovered && g.IO.MouseClicked[mouse_button]) { SetActiveID(source_id, window); FocusWindow(window); } if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. g.ActiveIdAllowOverlap = is_hovered; } else { g.ActiveIdAllowOverlap = false; } if (g.ActiveId != source_id) return false; source_parent_id = window->IDStack.back(); source_drag_active = IsMouseDragging(mouse_button); // Disable navigation and key inputs while dragging g.ActiveIdUsingNavDirMask = ~(ImU32)0; g.ActiveIdUsingNavInputMask = ~(ImU32)0; g.ActiveIdUsingKeyInputMask = ~(ImU64)0; } else { window = NULL; source_id = ImHashStr("#SourceExtern"); source_drag_active = true; } if (source_drag_active) { if (!g.DragDropActive) { IM_ASSERT(source_id != 0); ClearDragDrop(); ImGuiPayload& payload = g.DragDropPayload; payload.SourceId = source_id; payload.SourceParentId = source_parent_id; g.DragDropActive = true; g.DragDropSourceFlags = flags; g.DragDropMouseButton = mouse_button; if (payload.SourceId == g.ActiveId) g.ActiveIdNoClearOnFocusLoss = true; } g.DragDropSourceFrameCount = g.FrameCount; g.DragDropWithinSource = true; if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. BeginTooltip(); if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) { ImGuiWindow* tooltip_window = g.CurrentWindow; tooltip_window->SkipItems = true; tooltip_window->HiddenFramesCanSkipItems = 1; } } if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern)) window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect; return true; } return false; } void ImGui::EndDragDropSource() { ImGuiContext& g = *GImGui; IM_ASSERT(g.DragDropActive); IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?"); if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) EndTooltip(); // Discard the drag if have not called SetDragDropPayload() if (g.DragDropPayload.DataFrameCount == -1) ClearDragDrop(); g.DragDropWithinSource = false; } // Use 'cond' to choose to submit payload on drag start or every frame bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond) { ImGuiContext& g = *GImGui; ImGuiPayload& payload = g.DragDropPayload; if (cond == 0) cond = ImGuiCond_Always; IM_ASSERT(type != NULL); IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long"); IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0)); IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once); IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) { // Copy payload ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType)); g.DragDropPayloadBufHeap.resize(0); if (data_size > sizeof(g.DragDropPayloadBufLocal)) { // Store in heap g.DragDropPayloadBufHeap.resize((int)data_size); payload.Data = g.DragDropPayloadBufHeap.Data; memcpy(payload.Data, data, data_size); } else if (data_size > 0) { // Store locally memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); payload.Data = g.DragDropPayloadBufLocal; memcpy(payload.Data, data, data_size); } else { payload.Data = NULL; } payload.DataSize = (int)data_size; } payload.DataFrameCount = g.FrameCount; return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1); } bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) { ImGuiContext& g = *GImGui; if (!g.DragDropActive) return false; ImGuiWindow* window = g.CurrentWindow; ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow) return false; IM_ASSERT(id != 0); if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) return false; if (window->SkipItems) return false; IM_ASSERT(g.DragDropWithinTarget == false); g.DragDropTargetRect = bb; g.DragDropTargetId = id; g.DragDropWithinTarget = true; return true; } // We don't use BeginDragDropTargetCustom() and duplicate its code because: // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) bool ImGui::BeginDragDropTarget() { ImGuiContext& g = *GImGui; if (!g.DragDropActive) return false; ImGuiWindow* window = g.CurrentWindow; if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow; if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow) return false; const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect; ImGuiID id = window->DC.LastItemId; if (id == 0) id = window->GetIDFromRectangle(display_rect); if (g.DragDropPayload.SourceId == id) return false; IM_ASSERT(g.DragDropWithinTarget == false); g.DragDropTargetRect = display_rect; g.DragDropTargetId = id; g.DragDropWithinTarget = true; return true; } bool ImGui::IsDragDropPayloadBeingAccepted() { 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; ImGuiPayload& payload = g.DragDropPayload; IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? if (type != NULL && !payload.IsDataType(type)) return NULL; // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. // 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(); if (r_surface <= g.DragDropAcceptIdCurrRectSurface) { g.DragDropAcceptFlags = flags; g.DragDropAcceptIdCurr = g.DragDropTargetId; g.DragDropAcceptIdCurrRectSurface = r_surface; } // Render default drop visuals payload.Preview = was_accepted_previously; flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame) if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview) { // FIXME-DRAG: Settle on a proper default visuals for drop target. r.Expand(3.5f); 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(); } g.DragDropAcceptFrameCount = g.FrameCount; payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) return NULL; return &payload; } const ImGuiPayload* ImGui::GetDragDropPayload() { ImGuiContext& g = *GImGui; return g.DragDropActive ? &g.DragDropPayload : NULL; } // We don't really use/need this now, but added it for the sake of consistency and because we might need it later. void ImGui::EndDragDropTarget() { ImGuiContext& g = *GImGui; IM_ASSERT(g.DragDropActive); IM_ASSERT(g.DragDropWithinTarget); g.DragDropWithinTarget = false; } //----------------------------------------------------------------------------- // [SECTION] LOGGING/CAPTURING //----------------------------------------------------------------------------- // All text output from the interface can be captured into tty/file/clipboard. // By default, tree nodes are automatically opened during logging. //----------------------------------------------------------------------------- // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; va_list args; va_start(args, fmt); if (g.LogFile) { g.LogBuffer.Buf.resize(0); g.LogBuffer.appendfv(fmt, args); ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile); } else { g.LogBuffer.appendfv(fmt, args); } va_end(args); } // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!text_end) text_end = FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1); if (ref_pos) g.LogLinePosY = ref_pos->y; if (log_new_line) g.LogLineFirstItem = true; const char* text_remaining = text; if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth g.LogDepthRef = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. // We don't add a trailing \n to allow a subsequent item on the same line to be captured. const char* line_start = text_remaining; const char* line_end = ImStreolRange(line_start, text_end); const bool is_first_line = (line_start == text); const bool is_last_line = (line_end == text_end); if (!is_last_line || (line_start != line_end)) { const int char_count = (int)(line_end - line_start); if (log_new_line || !is_first_line) LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start); else if (g.LogLineFirstItem) LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start); else LogText(" %.*s", char_count, line_start); g.LogLineFirstItem = false; } else if (log_new_line) { // An empty "" string at a different Y position should output a carriage return. LogText(IM_NEWLINE); break; } if (is_last_line) break; text_remaining = line_end + 1; } } // Start logging/capturing text output void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.LogEnabled == false); IM_ASSERT(g.LogFile == NULL); IM_ASSERT(g.LogBuffer.empty()); g.LogEnabled = true; g.LogType = type; g.LogDepthRef = window->DC.TreeDepth; g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); g.LogLinePosY = FLT_MAX; g.LogLineFirstItem = true; } void ImGui::LogToTTY(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; IM_UNUSED(auto_open_depth); #ifndef IMGUI_DISABLE_TTY_FUNCTIONS LogBegin(ImGuiLogType_TTY, auto_open_depth); g.LogFile = stdout; #endif } // Start logging/capturing text output to given file void ImGui::LogToFile(int auto_open_depth, const char* filename) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. // By opening the file in binary mode "ab" we have consistent output everywhere. if (!filename) filename = g.IO.LogFilename; if (!filename || !filename[0]) return; ImFileHandle f = ImFileOpen(filename, "ab"); if (!f) { IM_ASSERT(0); return; } LogBegin(ImGuiLogType_File, auto_open_depth); g.LogFile = f; } // Start logging/capturing text output to clipboard void ImGui::LogToClipboard(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; LogBegin(ImGuiLogType_Clipboard, auto_open_depth); } void ImGui::LogToBuffer(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; LogBegin(ImGuiLogType_Buffer, auto_open_depth); } void ImGui::LogFinish() { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; LogText(IM_NEWLINE); switch (g.LogType) { case ImGuiLogType_TTY: #ifndef IMGUI_DISABLE_TTY_FUNCTIONS fflush(g.LogFile); #endif break; case ImGuiLogType_File: ImFileClose(g.LogFile); break; case ImGuiLogType_Buffer: break; case ImGuiLogType_Clipboard: if (!g.LogBuffer.empty()) SetClipboardText(g.LogBuffer.begin()); break; case ImGuiLogType_None: IM_ASSERT(0); break; } g.LogEnabled = false; g.LogType = ImGuiLogType_None; g.LogFile = NULL; g.LogBuffer.clear(); } // Helper to display logging buttons // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) void ImGui::LogButtons() { ImGuiContext& g = *GImGui; PushID("LogButtons"); #ifndef IMGUI_DISABLE_TTY_FUNCTIONS const bool log_to_tty = Button("Log To TTY"); SameLine(); #else const bool log_to_tty = false; #endif const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); PushAllowKeyboardFocus(false); SetNextItemWidth(80.0f); SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); PopAllowKeyboardFocus(); PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) LogToTTY(); if (log_to_file) LogToFile(); if (log_to_clipboard) LogToClipboard(); } //----------------------------------------------------------------------------- // [SECTION] SETTINGS //----------------------------------------------------------------------------- // - UpdateSettings() [Internal] // - MarkIniSettingsDirty() [Internal] // - CreateNewWindowSettings() [Internal] // - FindWindowSettings() [Internal] // - FindOrCreateWindowSettings() [Internal] // - FindSettingsHandler() [Internal] // - ClearIniSettings() [Internal] // - LoadIniSettingsFromDisk() // - LoadIniSettingsFromMemory() // - SaveIniSettingsToDisk() // - SaveIniSettingsToMemory() // - WindowSettingsHandler_***() [Internal] //----------------------------------------------------------------------------- // Called by NewFrame() void ImGui::UpdateSettings() { // Load settings on first frame (if not explicitly loaded manually before) ImGuiContext& g = *GImGui; if (!g.SettingsLoaded) { IM_ASSERT(g.SettingsWindows.empty()); if (g.IO.IniFilename) LoadIniSettingsFromDisk(g.IO.IniFilename); g.SettingsLoaded = true; } // Save settings (with a delay after the last modification, so we don't spam disk too much) if (g.SettingsDirtyTimer > 0.0f) { g.SettingsDirtyTimer -= g.IO.DeltaTime; if (g.SettingsDirtyTimer <= 0.0f) { if (g.IO.IniFilename != NULL) SaveIniSettingsToDisk(g.IO.IniFilename); else g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0f; } } } void ImGui::MarkIniSettingsDirty() { ImGuiContext& g = *GImGui; if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } void ImGui::MarkIniSettingsDirty(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) { ImGuiContext& g = *GImGui; #if !IMGUI_DEBUG_INI_SETTINGS // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier. if (const char* p = strstr(name, "###")) name = p; #endif const size_t name_len = strlen(name); // Allocate chunk const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1; ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size); IM_PLACEMENT_NEW(settings) ImGuiWindowSettings(); settings->ID = ImHashStr(name, name_len); memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator return settings; } ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) { ImGuiContext& g = *GImGui; for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (settings->ID == id) return settings; return NULL; } ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) { if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name))) return settings; return CreateNewWindowSettings(name); } ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) { ImGuiContext& g = *GImGui; const ImGuiID type_hash = ImHashStr(type_name); for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].TypeHash == type_hash) return &g.SettingsHandlers[handler_n]; return NULL; } void ImGui::ClearIniSettings() { ImGuiContext& g = *GImGui; g.SettingsIniData.clear(); for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].ClearAllFn) g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]); } void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) { size_t file_data_size = 0; char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); if (!file_data) return; LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); IM_FREE(file_data); } // Zero-tolerance, no error reporting, cheap .ini parsing void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()"); //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). // 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); g.SettingsIniData.Buf.resize((int)ini_size + 1); char* const buf = g.SettingsIniData.Buf.Data; char* const buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); buf_end[0] = 0; // Call pre-read handlers // Some types will clear their data (e.g. dock information) some types will allow merge/override (window) for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].ReadInitFn) g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]); void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; char* line_end = NULL; for (char* line = buf; line < buf_end; line = line_end + 1) { // Skip new lines markers, then find end of the line while (*line == '\n' || *line == '\r') line++; line_end = line; while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++; line_end[0] = 0; if (line[0] == ';') continue; if (line[0] == '[' && line_end > line && line_end[-1] == ']') { // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. line_end[-1] = 0; const char* name_end = line_end - 1; const char* type_start = line + 1; char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']'); const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; if (!type_end || !name_start) continue; *type_end = 0; // Overwrite first ']' name_start++; // Skip second '[' entry_handler = FindSettingsHandler(type_start); entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; } else if (entry_handler != NULL && entry_data != NULL) { // Let type handler parse the line entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); } } g.SettingsLoaded = true; // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary) memcpy(buf, ini_data, ini_size); // Call post-read handlers for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].ApplyAllFn) g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]); } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; if (!ini_filename) return; size_t ini_data_size = 0; const char* ini_data = SaveIniSettingsToMemory(&ini_data_size); ImFileHandle f = ImFileOpen(ini_filename, "wt"); if (!f) return; ImFileWrite(ini_data, sizeof(char), ini_data_size, f); ImFileClose(f); } // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; g.SettingsIniData.Buf.resize(0); g.SettingsIniData.Buf.push_back(0); for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) { ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n]; handler->WriteAllFn(&g, handler, &g.SettingsIniData); } if (out_size) *out_size = (size_t)g.SettingsIniData.size(); return g.SettingsIniData.c_str(); } static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { ImGuiContext& g = *ctx; for (int i = 0; i != g.Windows.Size; i++) g.Windows[i]->SettingsOffset = -1; g.SettingsWindows.clear(); } static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name); ImGuiID id = settings->ID; *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry settings->ID = id; settings->WantApply = true; return (void*)settings; } static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) { ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; int x, y; int i; if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); } else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); } else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } } // Apply to existing windows (if any) static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { ImGuiContext& g = *ctx; for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (settings->WantApply) { if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID)) ApplyWindowSettings(window, settings); settings->WantApply = false; } } static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { // Gather data from windows that were active during this session // (if a window wasn't opened in this session we preserve its settings) ImGuiContext& g = *ctx; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Flags & ImGuiWindowFlags_NoSavedSettings) continue; ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID); if (!settings) { settings = ImGui::CreateNewWindowSettings(window->Name); window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings); } IM_ASSERT(settings->ID == window->ID); settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y); settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y); settings->Collapsed = window->Collapsed; } // Write to text buffer buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) { const char* settings_name = settings->GetName(); buf->appendf("[%s][%s]\n", handler->TypeName, settings_name); buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y); buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); buf->appendf("Collapsed=%d\n", settings->Collapsed); buf->append("\n"); } } //----------------------------------------------------------------------------- // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- // (this section is filled in the 'docking' branch) //----------------------------------------------------------------------------- // [SECTION] DOCKING //----------------------------------------------------------------------------- // (this section is filled in the 'docking' branch) //----------------------------------------------------------------------------- // [SECTION] PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) #ifdef _MSC_VER #pragma comment(lib, "user32") #pragma comment(lib, "kernel32") #endif // Win32 clipboard implementation // We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown() static const char* GetClipboardTextFn_DefaultImpl(void*) { ImGuiContext& g = *GImGui; g.ClipboardHandlerData.clear(); if (!::OpenClipboard(NULL)) return NULL; HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) { ::CloseClipboard(); return NULL; } if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle)) { int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL); g.ClipboardHandlerData.resize(buf_len); ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL); } ::GlobalUnlock(wbuf_handle); ::CloseClipboard(); return g.ClipboardHandlerData.Data; } static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!::OpenClipboard(NULL)) return; const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0); HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR)); if (wbuf_handle == NULL) { ::CloseClipboard(); return; } WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle); ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length); ::GlobalUnlock(wbuf_handle); ::EmptyClipboard(); if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL) ::GlobalFree(wbuf_handle); ::CloseClipboard(); } #elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS) #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file static PasteboardRef main_clipboard = 0; // OSX clipboard implementation // If you enable this you will need to add '-framework ApplicationServices' to your linker command-line! static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!main_clipboard) PasteboardCreate(kPasteboardClipboard, &main_clipboard); PasteboardClear(main_clipboard); CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text)); if (cf_data) { PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0); CFRelease(cf_data); } } static const char* GetClipboardTextFn_DefaultImpl(void*) { if (!main_clipboard) PasteboardCreate(kPasteboardClipboard, &main_clipboard); PasteboardSynchronize(main_clipboard); ItemCount item_count = 0; PasteboardGetItemCount(main_clipboard, &item_count); for (ItemCount i = 0; i < item_count; i++) { PasteboardItemID item_id = 0; PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id); CFArrayRef flavor_type_array = 0; PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array); for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++) { CFDataRef cf_data; if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr) { ImGuiContext& g = *GImGui; g.ClipboardHandlerData.clear(); int length = (int)CFDataGetLength(cf_data); g.ClipboardHandlerData.resize(length + 1); CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data); g.ClipboardHandlerData[length] = 0; CFRelease(cf_data); return g.ClipboardHandlerData.Data; } } } return NULL; } #else // Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers. static const char* GetClipboardTextFn_DefaultImpl(void*) { ImGuiContext& g = *GImGui; return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin(); } static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { ImGuiContext& g = *GImGui; g.ClipboardHandlerData.clear(); const char* text_end = text + strlen(text); g.ClipboardHandlerData.resize((int)(text_end - text) + 1); memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text)); g.ClipboardHandlerData[(int)(text_end - text)] = 0; } #endif // Win32 API IME support (for Asian languages, etc.) #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) #include <imm.h> #ifdef _MSC_VER #pragma comment(lib, "imm32") #endif static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { // Notify OS Input Method Editor of text input position ImGuiIO& io = ImGui::GetIO(); if (HWND hwnd = (HWND)io.ImeWindowHandle) if (HIMC himc = ::ImmGetContext(hwnd)) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = x; cf.ptCurrentPos.y = y; cf.dwStyle = CFS_FORCE_POSITION; ::ImmSetCompositionWindow(himc, &cf); ::ImmReleaseContext(hwnd, himc); } } #else static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} #endif //----------------------------------------------------------------------------- // [SECTION] METRICS/DEBUGGER WINDOW //----------------------------------------------------------------------------- // - MetricsHelpMarker() [Internal] // - ShowMetricsWindow() // - DebugNodeColumns() [Internal] // - DebugNodeDrawList() [Internal] // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal] // - DebugNodeStorage() [Internal] // - DebugNodeTabBar() [Internal] // - DebugNodeWindow() [Internal] // - DebugNodeWindowSettings() [Internal] // - DebugNodeWindowsList() [Internal] //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_METRICS_WINDOW // Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds. static void MetricsHelpMarker(const char* desc) { ImGui::TextDisabled("(?)"); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); ImGui::TextUnformatted(desc); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } void ImGui::ShowMetricsWindow(bool* p_open) { if (!Begin("Dear ImGui Metrics/Debugger", p_open)) { End(); return; } ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; // Basic info Text("Dear ImGui %s", ImGui::GetVersion()); Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows); Text("%d active allocations", io.MetricsActiveAllocations); //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; } Separator(); // Debugging enums enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentRegionRect" }; enum { TRT_OuterRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentRowsFrozen, TRT_ColumnsContentRowsUnfrozen, TRT_Count }; // Tables Rect Type const char* trt_rects_names[TRT_Count] = { "OuterRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentRowsFrozen", "ColumnsContentRowsUnfrozen" }; if (cfg->ShowWindowsRectsType < 0) cfg->ShowWindowsRectsType = WRT_WorkRect; if (cfg->ShowTablesRectsType < 0) cfg->ShowTablesRectsType = TRT_WorkRect; struct Funcs { static ImRect GetWindowRect(ImGuiWindow* window, int rect_type) { if (rect_type == WRT_OuterRect) { return window->Rect(); } else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; } 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_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; } IM_ASSERT(0); return ImRect(); } }; // Tools if (TreeNode("Tools")) { // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted. if (Button("Item Picker..")) DebugStartItemPicker(); SameLine(); MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash."); Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder); Checkbox("Show windows rectangles", &cfg->ShowWindowsRects); SameLine(); SetNextItemWidth(GetFontSize() * 12); cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count); if (cfg->ShowWindowsRects && g.NavWindow != NULL) { BulletText("'%s':", g.NavWindow->Name); Indent(); for (int rect_n = 0; rect_n < WRT_Count; rect_n++) { ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n); Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]); } Unindent(); } Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh); Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes); TreePop(); } // Contents DebugNodeWindowsList(&g.Windows, "Windows"); //DebugNodeWindowList(&g.WindowsFocusOrder, "WindowsFocusOrder"); if (TreeNode("DrawLists", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) { for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++) DebugNodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList"); TreePop(); } // Details for Popups if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) { for (int i = 0; i < g.OpenPopupStack.Size; i++) { ImGuiWindow* window = g.OpenPopupStack[i].Window; 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" : ""); } TreePop(); } // Details for TabBars if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize())) { for (int n = 0; n < g.TabBars.GetSize(); n++) DebugNodeTabBar(g.TabBars.GetByIndex(n), "TabBar"); TreePop(); } // Details for Tables IM_UNUSED(trt_rects_names); #ifdef IMGUI_HAS_TABLE if (TreeNode("Tables", "Tables (%d)", g.Tables.GetSize())) { for (int n = 0; n < g.Tables.GetSize(); n++) DebugNodeTable(g.Tables.GetByIndex(n)); TreePop(); } #endif // #ifdef IMGUI_HAS_TABLE // Details for Docking #ifdef IMGUI_HAS_DOCK if (TreeNode("Docking")) { TreePop(); } #endif // #ifdef IMGUI_HAS_DOCK // Settings if (TreeNode("Settings")) { if (SmallButton("Clear")) ClearIniSettings(); SameLine(); if (SmallButton("Save to memory")) SaveIniSettingsToMemory(); SameLine(); if (SmallButton("Save to disk")) SaveIniSettingsToDisk(g.IO.IniFilename); SameLine(); if (g.IO.IniFilename) Text("\"%s\"", g.IO.IniFilename); else TextUnformatted("<NULL>"); Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer); if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size)) { for (int n = 0; n < g.SettingsHandlers.Size; n++) BulletText("%s", g.SettingsHandlers[n].TypeName); TreePop(); } if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size())) { for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) DebugNodeWindowSettings(settings); TreePop(); } #ifdef IMGUI_HAS_TABLE if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size())) { for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings)) DebugNodeTableSettings(settings); TreePop(); } #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK #endif // #ifdef IMGUI_HAS_DOCK if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size())) { InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly); TreePop(); } TreePop(); } // Misc Details if (TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); Text("WINDOWING"); Indent(); Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); Unindent(); Text("ITEMS"); Indent(); Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); Unindent(); Text("NAV,FOCUS"); Indent(); Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); Text("NavInputSource: %s", input_source_names[g.NavInputSource]); Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId); Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); Unindent(); TreePop(); } // Overlay: Display windows Rectangles and Begin Order if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder) { for (int n = 0; n < g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; if (!window->WasActive) continue; ImDrawList* draw_list = GetForegroundDrawList(window); if (cfg->ShowWindowsRects) { ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow)) { char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); float font_size = 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); } } } #ifdef IMGUI_HAS_TABLE // Overlay: Display Tables Rectangles if (show_tables_rects) { for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++) { ImGuiTable* table = g.Tables.GetByIndex(table_n); } } #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK // Overlay: Display Docking info if (show_docking_nodes && g.IO.KeyCtrl) { } #endif // #ifdef IMGUI_HAS_DOCK End(); } // [DEBUG] Display contents of Columns void ImGui::DebugNodeColumns(ImGuiOldColumns* columns) { if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) return; BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); for (int column_n = 0; column_n < columns->Columns.Size; column_n++) BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm)); TreePop(); } // [DEBUG] Display contents of ImDrawList void ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label) { ImGuiContext& g = *GImGui; ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig; int cmd_count = draw_list->CmdBuffer.Size; if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL) cmd_count--; bool node_open = 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, cmd_count); if (draw_list == GetWindowDrawList()) { SameLine(); TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) if (node_open) TreePop(); return; } ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list if (window && IsItemHovered()) fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!node_open) return; if (window && !window->WasActive) TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!"); for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++) { if (pcmd->UserCallback) { BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); continue; } char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%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 = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list) DebugNodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes); if (!pcmd_node_open) continue; // Calculate approximate coverage area (touched pixel count) // This will be in pixels squared as long there's no post-scaling happening to the renderer output. const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset; float total_area = 0.0f; for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; ) { ImVec2 triangle[3]; for (int n = 0; n < 3; n++, idx_n++) triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos; total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]); } // Display vertex information summary. Hover to get all triangles drawn in wire-frame ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area); Selectable(buf); if (IsItemHovered() && fg_draw_list) DebugNodeDrawCmdShowMeshAndBoundingBox(window, draw_list, pcmd, true, false); // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. ImGuiListClipper clipper; clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++) { char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangle[3]; for (int n = 0; n < 3; n++, idx_i++) { const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i]; triangle[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) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); } Selectable(buf, false); if (fg_draw_list && IsItemHovered()) { ImDrawListFlags backup_flags = fg_draw_list->Flags; fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); fg_draw_list->Flags = backup_flags; } } TreePop(); } TreePop(); } // [DEBUG] Display mesh/aabb of a ImDrawCmd void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow* window, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb) { IM_ASSERT(show_mesh || show_aabb); ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset; // Draw wire-frame version of all triangles ImRect clip_rect = draw_cmd->ClipRect; ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); ImDrawListFlags backup_flags = fg_draw_list->Flags; fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles. for (unsigned int idx_n = draw_cmd->IdxOffset; idx_n < draw_cmd->IdxOffset + draw_cmd->ElemCount; ) { ImVec2 triangle[3]; for (int n = 0; n < 3; n++, idx_n++) vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos)); if (show_mesh) fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), true, 1.0f); // In yellow: mesh triangles } // Draw bounding boxes if (show_aabb) { fg_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU fg_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles } fg_draw_list->Flags = backup_flags; } // [DEBUG] Display contents of ImGuiStorage void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label) { if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes())) return; for (int n = 0; n < storage->Data.Size; n++) { const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n]; BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer. } TreePop(); } // [DEBUG] Display contents of ImGuiTabBar void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label) { // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. char buf[256]; char* p = buf; const char* buf_end = buf + IM_ARRAYSIZE(buf); const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2); p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*"); IM_UNUSED(p); if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } bool open = TreeNode(tab_bar, "%s", buf); if (!is_active) { PopStyleColor(); } if (is_active && IsItemHovered()) { ImDrawList* draw_list = GetForegroundDrawList(); draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255)); draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255)); } if (open) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; PushID(tab); if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2); if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine(); Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "", tab->Offset, tab->Width, tab->ContentWidth); PopID(); } TreePop(); } } void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label) { if (window == NULL) { BulletText("%s: NULL", label); return; } ImGuiContext& g = *GImGui; const bool is_active = window->WasActive; ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None; if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*"); if (!is_active) { PopStyleColor(); } if (IsItemHovered() && is_active) GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!open) return; if (window->MemoryCompacted) TextDisabled("Note: some memory buffers have been compacted/freed."); ImGuiWindowFlags flags = window->Flags; DebugNodeDrawList(window, window->DrawList, "DrawList"); 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); BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : ""); BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); if (!window->NavRectRel[0].IsInverted()) BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y); else BulletText("NavRectRel[0]: <None>"); if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); } if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); } if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); } if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) { for (int n = 0; n < window->ColumnsStorage.Size; n++) DebugNodeColumns(&window->ColumnsStorage[n]); TreePop(); } DebugNodeStorage(&window->StateStorage, "Storage"); TreePop(); } void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings) { Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d", settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed); } void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label) { if (!TreeNode(label, "%s (%d)", label, windows->Size)) return; Text("(In front-to-back order:)"); for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back { PushID((*windows)[i]); DebugNodeWindow((*windows)[i], "Window"); PopID(); } TreePop(); } #else void ImGui::ShowMetricsWindow(bool*) {} void ImGui::DebugNodeColumns(ImGuiOldColumns*) {} void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {} void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImGuiWindow*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {} void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {} void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {} void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {} void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {} #endif //----------------------------------------------------------------------------- // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. // Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL #include "imgui_user.inl" #endif //----------------------------------------------------------------------------- #endif // #ifndef IMGUI_DISABLE
[ "yangfengzzz@hotmail.com" ]
yangfengzzz@hotmail.com
ffde8ff7e1547f800c52163dbdb9cf5e4d1bcf1e
38652d98c1d0f4cf3154874edf493a68bb0885f4
/homework01/x_pow_y.cpp
810789480ae2ed62508a63b17e51552017f74796
[]
no_license
littlebowlnju/cpp-homework
cc53b7644a3aa9b0f7d9f16a0e0aa383f5ca6fc4
daf4ae71ddfa0231fd1edd2193ee792da91efe4f
refs/heads/master
2021-05-20T02:33:39.924635
2020-04-01T11:32:31
2020-04-01T11:32:31
252,149,421
0
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include <iostream> #include <climits> using namespace std; int x_pow_y(int x, int y) { long long res=1; int max = INT_MAX; int min = INT_MIN; for (int i = 0; i < y; i++) { if (res*x > max || res * x < min) { return -1; }res *= x; }return (int)res; } int main() { char c; int x, y; cin >> c >> c >> x >> c >> c >> c >> y; cout << x_pow_y(x, y); }
[ "noreply@github.com" ]
noreply@github.com
87be5bfd1ee8ddb6f0b9dd1217533bdb67b06d82
dd9841d01e14acd6b76a99aad6d4646e62cf7d5e
/src/widget/slided_panel.cpp
e3de3ef45de7c82f3c38d71aa227622e9e2270f4
[]
no_license
3dsman/snice_ui
5b489e7b6cf5a3e73531bd827e0c44db8a120f55
a684d0a3ff53b9788cc379409fae3402a864f352
refs/heads/master
2021-01-01T15:45:05.362719
2015-10-07T12:54:30
2015-10-07T12:54:30
25,481,412
1
3
null
null
null
null
UTF-8
C++
false
false
14,653
cpp
// crafter interface library // Funny Farm // copyright © 2002 Wybren van Keulen // www.funnyfarm.tv // thanks to nehe stencil buffer tutorial http://nehe.gamedev.net/ // File modified by Tricoire Sebastien // Date of creation : 2004 10 14 /// // File modified by // Date of modification : /* ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. The Blender * Foundation also sells licenses for use in proprietary software under * the Blender License. See http://www.blender.org/BL/ for information * about this. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * The Original Code is Copyright (C) 2002-2003 by Funny Farm. * www.funnyfarm.tv * * ***** END GPL LICENSE BLOCK ***** */ #include "../snice_UI.h" #include "widget/slided_panel.h" W_slidedPanel::W_slidedPanel(int x, int y, int w, int h, int sx, int sy, float red, float green, float blue) :UI_widget(x, y, w, h, red, green, blue) { width = w; height = h; SetPanelSurface(sx,sy); } W_slidedPanel::~W_slidedPanel() { if (pHorizontalSlider) delete pHorizontalSlider; if (pVerticalSlider) delete pVerticalSlider; } void W_slidedPanel::StatChangeSliders(UI_base * asker, W_slider* caller,float value, bool realtime) { (dynamic_cast<W_slidedPanel*> (asker))->ChangeSliders(caller, value, realtime); } void W_slidedPanel::ChangeSliders( W_slider* caller,float value, bool realtime) { if (caller == pHorizontalSlider) xOffset = value; if (caller == pVerticalSlider) { yOffset = (surfacey-windSizeY)-value; //std::cout<<surfacey-windSizeY<<" "<<value<<std::endl; } } void W_slidedPanel::Draw() { glTranslated(posx, posy, 0); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); // Fill // glColor4f(1.0f, 1.0f, 1.0f,0.6f); // glColor4f(0.64f, 0.59f, 0.53f,1.0f); glColor4f(r, g, b, 1.0f); //background color /*glBegin(GL_POLYGON); glVertex2d(6, -1); glVertex2d(width-6, -1); glVertex2d(width-2, -2); glVertex2d(width-1, -4); glVertex2d(width-1, -6); glVertex2d(width-1, -winHeight+6); glVertex2d(width-2, -winHeight+2); glVertex2d(width-4, -winHeight+1); glVertex2d(width-6, -winHeight+1); glVertex2d(6, -winHeight+1); glVertex2d(2, -winHeight+2); glVertex2d(1, -winHeight+4); glVertex2d(1, -winHeight+5); glVertex2d(1, -7); glVertex2d(2, -2); glVertex2d(4, -1); glVertex2d(6, 0); glEnd();*/ glClear(GL_STENCIL_BUFFER_BIT); // clear the stencil buffer glEnable(GL_STENCIL_TEST); // Enable stencil buffer for "marking" the content of the list selector glStencilFunc(GL_ALWAYS, 1, 1); // Always passes, 1 bit plane, 1 as mask glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); // We set the stencil buffer to 1 where we draw any polygon // Keep if test fails, keep if test passes but buffer test fails replace if test passes glBegin(GL_QUADS); glVertex2d(1,-1); glVertex2d(windSizeX-1, -1); // Draw the backgound to color and stencil buffers. glVertex2d(windSizeX-1, -windSizeY+1); // We Only Want To Mark It In The Stencil Buffer glVertex2d(1, -windSizeY+1); glEnd(); glStencilFunc(GL_EQUAL, 1, 1); // We draw only where the stencil is 1 // (I.E. where the background was drawn) glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // Don't change the stencil buffer glPushMatrix(); // Push the matrix for the slider translation glTranslated(-xOffset, yOffset, 0); // Slider translation //********************************** draw the content of the window *********************** for(std::list<UI_base*>::iterator iter = childList.begin(); iter != childList.end(); iter ++) { (*iter)->Draw(); } /* if (childList.ToFirst()) do { ((UI_base*)childList.GetCurrentObjectPointer())->Draw(); }while(childList.ToNext());*/ //PanelDraw(); //******************************************************************************************* glPopMatrix(); // Get the matrix before translation glDisable(GL_STENCIL_TEST); // We don't need the stencil buffer any more (Disable) // draw the border glColor4f(1.0f,1.0f,1.0f,0.7f); glEnable(GL_TEXTURE_2D); textures.slider.BindTex(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glBegin(GL_QUADS); glTexCoord2f(0.0f,1.0f); glVertex2d(0, 0); glTexCoord2f(0.25f,1.0f); glVertex2d(8, 0); glTexCoord2f(0.25,0.75f); glVertex2d(8, -8); glTexCoord2f(0.0f,0.75f); glVertex2d(0, -8); glTexCoord2f(0.49f,1.0f); glVertex2d(8, 0); glTexCoord2f(0.51f,1.0f); glVertex2d(windSizeX-8, 0); glTexCoord2f(0.51f,0.75f); glVertex2d(windSizeX-8, -8); glTexCoord2f(0.49f,0.75f); glVertex2d(8, -8); glTexCoord2f(0.75f,1.0f); glVertex2d(windSizeX-8, 0); glTexCoord2f(1.00f,1.0f); glVertex2d(windSizeX, 0); glTexCoord2f(1.00f,0.75f); glVertex2d(windSizeX, -8); glTexCoord2f(0.75f,0.75f); glVertex2d(windSizeX-8, -8); glTexCoord2f(0.75f,0.75f); glVertex2d(windSizeX-8, -8); glTexCoord2f(1.00f,0.75f); glVertex2d(windSizeX, -8); glTexCoord2f(1.00f,0.25f); glVertex2d(windSizeX, -windSizeY+8); glTexCoord2f(0.75f,0.25f); glVertex2d(windSizeX-8, -windSizeY+8); glTexCoord2f(0.75f,0.25f); glVertex2d(windSizeX-8, -windSizeY+8); glTexCoord2f(1.00f,0.25f); glVertex2d(windSizeX, -windSizeY+8); glTexCoord2f(1.00f,0.00f); glVertex2d(windSizeX, -windSizeY); glTexCoord2f(0.75f,0.00f); glVertex2d(windSizeX-8, -windSizeY); glTexCoord2f(0.25f,0.25f); glVertex2d(8, -windSizeY+8); glTexCoord2f(0.75f,0.25f); glVertex2d(windSizeX-8, -windSizeY+8); glTexCoord2f(0.75,0.00f); glVertex2d(windSizeX-8, -windSizeY); glTexCoord2f(0.25f,0.00f); glVertex2d(8, -windSizeY); glTexCoord2f(0.0f,0.25f); glVertex2d(0, -windSizeY+8); glTexCoord2f(0.25f,0.25f); glVertex2d(8, -windSizeY+8); glTexCoord2f(0.25f,0.00f); glVertex2d(8, -windSizeY); glTexCoord2f(0.0f,0.00f); glVertex2d(0, -windSizeY); glTexCoord2f(0.00f,0.75f); glVertex2d(0, -8); glTexCoord2f(0.25f,0.75f); glVertex2d(8, -8); glTexCoord2f(0.25f,0.25f); glVertex2d(8, -windSizeY+8); glTexCoord2f(0.00f,0.25f); glVertex2d(0, -windSizeY+8); glEnd(); /*glBindTexture(GL_TEXTURE_2D, textures[10].texID); glColor4f(1.0f,1.0f,1.0f,0.6f); glBegin(GL_QUADS); glTexCoord2f(0.0f,1.0f); glVertex2d(0, 0); glTexCoord2f(1.0f,1.0f); glVertex2d(width, 0); glTexCoord2f(1.0f,0.0f); glVertex2d(width,-winHeight); glTexCoord2f(0.0f,0.0f); glVertex2d(0, -winHeight); glEnd();*/ glDisable(GL_TEXTURE_2D); if (pHorizontalSlider) pHorizontalSlider->Draw(); if (pVerticalSlider) pVerticalSlider->Draw(); glTranslated(-posx,-posy,0); } void W_slidedPanel::SetColor(float red, float green, float blue) { r = red; g = green; b = blue; } void W_slidedPanel::GetColor(float * red, float * green, float * blue) { *red = r; *green = g; *blue = b; } void W_slidedPanel::SetPanelSurface(int x, int y) { windSizeX = width; windSizeY = height; xOffset = 0; yOffset = 0; if (width<x) windSizeY = height - 20; if (height<y) windSizeX = width - 20; surfacex = max(x,windSizeX); surfacey = max(y,windSizeY); if (width<x) { if (!pHorizontalSlider) { pHorizontalSlider = new W_slider(0,-windSizeY,windSizeX,20,"", 0.0f, 0.0f, (float)surfacex, 0, (float)windSizeX); pHorizontalSlider->OnSetValue(this, W_slidedPanel::StatChangeSliders); }else { pHorizontalSlider->SetTo((float)surfacex); pHorizontalSlider->SetValue((float)0,false); pHorizontalSlider->SetBarSize((float)windSizeX); pHorizontalSlider->SetWidth(windSizeX); pHorizontalSlider->SetPosY(-windSizeY); } } else if (pHorizontalSlider) { delete pHorizontalSlider; pHorizontalSlider = nullptr; }; if (height<y) { if (!pVerticalSlider) { pVerticalSlider = new W_slider(windSizeX,0,20,windSizeY,"", (float)surfacey-(float)windSizeY, 0, (float)surfacey, 0, (float)windSizeY); pVerticalSlider->OnSetValue(this, W_slidedPanel::StatChangeSliders); }else { pVerticalSlider->SetTo((float)surfacey); pVerticalSlider->SetValue((float)surfacey-(float)windSizeY,false); pVerticalSlider->SetBarSize((float)windSizeY); pVerticalSlider->SetHeight(windSizeY); pVerticalSlider->SetPosX(windSizeX); } } else if (pVerticalSlider) { delete pVerticalSlider; pVerticalSlider = nullptr; } } bool W_slidedPanel::HitPanel(int x, int y) { if (x<posx || x>posx+windSizeX || y>posy || y<posy-windSizeY) return 0; else return 1; } UI_base* W_slidedPanel::OnLButtonDown(int x, int y) { if (pInterceptChild) { if ((pInterceptChild==pVerticalSlider)||(pInterceptChild==pHorizontalSlider)) { pInterceptChild = (pInterceptChild)->OnLButtonDown(x - posx , y - posy); Autokill(pInterceptChild); }else if (pInterceptChild!=this) { pInterceptChild = (pInterceptChild)->OnLButtonDown(x - posx + xOffset, y - posy - yOffset); Autokill(pInterceptChild); } if (pInterceptChild) return this; else return 0; }; if (HitPanel(x,y)) { std::list<UI_base*>::iterator iter = childList.begin(); while (iter != childList.end()) { pInterceptChild = (*iter)->OnLButtonDown(x - posx + xOffset, y - posy - yOffset); Autokill(*iter++); if (pInterceptChild) {return this;}; } }else{ if (pHorizontalSlider) { pInterceptChild = pHorizontalSlider->OnLButtonDown(x-posx,y-posy); if (pInterceptChild) {return this;}; } if (pVerticalSlider) { pInterceptChild = pVerticalSlider->OnLButtonDown(x-posx,y-posy); if (pInterceptChild) {return this;}; } } return 0; } UI_base* W_slidedPanel::OnLButtonUp(int x, int y) { if (pInterceptChild) { if ((pInterceptChild==pVerticalSlider)||(pInterceptChild==pHorizontalSlider)) { pInterceptChild = (pInterceptChild)->OnLButtonUp(x - posx , y - posy); Autokill(pInterceptChild); }else if (pInterceptChild!=this) { pInterceptChild = (pInterceptChild)->OnLButtonUp(x - posx + xOffset, y - posy - yOffset); Autokill(pInterceptChild); } if (pInterceptChild) return this; else return 0; }; if (HitPanel(x,y)) { std::list<UI_base*>::iterator iter = childList.begin(); while (iter != childList.end()) { pInterceptChild = (*iter)->OnLButtonUp(x - posx + xOffset, y - posy - yOffset); Autokill(*iter++); if (pInterceptChild) {return this;}; } }else{ if (pHorizontalSlider) { pInterceptChild = pHorizontalSlider->OnLButtonUp(x-posx,y-posy); if (pInterceptChild) {return this;}; } if (pVerticalSlider) { pInterceptChild = pVerticalSlider->OnLButtonUp(x-posx,y-posy); if (pInterceptChild) {return this;}; } } return 0; //if (HitPanel(x,y)) // PanelOnLButtonUp( x - posx + (int)(pHorizontalSlider->GetValue()), y - posy); //pHorizontalSlider->OnLButtonUp(x-posx,y-posy); //pVerticalSlider->OnLButtonUp(x-posx,y-posy); } UI_base* W_slidedPanel::OnMouseMove(int x, int y, int prevx, int prevy) { //int xOffset = (int)(pHorizontalSlider->GetValue()); //int yOffset = (int)(pVerticalSlider->GetValue()); if (pInterceptChild) { if ((pInterceptChild==pVerticalSlider)||(pInterceptChild==pHorizontalSlider)) { pInterceptChild = (pInterceptChild)->OnMouseMove(x-posx,y-posy, prevx-posx, prevy-posy); Autokill(pInterceptChild); }else if (pInterceptChild!=this) { pInterceptChild = (pInterceptChild)->OnMouseMove( x - posx + xOffset, y - posy - yOffset, prevx - posx + xOffset, prevy - posy - yOffset); Autokill(pInterceptChild); } if (pInterceptChild) return this; else return 0; }; if (HitPanel(x,y)) { std::list<UI_base*>::iterator iter = childList.begin(); while (iter != childList.end()) { pInterceptChild = (*iter)->OnMouseMove( x - posx + xOffset, y - posy - yOffset, prevx - posx + xOffset, prevy - posy - yOffset); Autokill(*iter++); if (pInterceptChild) {return this;}; } }else{ if (pHorizontalSlider) { pInterceptChild = pHorizontalSlider->OnMouseMove(x-posx,y-posy, prevx-posx, prevy-posy); if (pInterceptChild) {return this;}; } if (pVerticalSlider) { pInterceptChild = pVerticalSlider->OnMouseMove(x-posx,y-posy, prevx-posx, prevy-posy); if (pInterceptChild) {return this;}; } } return 0; //if (HitPanel(x,y)) // PanelOnMouseMove( x - posx + (int)(pHorizontalSlider->GetValue()), y - posy, prevx - posx + (int)(pHorizontalSlider->GetValue()), prevy - posy); //pHorizontalSlider->OnMouseMove(x-posx,y-posy, prevx-posx, prevy-posy); //pVerticalSlider->OnMouseMove(x-posx,y-posy, prevx-posx, prevy-posy); } /* UI_base* W_slidedPanel::OnKeyPressed(int key) UI_base::OnKeyPressed(int key) { // PanelOnKeyPressed(key); }*/ /* void W_slidedPanel::panelOnLButtonDown(int x, int y, int px, int py){}; void W_slidedPanel::panelOnLButtonUp(int x, int y){}; void W_slidedPanel::panelOnMouseMove(int x, int y, int prevx, int prevy){}; void W_slidedPanel::panelOnKeyPressed(int key){}; void W_slidedPanel::panelDraw(){}; */ /* void W_slidedPanel::LoadXML(TiXmlElement* element) { double red, green, blue; element->Attribute("Red",&red); element->Attribute("Green",&green); element->Attribute("Blue",&blue); SetColor((float)red, (float)green, (float)blue); }*/
[ "3dsman@free.fr" ]
3dsman@free.fr
784e8ac3ff7fc2d1b1cc725d15c70d77417df464
5d711c13d3ed0a9c078113652d7cd7963099fa5d
/SchedulingSimulator/FIFO.cpp
83a205a439b4ce32a596cc9276741e5c8820567c
[]
no_license
BenHSmith13/sudoOS
40146fffc19c91c04b972567179879a464402f06
2f1b0ef1b1c68377c5ff604c3aeeaf3250d0ce66
refs/heads/master
2020-05-17T22:22:47.320890
2015-04-07T22:08:58
2015-04-07T22:08:58
31,424,910
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
#include "fifo.h" void FIFO::run() { createTasks(); for (auto && t : getTaskVect()) { for (auto && e : t.getEvents()) { fifoQ.push(e); } } for (auto && i : CPUtimes) //initializes CPU's with context switch { i += getContextSwitch(); } //Add Event to CPU addEventToCPU(); //Add Event Time to CPU time //Find min CPU Time //Repeat } void FIFO::addEventToCPU() { if (isCPUfree()) { auto temp = fifoQ.front(); if (temp.getRunTime() > 999) { } std::min_element(CPUtimes.begin(), CPUtimes.end()) += temp.getRunTime(); fifoQ.pop(); } }
[ "benhsmith13@gmail.com" ]
benhsmith13@gmail.com
f9b575c58da960faf6c5cb53aab40fdfb9e64c60
fc8458f397f662d5a49bb2d94e277b7242ffad4e
/src/Processor/Instruction.cpp
11b2e83e3bae512ff332a310f2cc4a31d6730333
[ "BSD-2-Clause" ]
permissive
QED-it/SCALE-MAMBA
c19e5626e385eb3de1b9154f951669693d8bc237
316c922f38a04fd3daaf70557a9b8e2294240ace
refs/heads/master
2022-06-18T18:57:56.176840
2020-05-06T10:09:12
2020-05-06T10:09:12
268,619,198
0
0
null
2020-06-01T19:57:45
2020-06-01T19:57:44
null
UTF-8
C++
false
false
69,210
cpp
/* Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom. Copyright (c) 2020, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium. All rights reserved */ #include "Processor/Instruction.h" #include "Exceptions/Exceptions.h" #include "Local/Local_Functions.h" #include "Offline/offline_data.h" #include "Processor/Processor.h" #include "Tools/Crypto.h" #include "Tools/parse.h" extern Local_Functions Global_LF; #include <algorithm> #include <limits> #include <map> #include <mutex> #include <sstream> #include <stdlib.h> #include <unistd.h> #include "GC/Garbled.h" #include "OT/OT_Thread_Data.h" extern OT_Thread_Data OTD; extern Base_Circuits Global_Circuit_Store; extern vector<sacrificed_data> SacrificeD; using namespace std; // Convert modp to signed bigint of a given bit length void to_signed_bigint(bigint &bi, const gfp &x, int len) { to_bigint(bi, x); int neg; // get sign and abs(x) bigint p_half= (gfp::pr() - 1) / 2; if (mpz_cmp(bi.get_mpz_t(), p_half.get_mpz_t()) < 0) neg= 0; else { bi= gfp::pr() - bi; neg= 1; } // reduce to range -2^(len-1), ..., 2^(len-1) bigint one= 1; bi&= (one << len) - 1; if (neg) bi= -bi; } void Instruction::parse(istream &s) { n= 0; start.resize(0); r[0]= 0; r[1]= 0; r[2]= 0; r[3]= 0; int pos= s.tellg(); opcode= get_int(s); size= opcode >> 9; opcode&= 0x1FF; if (size == 0) size= 1; parse_operands(s, pos); } void BaseInstruction::parse_operands(istream &s, int pos) { int num_var_args= 0; // cout << "Parsing instruction " << hex << showbase << opcode << " at " << // dec << pos << endl; switch (opcode) { // instructions with 3 register (or 3 integer) operands case ADDC: case ADDS: case ADDM: case SUBC: case SUBS: case SUBML: case SUBMR: case MULC: case MULM: case DIVC: case MODC: case TRIPLE: case ANDC: case XORC: case ORC: case SHLC: case SHRC: case LTINT: case GTINT: case EQINT: case ADDINT: case SUBINT: case MULINT: case DIVINT: case RUN_TAPE: case ADDSINT: case ADDSINTC: case SUBSINT: case SUBSINTC: case SUBCINTS: case MULSINT: case MULSINTC: case DIVSINT: case SAND: case XORSB: case ANDSB: case ORSB: case ANDSINT: case ANDSINTC: case ORSINT: case ORSINTC: case XORSINT: case XORSINTC: r[0]= get_int(s); r[1]= get_int(s); r[2]= get_int(s); break; // instructions with 2 register operands case LDMCI: case LDMSI: case STMCI: case STMSI: case MOVC: case MOVS: case MOVINT: case LDMINTI: case STMINTI: case LEGENDREC: case SQUARE: case DABIT: case CONVINT: case LTZINT: case EQZINT: case RAND: case DIGESTC: case NEG: case NEGB: case CONVSINTSREG: case CONVREGSREG: case CONVSREGSINT: case CONVSUREGSINT: case OPENSINT: case OPENSBIT: case LDMSINTI: case STMSINTI: case MOVSINT: case INVSINT: case EQZSINT: case LTZSINT: case PEEKINT: case PEEKSINT: case PEEKC: case PEEKS: case PEEKSBIT: case POKEINT: case POKESINT: case POKEC: case POKES: case POKESBIT: r[0]= get_int(s); r[1]= get_int(s); break; // instructions with 1 register operand case BIT: case PRINT_REG: case LDTN: case LDARG: case STARG: case PUSHINT: case PUSHSINT: case PUSHC: case PUSHS: case PUSHSBIT: case POPINT: case POPSINT: case POPC: case POPS: case POPSBIT: case GETSPINT: case GETSPSINT: case GETSPC: case GETSPS: case GETSPSBIT: case PRINT_CHAR_REGINT: case PRINT_CHAR4_REGINT: case PRINT_INT: case PRINT_IEEE_FLOAT: r[0]= get_int(s); break; // instructions with 2 registers + 1 integer operand case ADDCI: case ADDSI: case SUBCI: case SUBSI: case SUBCFI: case SUBSFI: case MULCI: case MULSI: case DIVCI: case MODCI: case ANDCI: case XORCI: case ORCI: case SHLCI: case SHRCI: case SHLSINT: case SHRSINT: case NOTC: case CONVMODP: case BITSINT: r[0]= get_int(s); r[1]= get_int(s); n= get_int(s); break; // instructions with 2 registers + 1 integer operand case SINTBIT: r[0]= get_int(s); r[1]= get_int(s); r[2]= get_int(s); n= get_int(s); break; // instructions with 1 register + 1 integer operand case LDI: case LDSI: case LDMC: case LDMS: case STMC: case STMS: case LDMINT: case STMINT: case JMPNZ: case JMPEQZ: case LDINT: case INPUT_CLEAR: case OUTPUT_CLEAR: case INPUT_INT: case OPEN_CHANNEL: case OUTPUT_INT: case LDMSINT: case STMSINT: case LDSINT: case LDSBIT: r[0]= get_int(s); n= get_int(s); break; // instructions with 1 reg + 1 player + 1 integer operand case PRIVATE_INPUT: case PRIVATE_OUTPUT: r[0]= get_int(s); p= get_int(s); m= get_int(s); break; // instructions with 1 reg + 2 integer operand case PRINT_FIX: r[0]= get_int(s); n= get_int(s); m= get_int(s); break; // instructions with 1 integer operand case PRINT_CHAR4: case PRINT_CHAR: case JMP: case CALL: case START_CLOCK: case STOP_CLOCK: case CLOSE_CHANNEL: case PRINT_MEM: case JOIN_TAPE: case GC: case LF: n= get_int(s); break; // instructions with no operand case CLEAR_MEMORY: case CLEAR_REGISTERS: case RESTART: case CRASH: case RETURN: break; // instructions with 4 register operands case PRINT_FLOAT: case MUL2SINT: get_vector(4, start, s); break; // open instructions instructions with variable length args case STARTOPEN: case STOPOPEN: num_var_args= get_int(s); get_vector(num_var_args, start, s); break; // As above, but with a trailing int argument case OUTPUT_SHARES: case INPUT_SHARES: // subtract player/channel number from the number of arguments num_var_args= get_int(s) - 1; p= get_int(s); get_vector(num_var_args, start, s); break; case REQBL: n= get_int(s); if (n > 0 && gfp::pr() < bigint(1) << (n - 1)) { cout << "Tape requires prime of bit length " << n << endl; throw invalid_params(); } break; default: ostringstream os; os << "Invalid instruction " << hex << showbase << opcode << " at " << dec << pos; throw Invalid_Instruction(os.str()); } } RegType BaseInstruction::get_reg_type() const { switch (opcode) { // List here commands which write to a specific type of register or a direct memory access case LDMINT: case LDMINTI: case MOVINT: case POPINT: case PEEKSINT: case PUSHINT: case PUSHSINT: case POKEINT: case POKESINT: case GETSPINT: case GETSPSINT: case GETSPS: case GETSPC: case GETSPSBIT: case LDTN: case LDARG: case INPUT_INT: case RAND: case LDINT: case CONVMODP: case ADDINT: case SUBINT: case MULINT: case DIVINT: case LTZINT: case LTINT: case GTINT: case EQINT: case EQZINT: case STMINT: case STMSINT: case STMSINTI: case LDMSINT: case LDMSINTI: case MOVSINT: case LDSINT: case ADDSINT: case ADDSINTC: case SUBSINT: case SUBSINTC: case SUBCINTS: case MULSINT: case MULSINTC: case DIVSINT: case SHLSINT: case SHRSINT: case NEG: case SAND: case SINTBIT: case CONVSINTSREG: case CONVREGSREG: case OPENSINT: case OPENSBIT: case ANDSINT: case ANDSINTC: case ORSINT: case ORSINTC: case XORSINT: case XORSINTC: case INVSINT: case MUL2SINT: case OPEN_CHANNEL: return INT; case XORSB: case ANDSB: case ORSB: case NEGB: case LTZSINT: case EQZSINT: case BITSINT: case POPSBIT: case PUSHSBIT: case PEEKSBIT: case POKESBIT: return SBIT; case STARG: case REQBL: case RUN_TAPE: case JOIN_TAPE: case CRASH: case CLEAR_MEMORY: case CLEAR_REGISTERS: case PRINT_MEM: case PRINT_REG: case PRINT_CHAR: case PRINT_CHAR4: case PRINT_CHAR_REGINT: case PRINT_CHAR4_REGINT: case PRINT_FLOAT: case PRINT_FIX: case PRINT_INT: case PRINT_IEEE_FLOAT: case CLOSE_CHANNEL: case OUTPUT_SHARES: case OUTPUT_INT: case PRIVATE_OUTPUT: case JMP: case JMPNZ: case JMPEQZ: case STARTOPEN: case START_CLOCK: case STOP_CLOCK: case CALL: case RETURN: case GC: case LF: return NONE; case DABIT: return DUAL; default: return MODP; } } /* This does an overestimate as it counts ALL values, even * if they are reading. But the reg_type looks only at * the RETURN value type. So we will overcount some register * usage. If we got the exact register usage it would cost * more logic, and would save little in terms of memeory * * The trick is that if a register is read it must be * written so if we only count the instructions which * write, and then take the max register in that * instruction it will be OK * * So if we had * blah with c0,c1,s0,s1 registers * c5 <- add c0, c1 * s3 <- add c5, s1 * Then the max registers *should* be * c : 5 s: 3 * But we actually count * c : 5 s: 5 * due to the c5 read in the last instruction. But we only * need a max and 3<5 so all is OK * * Dual is a weird one to catch the different write types * of the DABIT instruction * */ int BaseInstruction::get_max_reg(RegType reg_type) const { if ((get_reg_type() == reg_type) || (get_reg_type() == DUAL && (reg_type == SBIT || reg_type == MODP))) { if (start.size()) return *max_element(start.begin(), start.end()) + size; else return *max_element(r, r + 3) + size; } return 0; } ostream &operator<<(ostream &s, const Instruction &instr) { // Is it vectorized? if (instr.size != 1) { s << "V"; } // Then the main opcode switch (instr.opcode) { case LDI: s << "LDI"; break; case LDSI: s << "LDSI"; break; case LDMC: s << "LDMC"; break; case LDMS: s << "LDMS"; break; case STMC: s << "STMC"; break; case STMS: s << "STMS"; break; case LDMCI: s << "LDMCI"; break; case LDMSI: s << "LDMSI"; break; case STMCI: s << "STMCI"; break; case STMSI: s << "STMSI"; break; case MOVC: s << "MOVC"; break; case MOVS: s << "MOVS"; break; case LDMINT: s << "LDMINT"; break; case STMINT: s << "STMINT"; break; case LDMINTI: s << "LDMINTI"; break; case STMINTI: s << "STMINTI"; break; case PUSHINT: s << "PUSHINT"; break; case PUSHSINT: s << "PUSHSINT"; break; case PUSHS: s << "PUSHS"; break; case PUSHC: s << "PUSHC"; break; case PUSHSBIT: s << "PUSHSBIT"; break; case POPINT: s << "POPINT"; break; case POPSINT: s << "POPSINT"; break; case POPS: s << "POPS"; break; case POPC: s << "POPC"; break; case POPSBIT: s << "POPSBIT"; break; case PEEKINT: s << "PEEKINT"; break; case PEEKSINT: s << "PEEKSINT"; break; case PEEKS: s << "PEEKS"; break; case PEEKC: s << "PEEKC"; break; case PEEKSBIT: s << "PEEKSBIT"; break; case POKEINT: s << "POKEINT"; break; case POKESINT: s << "POKESINT"; break; case POKES: s << "POKES"; break; case POKEC: s << "POKEC"; break; case POKESBIT: s << "POKESBIT"; break; case GETSPINT: s << "GETSPINT"; break; case GETSPSINT: s << "GETSPSINT"; break; case GETSPS: s << "GETSPS"; break; case GETSPC: s << "GETSPC"; break; case GETSPSBIT: s << "GETSPSBIT"; break; case MOVINT: s << "MOVINT"; break; case LDTN: s << "LDTN"; break; case LDARG: s << "LDARG"; break; case REQBL: s << "REQBL"; break; case STARG: s << "STARG"; break; case CALL: s << "CALL"; break; case RETURN: s << "RETURN"; break; case RUN_TAPE: s << "RUN_TAPE"; break; case JOIN_TAPE: s << "JOIN_TAPE"; break; case CRASH: s << "CRASH"; break; case RESTART: s << "RESTART"; break; case CLEAR_MEMORY: s << "CLEAR_MEMORY"; break; case CLEAR_REGISTERS: s << "CLEAR_REGISTERS"; break; case ADDC: s << "ADDC"; break; case ADDS: s << "ADDS"; break; case ADDM: s << "ADDM"; break; case ADDCI: s << "ADDCI"; break; case ADDSI: s << "ADDSI"; break; case SUBC: s << "SUBC"; break; case SUBS: s << "SUBS"; break; case SUBML: s << "SUBML"; break; case SUBMR: s << "SUBMR"; break; case SUBCI: s << "SUBCI"; break; case SUBSI: s << "SUBSI"; break; case SUBCFI: s << "SUBCFI"; break; case SUBSFI: s << "SUBSFI"; break; case MULC: s << "MULC"; break; case MULM: s << "MULM"; break; case MULCI: s << "MULCI"; break; case MULSI: s << "MULSI"; break; case DIVC: s << "DIVC"; break; case DIVCI: s << "DICI"; break; case MODC: s << "MODC"; break; case MODCI: s << "MODCI"; break; case LEGENDREC: s << "LEGENDREC"; break; case DIGESTC: s << "DIGESTC"; break; case OUTPUT_CLEAR: s << "OUTPUT_CLEAR"; break; case INPUT_CLEAR: s << "INPUT_CLEAR"; break; case OUTPUT_SHARES: s << "OUTPUT_SHARES"; break; case INPUT_SHARES: s << "INPUT_SHARES"; break; case PRIVATE_INPUT: s << "PRIVATE_INPUT"; break; case PRIVATE_OUTPUT: s << "PRIVATE_OUTPUT"; break; case OUTPUT_INT: s << "OUTPUT_INT"; break; case INPUT_INT: s << "INPUT_INT"; break; case OPEN_CHANNEL: s << "OPEN_CHANNEL"; break; case CLOSE_CHANNEL: s << "CLOSE_CHANNEL"; break; case STARTOPEN: s << "STARTOPEN"; break; case STOPOPEN: s << "STOPOPEN"; break; case TRIPLE: s << "TRIPLE"; break; case BIT: s << "BIT"; break; case SQUARE: s << "SQUARE"; break; case DABIT: s << "DABIT"; break; case ANDC: s << "ANDC"; break; case XORC: s << "XORC"; break; case ORC: s << "ORC"; break; case ANDCI: s << "ANDCI"; break; case XORCI: s << "XORCI"; break; case ORCI: s << "ORCI"; break; case NOTC: s << "NOTC"; break; case SHLC: s << "SHLC"; break; case SHRC: s << "SHLR"; break; case SHLCI: s << "SHLCI"; break; case SHRCI: s << "SHRCI"; break; case JMP: s << "JMP"; break; case JMPNZ: s << "JMPNZ"; break; case JMPEQZ: s << "JMPEQZ"; break; case EQZINT: s << "EQZINT"; break; case LTZINT: s << "LTZINT"; break; case LTINT: s << "LTINT"; break; case GTINT: s << "GTINT"; break; case EQINT: s << "EQINT"; break; case LDINT: s << "LDINT"; break; case ADDINT: s << "ADDINT"; break; case SUBINT: s << "SUBINT"; break; case MULINT: s << "MULINT"; break; case DIVINT: s << "DIVINT"; break; case CONVINT: s << "CONVINT"; break; case CONVMODP: s << "CONVMODP"; break; case PRINT_MEM: s << "PRINT_MEM"; break; case PRINT_REG: s << "PRINT_REG"; break; case PRINT_CHAR: s << "PRINT_CHAR"; break; case PRINT_CHAR4: s << "PRINT_CHAR4"; break; case PRINT_CHAR_REGINT: s << "PRINT_CHAR_REGINT"; break; case PRINT_CHAR4_REGINT: s << "PRINT_CHAR4_REGINT"; break; case PRINT_FLOAT: s << "PRINT_FLOAT"; break; case PRINT_FIX: s << "PRINT_FIX"; break; case PRINT_INT: s << "PRINT_INT"; break; case PRINT_IEEE_FLOAT: s << "PRINT_IEEE_FLOAT"; break; case RAND: s << "RAND"; break; case START_CLOCK: s << "START_CLOCK"; break; case STOP_CLOCK: s << "STOP_CLOCK"; break; case LDMSINT: s << "LDMSINT"; break; case LDMSINTI: s << "LDMSINTI"; break; case STMSINT: s << "STMSINT"; break; case STMSINTI: s << "STMSINTI"; break; case MOVSINT: s << "MOVSINT"; break; case LDSINT: s << "LDSINT"; break; case ADDSINT: s << "ADDSINT"; break; case ADDSINTC: s << "ADDSINTC"; break; case SUBSINT: s << "SUBSINT"; break; case SUBSINTC: s << "SUBSINTC"; break; case SUBCINTS: s << "SUBCINTS"; break; case MULSINT: s << "MULSINT"; break; case MULSINTC: s << "MULSINTC"; break; case DIVSINT: s << "DIVSINT"; break; case SHLSINT: s << "SHLSINT"; break; case SHRSINT: s << "SHRSINT"; break; case NEG: s << "NEG"; break; case SAND: s << "SAND"; break; case XORSB: s << "XORSB"; break; case ANDSB: s << "ANDSB"; break; case ORSB: s << "ORSB"; break; case NEGB: s << "NEGB"; break; case LTZSINT: s << "LTZSINT"; break; case EQZSINT: s << "EQZSINT"; break; case BITSINT: s << "BITSINT"; break; case SINTBIT: s << "SINTBIT"; break; case CONVSINTSREG: s << "CONVSINTSREG"; break; case CONVREGSREG: s << "CONVREGSREG"; break; case CONVSREGSINT: s << "CONVSREGSINT"; break; case CONVSUREGSINT: s << "CONVSUREGSINT"; break; case OPENSINT: s << "OPENSINT"; break; case OPENSBIT: s << "OPENSBIT"; break; case ANDSINT: s << "ANDSINT"; break; case ANDSINTC: s << "ANDSINTC"; break; case ORSINT: s << "ORSINT"; break; case ORSINTC: s << "ORSINTC"; break; case XORSINT: s << "XORSINT"; break; case XORSINTC: s << "XORSINTC"; break; case INVSINT: s << "INVSINT"; break; case MUL2SINT: s << "MUL2SINT"; break; case GC: s << "GC"; break; case LF: s << "LF"; break; default: s << instr.opcode; throw Invalid_Instruction("Verbose Opcode Note Known"); } if (instr.size != 1) { s << " " << instr.size; } s << " "; // Now the arguments switch (instr.opcode) { // instructions with 3 cint register operands */ case ADDC: case SUBC: case MULC: case DIVC: case MODC: case ANDC: case XORC: case ORC: case SHLC: case SHRC: s << "c_" << instr.r[0] << " "; s << "c_" << instr.r[1] << " "; s << "c_" << instr.r[2] << " "; break; // instructions with 3 sint register operands */ case ADDS: case SUBS: case TRIPLE: s << "s_" << instr.r[0] << " "; s << "s_" << instr.r[1] << " "; s << "s_" << instr.r[2] << " "; break; // instructions with 3 rint register operands */ case ADDINT: case SUBINT: case MULINT: case DIVINT: case LTINT: case GTINT: case EQINT: s << "r_" << instr.r[0] << " "; s << "r_" << instr.r[1] << " "; s << "r_" << instr.r[2] << " "; break; // instructions with 3 sregint register operands */ case ADDSINT: case SUBSINT: case MULSINT: case DIVSINT: case ANDSINT: case ORSINT: case XORSINT: s << "sr_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; s << "sr_" << instr.r[2] << " "; break; // instructions with 3 sbit register operands */ case XORSB: case ANDSB: case ORSB: s << "sb_" << instr.r[0] << " "; s << "sb_" << instr.r[1] << " "; s << "sb_" << instr.r[2] << " "; break; // instructions with 2 sint + 1 cint register operands */ case ADDM: case SUBML: case MULM: s << "s_" << instr.r[0] << " "; s << "s_" << instr.r[1] << " "; s << "c_" << instr.r[2] << " "; break; // instructions with 2 sregint and 1 rint operand case ADDSINTC: case SUBSINTC: case MULSINTC: case ANDSINTC: case ORSINTC: case XORSINTC: s << "sr_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; s << "r_" << instr.r[2] << " "; break; // instructions with 2 sregint and 1 sbit operand case SAND: s << "sr_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; s << "sb_" << instr.r[2] << " "; break; // instructions with 1 sbit and 1 sregint operands case LTZSINT: case EQZSINT: case PEEKSBIT: s << "sb_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; break; // instructions with 1 sbit and 1 sregint and 1 integer operands case BITSINT: s << "sb_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; s << instr.n << " "; break; // instructions with 1 sregint and 1 sbit and 1 integer operands case SINTBIT: s << "sr_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; s << "sb_" << instr.r[2] << " "; s << instr.n << " "; break; // instructions with 1 sint + 1 cint + 1 sint register operands */ case SUBMR: s << "s_" << instr.r[0] << " "; s << "c_" << instr.r[1] << " "; s << "s_" << instr.r[2] << " "; break; // instructions with 1 sregint + 1 rint + 1 sregint operand case SUBCINTS: s << "sr_" << instr.r[0] << " "; s << "r_" << instr.r[1] << " "; s << "sr_" << instr.r[2] << " "; break; // instructions with 1 cint + 1 rint register operand case LDMCI: case CONVINT: case STMCI: case PEEKC: s << "c_" << instr.r[0] << " "; s << "r_" << instr.r[1] << " "; break; // instructions with 1 sint + 1 rint register operand case LDMSI: case STMSI: case PEEKS: s << "s_" << instr.r[0] << " "; s << "r_" << instr.r[1] << " "; break; // instructions with 1 sregint + 1 rint register operand case LDMSINTI: case CONVREGSREG: case PEEKSINT: s << "sr_" << instr.r[0] << " "; s << "r_" << instr.r[1] << " "; break; // instructions with 1 sregint + 1 sint register operand case CONVSINTSREG: s << "sr_" << instr.r[0] << " "; s << "s_" << instr.r[1] << " "; break; // instructions with 1 sint + 1 sregint register operand case CONVSREGSINT: case CONVSUREGSINT: s << "s_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; break; case DABIT: s << "s_" << instr.r[0] << " "; s << "sb_" << instr.r[1] << " "; break; // instructions with 1 rint + 1 sregint register operand case OPENSINT: case POKESINT: s << "r_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; break; // instructions with 1 rint + 1 cint register operand case POKEC: s << "r_" << instr.r[0] << " "; s << "c_" << instr.r[1] << " "; break; // instructions with 1 rint + 1 sint register operand case POKES: s << "r_" << instr.r[0] << " "; s << "s_" << instr.r[1] << " "; break; // instructions with 1 rint + 1 sbit register operand case OPENSBIT: case POKESBIT: s << "r_" << instr.r[0] << " "; s << "sb_" << instr.r[1] << " "; break; // instructions with 2 cint register operands case MOVC: case LEGENDREC: case DIGESTC: s << "c_" << instr.r[0] << " "; s << "c_" << instr.r[1] << " "; break; // instructions with 2 sint register operands case MOVS: case SQUARE: s << "s_" << instr.r[0] << " "; s << "s_" << instr.r[1] << " "; break; // instructions with 2 rint register operands case MOVINT: case LDMINTI: case RAND: case STMINTI: case STMSINTI: case LTZINT: case EQZINT: case PEEKINT: case POKEINT: s << "r_" << instr.r[0] << " "; s << "r_" << instr.r[1] << " "; break; // instructions with 2 srint operands case NEG: case MOVSINT: case INVSINT: s << "sr_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; break; // instructions with 2 sbit operands case NEGB: s << "sb_" << instr.r[0] << " "; s << "sb_" << instr.r[1] << " "; break; // instructions with 1 cint register operands case PRINT_REG: case POPC: case PUSHC: s << "c_" << instr.r[0] << " "; break; // instructions with 1 sint register operands case BIT: case POPS: case PUSHS: s << "s_" << instr.r[0] << " "; break; // instructions with 1 sbit register operands case POPSBIT: case PUSHSBIT: s << "sb_" << instr.r[0] << " "; break; // instructions with 1 srint register operands case POPSINT: case PUSHSINT: s << "sr_" << instr.r[0] << " "; break; // instructions with 1 rint register operands case PRINT_INT: case PRINT_IEEE_FLOAT: case PRINT_CHAR_REGINT: case PRINT_CHAR4_REGINT: case PUSHINT: case POPINT: case STARG: case LDTN: case LDARG: case GETSPINT: case GETSPSINT: case GETSPS: case GETSPC: case GETSPSBIT: s << "r_" << instr.r[0] << " "; break; // instructions with 2 cint + 1 integer operand case ADDCI: case SUBCI: case SUBCFI: case MULCI: case DIVCI: case MODCI: case ANDCI: case XORCI: case ORCI: case SHLCI: case NOTC: s << "c_" << instr.r[0] << " "; s << "c_" << instr.r[1] << " "; s << instr.n << " "; break; // instructions with 2 sint + 1 integer operand case ADDSI: case SUBSI: case SUBSFI: case MULSI: case SHRCI: s << "s_" << instr.r[0] << " "; s << "s_" << instr.r[1] << " "; s << instr.n << " "; break; // instructions with 2 srint + 1 integer operand case SHLSINT: case SHRSINT: s << "sr_" << instr.r[0] << " "; s << "sr_" << instr.r[1] << " "; s << instr.n << " "; break; // instructions with 1 rint + 1 cint + 1 integer operand case CONVMODP: s << "r_" << instr.r[0] << " "; s << "c_" << instr.r[1] << " "; s << instr.n << " "; break; // instructions with 1 rint + 1 integer operand case LDINT: case LDMINT: case STMINT: case JMPNZ: case JMPEQZ: case INPUT_INT: case OPEN_CHANNEL: case OUTPUT_INT: s << "r_" << instr.r[0] << " "; s << instr.n << " "; break; // instructions with 1 sint + 1 integer operand case LDSI: case LDMS: case STMS: s << "s_" << instr.r[0] << " "; s << instr.n << " "; break; // instructions with 1 cint + 1 integer operand case LDI: case LDMC: case STMC: case INPUT_CLEAR: case OUTPUT_CLEAR: s << "c_" << instr.r[0] << " "; s << instr.n << " "; break; // instructions with 1 srint + 1 integer operand case LDSINT: case LDMSINT: case STMSINT: s << "sr_" << instr.r[0] << " "; s << instr.n << " "; break; // instructions with 1 sint + 1 player + 1 integer operand case PRIVATE_INPUT: case PRIVATE_OUTPUT: s << "s_" << instr.r[0] << " "; s << instr.p << " "; s << instr.m << " "; break; // instructions with 1 sint + 2 integer operands case PRINT_FIX: s << "c_" << instr.r[0] << " "; s << instr.n << " "; s << instr.m << " "; break; // instructions with 1 integer operand case PRINT_CHAR: case PRINT_CHAR4: case REQBL: case JMP: case START_CLOCK: case STOP_CLOCK: case CLOSE_CHANNEL: case PRINT_MEM: case JOIN_TAPE: case CALL: case GC: case LF: s << instr.n << " "; break; // instructions with no operand case RESTART: case CRASH: case CLEAR_MEMORY: case CLEAR_REGISTERS: case RETURN: break; // Three integer operands case RUN_TAPE: s << instr.r[0] << " "; s << instr.r[1] << " "; s << instr.r[2] << " "; break; // Various variable length instructions case MUL2SINT: for (unsigned int i= 0; i < instr.start.size(); i++) { s << "sr_" << instr.start[i] << " "; } break; case PRINT_FLOAT: case STOPOPEN: for (unsigned int i= 0; i < instr.start.size(); i++) { s << "c_" << instr.start[i] << " "; } break; case STARTOPEN: for (unsigned int i= 0; i < instr.start.size(); i++) { s << "s_" << instr.start[i] << " "; } break; case OUTPUT_SHARES: case INPUT_SHARES: s << instr.p << " "; for (unsigned int i= 0; i < instr.start.size(); i++) { s << "s_" << instr.start[i] << " "; } break; default: throw Invalid_Instruction("Cannot parse operarands in verbose mode"); } return s; } void Instruction::execute_using_sacrifice_data( Processor &Proc, offline_control_data &OCD) const { int thread= Proc.get_thread_num(); // Check to see if we have to wait Wait_For_Preproc(opcode, size, thread, OCD); int r[3]= {this->r[0], this->r[1], this->r[2]}; switch (opcode) { case TRIPLE: OCD.mul_mutex[thread].lock(); for (unsigned int i= 0; i < size; i++) { Proc.get_Sp_ref(r[0])= SacrificeD[thread].TD.ta.front(); SacrificeD[thread].TD.ta.pop_front(); Proc.get_Sp_ref(r[1])= SacrificeD[thread].TD.tb.front(); SacrificeD[thread].TD.tb.pop_front(); Proc.get_Sp_ref(r[2])= SacrificeD[thread].TD.tc.front(); SacrificeD[thread].TD.tc.pop_front(); r[0]++; r[1]++; r[2]++; } OCD.mul_mutex[thread].unlock(); break; case SQUARE: OCD.sqr_mutex[thread].lock(); for (unsigned int i= 0; i < size; i++) { Proc.get_Sp_ref(r[0])= SacrificeD[thread].SD.sa.front(); SacrificeD[thread].SD.sa.pop_front(); Proc.get_Sp_ref(r[1])= SacrificeD[thread].SD.sb.front(); SacrificeD[thread].SD.sb.pop_front(); r[0]++; r[1]++; } OCD.sqr_mutex[thread].unlock(); break; case BIT: OCD.bit_mutex[thread].lock(); for (unsigned int i= 0; i < size; i++) { Proc.get_Sp_ref(r[0])= SacrificeD[thread].BD.bb.front(); SacrificeD[thread].BD.bb.pop_front(); r[0]++; } OCD.bit_mutex[thread].unlock(); break; default: throw bad_value(); break; } } bool Instruction::execute(Processor &Proc, Player &P, Machine &machine, offline_control_data &OCD) const { if (machine.verbose) { stringstream s; s << *this; printf("Thread %d : %s\n", Proc.get_thread_num(), s.str().c_str()); fflush(stdout); } bool restart= false; Proc.increment_PC(); int r[3]= {this->r[0], this->r[1], this->r[2]}; int n= this->n; /* First deal with instructions we want to deal with outside the main * loop for vectorized instructions */ // Deal the offline data input routines as these need thread locking if (opcode == TRIPLE || opcode == SQUARE || opcode == BIT) { execute_using_sacrifice_data(Proc, OCD); return restart; } // Extract daBit if (opcode == DABIT) { for (unsigned int i= 0; i < size; i++) { Proc.write_daBit(r[0] + i, r[1] + i); } return restart; } // Private input/output if (opcode == PRIVATE_OUTPUT || opcode == PRIVATE_INPUT) { if (Proc.get_thread_num() != 0) { throw IO_thread(); } if (opcode == PRIVATE_OUTPUT) { Proc.iop.private_output(p, r[0], m, Proc, P, machine, OCD, size); } else { Proc.iop.private_input(p, r[0], m, Proc, P, machine, OCD, size); } return restart; } if (opcode == STARTOPEN) { Proc.POpen_Start(start, size, P); return restart; } if (opcode == STOPOPEN) { Proc.POpen_Stop(start, size, P); return restart; } // Need to copy as we might need to alter this in the loop // But it should not be that big in any case here vector<int> c_start= start; // Loop here to cope with vectorization, if an instruction is not vectorizable // then size=1 in any case :-) for (unsigned int i= 0; i < size; i++) { switch (opcode) { case LDI: Proc.temp.ansp.assign(n); Proc.write_Cp(r[0], Proc.temp.ansp); break; case LDSI: { Proc.temp.ansp.assign(n); Proc.get_Sp_ref(r[0]).assign(Proc.temp.ansp, P.get_mac_keys()); } break; case LDMC: Proc.write_Cp(r[0], machine.Mc.read(n, machine.verbose)); n++; break; case LDMS: Proc.write_Sp(r[0], machine.Ms.read(n, machine.verbose)); n++; break; case LDMINT: Proc.write_Ri(r[0], machine.Mr.read(n, machine.verbose).get()); n++; break; case LDMCI: Proc.write_Cp(r[0], machine.Mc.read(Proc.read_Ri(r[1]), machine.verbose)); break; case LDMSI: Proc.write_Sp(r[0], machine.Ms.read(Proc.read_Ri(r[1]), machine.verbose)); break; case LDMINTI: Proc.write_Ri(r[0], machine.Mr.read(Proc.read_Ri(r[1]), machine.verbose).get()); break; case STMC: machine.Mc.write(n, Proc.read_Cp(r[0]), machine.verbose, Proc.get_PC()); n++; break; case STMS: machine.Ms.write(n, Proc.read_Sp(r[0]), machine.verbose, Proc.get_PC()); n++; break; case STMINT: machine.Mr.write(n, Integer(Proc.read_Ri(r[0])), machine.verbose, Proc.get_PC()); n++; break; case STMCI: machine.Mc.write(Proc.read_Ri(r[1]), Proc.read_Cp(r[0]), machine.verbose, Proc.get_PC()); break; case STMSI: machine.Ms.write(Proc.read_Ri(r[1]), Proc.read_Sp(r[0]), machine.verbose, Proc.get_PC()); break; case STMINTI: machine.Mr.write(Proc.read_Ri(r[1]), Integer(Proc.read_Ri(r[0])), machine.verbose, Proc.get_PC()); break; case MOVC: Proc.write_Cp(r[0], Proc.read_Cp(r[1])); break; case MOVS: Proc.write_Sp(r[0], Proc.read_Sp(r[1])); break; case MOVINT: Proc.write_Ri(r[0], Proc.read_Ri(r[1])); break; case PUSHINT: Proc.push_int(Proc.read_Ri(r[0])); break; case PUSHSINT: Proc.push_srint(Proc.read_srint(r[0])); break; case PUSHC: Proc.push_Cp(Proc.read_Cp(r[0])); break; case PUSHS: Proc.push_Sp(Proc.read_Sp(r[0])); break; case PUSHSBIT: Proc.push_sbit(Proc.read_sbit(r[0])); break; case POPINT: Proc.pop_int(Proc.get_Ri_ref(r[0])); break; case POPSINT: Proc.pop_srint(Proc.get_srint_ref(r[0])); break; case POPC: Proc.pop_Cp(Proc.get_Cp_ref(r[0])); break; case POPS: Proc.pop_Sp(Proc.get_Sp_ref(r[0])); break; case POPSBIT: Proc.pop_sbit(Proc.get_sbit_ref(r[0])); break; case PEEKINT: Proc.peek_int(Proc.get_Ri_ref(r[0]), Proc.read_Ri(r[1])); break; case PEEKSINT: Proc.peek_srint(Proc.get_srint_ref(r[0]), Proc.read_Ri(r[1])); break; case PEEKC: Proc.peek_Cp(Proc.get_Cp_ref(r[0]), Proc.read_Ri(r[1])); break; case PEEKS: Proc.peek_Sp(Proc.get_Sp_ref(r[0]), Proc.read_Ri(r[1])); break; case PEEKSBIT: Proc.peek_sbit(Proc.get_sbit_ref(r[0]), Proc.read_Ri(r[1])); break; case POKEINT: Proc.poke_int(Proc.read_Ri(r[0]), Proc.read_Ri(r[1])); break; case POKESINT: Proc.poke_srint(Proc.read_Ri(r[0]), Proc.read_srint(r[1])); break; case POKEC: Proc.poke_Cp(Proc.read_Ri(r[0]), Proc.read_Cp(r[1])); break; case POKES: Proc.poke_Sp(Proc.read_Ri(r[0]), Proc.read_Sp(r[1])); break; case POKESBIT: Proc.poke_sbit(Proc.read_Ri(r[0]), Proc.read_sbit(r[1])); break; case GETSPINT: Proc.getsp_int(Proc.get_Ri_ref(r[0])); break; case GETSPSINT: Proc.getsp_srint(Proc.get_Ri_ref(r[0])); break; case GETSPC: Proc.getsp_Cp(Proc.get_Ri_ref(r[0])); break; case GETSPS: Proc.getsp_Sp(Proc.get_Ri_ref(r[0])); break; case GETSPSBIT: Proc.getsp_sbit(Proc.get_Ri_ref(r[0])); break; case LDTN: Proc.write_Ri(r[0], Proc.get_thread_num()); break; case LDARG: Proc.write_Ri(r[0], Proc.get_arg()); break; case STARG: Proc.set_arg(Proc.read_Ri(r[0])); break; case ADDC: #ifdef DEBUG Proc.temp.ansp.add(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).add(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); #endif break; case ADDS: #ifdef DEBUG Proc.temp.Sansp.add(Proc.read_Sp(r[1]), Proc.read_Sp(r[2])); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).add(Proc.read_Sp(r[1]), Proc.read_Sp(r[2])); #endif break; case ADDM: #ifdef DEBUG Proc.temp.Sansp.add(Proc.read_Sp(r[1]), Proc.read_Cp(r[2]), P.get_mac_keys()); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).add(Proc.read_Sp(r[1]), Proc.read_Cp(r[2]), P.get_mac_keys()); #endif break; case SUBC: #ifdef DEBUG Proc.temp.ansp.sub(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).sub(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); #endif break; case SUBS: #ifdef DEBUG Proc.temp.Sansp.sub(Proc.read_Sp(r[1]), Proc.read_Sp(r[2])); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).sub(Proc.read_Sp(r[1]), Proc.read_Sp(r[2])); #endif break; case SUBML: #ifdef DEBUG Proc.temp.Sansp.sub(Proc.read_Sp(r[1]), Proc.read_Cp(r[2]), P.get_mac_keys()); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).sub(Proc.read_Sp(r[1]), Proc.read_Cp(r[2]), P.get_mac_keys()); #endif break; case SUBMR: #ifdef DEBUG Proc.temp.Sansp.sub(Proc.read_Cp(r[1]), Proc.read_Sp(r[2]), P.get_mac_keys()); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).sub(Proc.read_Cp(r[1]), Proc.read_Sp(r[2]), P.get_mac_keys()); #endif break; case MULC: #ifdef DEBUG Proc.temp.ansp.mul(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).mul(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); #endif break; case MULM: #ifdef DEBUG Proc.temp.Sansp.mul(Proc.read_Sp(r[1]), Proc.read_Cp(r[2])); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).mul(Proc.read_Sp(r[1]), Proc.read_Cp(r[2])); #endif break; case DIVC: if (Proc.read_Cp(r[2]).is_zero()) throw Processor_Error("Division by zero from register"); Proc.temp.ansp.invert(Proc.read_Cp(r[2])); Proc.temp.ansp.mul(Proc.read_Cp(r[1])); Proc.write_Cp(r[0], Proc.temp.ansp); break; case MODC: to_bigint(Proc.temp.aa, Proc.read_Cp(r[1])); to_bigint(Proc.temp.aa2, Proc.read_Cp(r[2])); mpz_fdiv_r(Proc.temp.aa.get_mpz_t(), Proc.temp.aa.get_mpz_t(), Proc.temp.aa2.get_mpz_t()); to_gfp(Proc.temp.ansp, Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); break; case LEGENDREC: to_bigint(Proc.temp.aa, Proc.read_Cp(r[1])); Proc.temp.aa= mpz_legendre(Proc.temp.aa.get_mpz_t(), gfp::pr().get_mpz_t()); to_gfp(Proc.temp.ansp, Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); break; case DIGESTC: { stringstream o; to_bigint(Proc.temp.aa, Proc.read_Cp(r[1])); to_gfp(Proc.temp.ansp, Proc.temp.aa); Proc.temp.ansp.output(o, false); string s= Hash(o.str()); // keep first n bytes istringstream is(s); Proc.temp.ansp.input(is, false); Proc.write_Cp(r[0], Proc.temp.ansp); } break; case DIVCI: if (n == 0) throw Processor_Error("Division by immediate zero"); to_gfp(Proc.temp.ansp, n % gfp::pr()); Proc.temp.ansp.invert(); Proc.temp.ansp.mul(Proc.read_Cp(r[1])); Proc.write_Cp(r[0], Proc.temp.ansp); break; case MODCI: to_bigint(Proc.temp.aa, Proc.read_Cp(r[1])); to_gfp(Proc.temp.ansp, mpz_fdiv_ui(Proc.temp.aa.get_mpz_t(), n)); Proc.write_Cp(r[0], Proc.temp.ansp); break; case ADDCI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.ansp.add(Proc.temp.ansp, Proc.read_Cp(r[1])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).add(Proc.temp.ansp, Proc.read_Cp(r[1])); #endif break; case ADDSI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.Sansp.add(Proc.read_Sp(r[1]), Proc.temp.ansp, P.get_mac_keys()); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).add(Proc.read_Sp(r[1]), Proc.temp.ansp, P.get_mac_keys()); #endif break; case SUBCI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.ansp.sub(Proc.read_Cp(r[1]), Proc.temp.ansp); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).sub(Proc.read_Cp(r[1]), Proc.temp.ansp); #endif break; case SUBSI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.Sansp.sub(Proc.read_Sp(r[1]), Proc.temp.ansp, P.get_mac_keys()); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).sub(Proc.read_Sp(r[1]), Proc.temp.ansp, P.get_mac_keys()); #endif break; case SUBCFI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.ansp.sub(Proc.temp.ansp, Proc.read_Cp(r[1])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).sub(Proc.temp.ansp, Proc.read_Cp(r[1])); #endif break; case SUBSFI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.Sansp.sub(Proc.temp.ansp, Proc.read_Sp(r[1]), P.get_mac_keys()); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).sub(Proc.temp.ansp, Proc.read_Sp(r[1]), P.get_mac_keys()); #endif break; case MULCI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.ansp.mul(Proc.temp.ansp, Proc.read_Cp(r[1])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).mul(Proc.temp.ansp, Proc.read_Cp(r[1])); #endif break; case MULSI: Proc.temp.ansp.assign(n); #ifdef DEBUG Proc.temp.Sansp.mul(Proc.read_Sp(r[1]), Proc.temp.ansp); Proc.write_Sp(r[0], Proc.temp.Sansp); #else Proc.get_Sp_ref(r[0]).mul(Proc.read_Sp(r[1]), Proc.temp.ansp); #endif break; case ANDC: #ifdef DEBUG Proc.temp.ansp.AND(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).AND(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); #endif break; case XORC: #ifdef DEBUG Proc.temp.ansp.XOR(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).XOR(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); #endif break; case ORC: #ifdef DEBUG Proc.temp.ansp.OR(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).OR(Proc.read_Cp(r[1]), Proc.read_Cp(r[2])); #endif break; case ANDCI: Proc.temp.aa= n; #ifdef DEBUG Proc.temp.ansp.AND(Proc.read_Cp(r[1]), Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).AND(Proc.read_Cp(r[1]), Proc.temp.aa); #endif break; case XORCI: Proc.temp.aa= n; #ifdef DEBUG Proc.temp.ansp.XOR(Proc.read_Cp(r[1]), Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).XOR(Proc.read_Cp(r[1]), Proc.temp.aa); #endif break; case ORCI: Proc.temp.aa= n; #ifdef DEBUG Proc.temp.ansp.OR(Proc.read_Cp(r[1]), Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).OR(Proc.read_Cp(r[1]), Proc.temp.aa); #endif break; case NOTC: to_bigint(Proc.temp.aa, Proc.read_Cp(r[1])); mpz_com(Proc.temp.aa.get_mpz_t(), Proc.temp.aa.get_mpz_t()); Proc.temp.aa2= 1; Proc.temp.aa2<<= n; Proc.temp.aa+= Proc.temp.aa2; to_gfp(Proc.temp.ansp, Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); break; case SHLC: to_bigint(Proc.temp.aa, Proc.read_Cp(r[2])); if (Proc.temp.aa > 63) throw not_implemented(); #ifdef DEBUG Proc.temp.ansp.SHL(Proc.read_Cp(r[1]), Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).SHL(Proc.read_Cp(r[1]), Proc.temp.aa); #endif break; case SHRC: to_bigint(Proc.temp.aa, Proc.read_Cp(r[2])); if (Proc.temp.aa > 63) throw not_implemented(); #ifdef DEBUG Proc.temp.ansp.SHR(Proc.read_Cp(r[1]), Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).SHR(Proc.read_Cp(r[1]), Proc.temp.aa); #endif break; case SHLCI: #ifdef DEBUG Proc.temp.ansp.SHL(Proc.read_Cp(r[1]), Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).SHL(Proc.read_Cp(r[1]), n); #endif break; case SHRCI: #ifdef DEBUG Proc.temp.ansp.SHR(Proc.read_Cp(r[1]), Proc.temp.aa); Proc.write_Cp(r[0], Proc.temp.ansp); #else Proc.get_Cp_ref(r[0]).SHR(Proc.read_Cp(r[1]), n); #endif break; case JMP: Proc.relative_jump((signed int) n); break; case JMPNZ: if (Proc.read_Ri(r[0]) != 0) { Proc.relative_jump((signed int) n); } break; case JMPEQZ: if (Proc.read_Ri(r[0]) == 0) { Proc.relative_jump((signed int) n); } break; case CALL: Proc.push_int(Proc.get_PC()); Proc.relative_jump((signed int) n); break; case RETURN: long ret_pos; Proc.pop_int(ret_pos); Proc.jump(ret_pos); break; case EQZINT: if (Proc.read_Ri(r[1]) == 0) Proc.write_Ri(r[0], 1); else Proc.write_Ri(r[0], 0); break; case LTZINT: if (Proc.read_Ri(r[1]) < 0) Proc.write_Ri(r[0], 1); else Proc.write_Ri(r[0], 0); break; case LTINT: if (Proc.read_Ri(r[1]) < Proc.read_Ri(r[2])) Proc.write_Ri(r[0], 1); else Proc.write_Ri(r[0], 0); break; case GTINT: if (Proc.read_Ri(r[1]) > Proc.read_Ri(r[2])) Proc.write_Ri(r[0], 1); else Proc.write_Ri(r[0], 0); break; case EQINT: if (Proc.read_Ri(r[1]) == Proc.read_Ri(r[2])) Proc.write_Ri(r[0], 1); else Proc.write_Ri(r[0], 0); break; case LDINT: Proc.write_Ri(r[0], n); break; case ADDINT: Proc.get_Ri_ref(r[0])= Proc.read_Ri(r[1]) + Proc.read_Ri(r[2]); break; case SUBINT: Proc.get_Ri_ref(r[0])= Proc.read_Ri(r[1]) - Proc.read_Ri(r[2]); break; case MULINT: Proc.get_Ri_ref(r[0])= Proc.read_Ri(r[1]) * Proc.read_Ri(r[2]); break; case DIVINT: Proc.get_Ri_ref(r[0])= Proc.read_Ri(r[1]) / Proc.read_Ri(r[2]); break; case CONVINT: Proc.get_Cp_ref(r[0]).assign(Proc.read_Ri(r[1])); break; case CONVMODP: to_signed_bigint(Proc.temp.aa, Proc.read_Cp(r[1]), n); Proc.write_Ri(r[0], Proc.temp.aa.get_si()); break; case PRINT_MEM: if (P.whoami() == 0) { stringstream ss; ss << "Mem[" << n << "] = " << machine.Mc.read(n, machine.verbose) << endl; machine.get_IO().debug_output(ss); } break; case PRINT_REG: if (P.whoami() == 0) { stringstream ss; ss << Proc.read_Cp(r[0]); machine.get_IO().debug_output(ss); } break; case PRINT_FIX: if (P.whoami() == 0) { gfp v= Proc.read_Cp(r[0]); // immediate values auto f= n; auto k= m; // v has k bits max to_signed_bigint(Proc.temp.aa, v, k); mpf_class res= Proc.temp.aa; // compute v * 2^{-f} mpf_div_2exp(res.get_mpf_t(), res.get_mpf_t(), f); stringstream ss; ss << res; machine.get_IO().debug_output(ss); } break; case PRINT_FLOAT: if (P.whoami() == 0) { gfp v= Proc.read_Cp(c_start[0]); gfp p= Proc.read_Cp(c_start[1]); gfp z= Proc.read_Cp(c_start[2]); gfp s= Proc.read_Cp(c_start[3]); to_bigint(Proc.temp.aa, v); // MPIR can't handle more precision in exponent to_signed_bigint(Proc.temp.aa2, p, 31); long exp= Proc.temp.aa2.get_si(); mpf_class res= Proc.temp.aa; if (exp > 0) mpf_mul_2exp(res.get_mpf_t(), res.get_mpf_t(), exp); else mpf_div_2exp(res.get_mpf_t(), res.get_mpf_t(), -exp); if (z.is_one()) res= 0; if (!s.is_zero()) res*= -1; if (not z.is_bit() or not s.is_bit()) throw Processor_Error("invalid floating point number"); stringstream ss; ss << res; machine.get_IO().debug_output(ss); } break; case PRINT_INT: if (P.whoami() == 0) { stringstream ss; ss << Proc.read_Ri(r[0]); machine.get_IO().debug_output(ss); } break; case PRINT_IEEE_FLOAT: if (P.whoami() == 0) { unsigned long y= Proc.read_Ri(r[0]); // First convert long to bits vector<int> bits(64); for (int index= 0; index < 64; index++) { bits[63 - index]= y & 1; y>>= 1; } // Now convert bits to double double x; uint8_t *ptr= (uint8_t *) &x; for (int index= 0; index < 8; index++) { uint8_t byte= 0; for (int j= 0; j < 8; j++) { byte<<= 1; byte+= bits[56 + j - index * 8]; } ptr[index]= byte; } // Now print the double stringstream ss; ss.precision(numeric_limits<double>::digits10 + 2); ss << x; machine.get_IO().debug_output(ss); } break; case PRINT_CHAR4: if (P.whoami() == 0) { stringstream ss; ss << string((char *) &n, sizeof(n)); machine.get_IO().debug_output(ss); } break; case PRINT_CHAR: if (P.whoami() == 0) { stringstream ss; ss << string((char *) &n, 1); machine.get_IO().debug_output(ss); } break; case PRINT_CHAR_REGINT: if (P.whoami() == 0) { stringstream ss; ss << string((char *) &(Proc.read_Ri(r[0])), 1); machine.get_IO().debug_output(ss); } break; case PRINT_CHAR4_REGINT: if (P.whoami() == 0) { stringstream ss; ss << string((char *) &(Proc.read_Ri(r[0])), sizeof(int)); machine.get_IO().debug_output(ss); } break; case RAND: Proc.write_Ri(r[0], Proc.get_random_uint() % (1 << Proc.read_Ri(r[1]))); break; case START_CLOCK: machine.start_timer(n); break; case STOP_CLOCK: machine.stop_timer(n); break; case REQBL: break; case RUN_TAPE: machine.run_tape(r[0], r[2], r[1]); break; case JOIN_TAPE: machine.Lock_Until_Finished_Tape(n); break; case CRASH: machine.get_IO().crash(Proc.get_PC() - 1, Proc.get_thread_num()); // Note deliberately no "break" to enable CRASH to call RESTART // if the IO.crash returns case RESTART: if (Proc.get_thread_num() != 0) { throw IO_thread(); } restart= true; break; case CLEAR_MEMORY: machine.Mc.clear_memory(); machine.Ms.clear_memory(); machine.Mr.clear_memory(); machine.Msr.clear_memory(); break; case CLEAR_REGISTERS: Proc.clear_registers(); break; case OUTPUT_SHARES: if (Proc.get_thread_num() != 0) { throw IO_thread(); } for (unsigned int j= 0; j < c_start.size(); j++) { machine.get_IO().output_share(Proc.get_Sp_ref(c_start[j]), p); } break; case INPUT_SHARES: if (Proc.get_thread_num() != 0) { throw IO_thread(); } for (unsigned int j= 0; j < c_start.size(); j++) { Proc.get_Sp_ref(c_start[j])= machine.get_IO().input_share(p); } break; case INPUT_CLEAR: if (Proc.get_thread_num() != 0) { throw IO_thread(); } Proc.get_Cp_ref(r[0])= machine.get_IO().public_input_gfp(n); break; case INPUT_INT: if (Proc.get_thread_num() != 0) { throw IO_thread(); } Proc.get_Ri_ref(r[0])= machine.get_IO().public_input_int(n); break; case OUTPUT_CLEAR: if (Proc.get_thread_num() != 0) { throw IO_thread(); } machine.get_IO().public_output_gfp(Proc.read_Cp(r[0]), n); break; case OUTPUT_INT: if (Proc.get_thread_num() != 0) { throw IO_thread(); } machine.get_IO().public_output_int(Proc.read_Ri(r[0]), n); break; case OPEN_CHANNEL: if (Proc.get_thread_num() != 0) { throw IO_thread(); } Proc.get_Ri_ref(r[0])= machine.get_IO().open_channel(n); break; case CLOSE_CHANNEL: if (Proc.get_thread_num() != 0) { throw IO_thread(); } machine.get_IO().close_channel(n); break; /* Now we add in the new instructions for sregint and sbit operations */ case LDMSINT: Proc.write_srint(r[0], machine.Msr.read(n, machine.verbose)); n++; break; case LDMSINTI: Proc.write_srint(r[0], machine.Msr.read(Proc.read_Ri(r[1]), machine.verbose)); break; case STMSINT: machine.Msr.write(n, Proc.read_srint(r[0]), machine.verbose, Proc.get_PC()); n++; break; case STMSINTI: machine.Msr.write(Proc.read_Ri(r[1]), Proc.read_srint(r[0]), machine.verbose, Proc.get_PC()); break; case MOVSINT: Proc.write_srint(r[0], Proc.read_srint(r[1])); break; case LDSINT: Proc.write_srint(r[0], n); break; case LDSBIT: Proc.temp.aB.assign_zero(); Proc.temp.aB.add(n); Proc.write_sbit(r[0], Proc.temp.aB); break; case ADDSINT: Proc.get_srint_ref(r[0]).add(Proc.read_srint(r[1]), Proc.read_srint(r[2]), P, Proc.online_thread_num); break; case ADDSINTC: Proc.get_srint_ref(r[0]).add(Proc.read_srint(r[1]), Proc.read_Ri(r[2]), P, Proc.online_thread_num); break; case SUBSINT: Proc.get_srint_ref(r[0]).sub(Proc.read_srint(r[1]), Proc.read_srint(r[2]), P, Proc.online_thread_num); break; case SUBSINTC: Proc.get_srint_ref(r[0]).sub(Proc.read_srint(r[1]), Proc.read_Ri(r[2]), P, Proc.online_thread_num); break; case SUBCINTS: Proc.get_srint_ref(r[0]).sub(Proc.read_Ri(r[1]), Proc.read_srint(r[2]), P, Proc.online_thread_num); break; case MULSINT: Proc.get_srint_ref(r[0]).mul(Proc.read_srint(r[1]), Proc.read_srint(r[2]), P, Proc.online_thread_num); break; case MULSINTC: Proc.get_srint_ref(r[0]).mul(Proc.read_srint(r[1]), Proc.read_Ri(r[2]), P, Proc.online_thread_num); break; case MUL2SINT: mul(Proc.get_srint_ref(c_start[0]), Proc.get_srint_ref(c_start[1]), Proc.read_srint(c_start[2]), Proc.read_srint(c_start[3]), P, Proc.online_thread_num); break; case DIVSINT: Proc.get_srint_ref(r[0]).div(Proc.read_srint(r[1]), Proc.read_srint(r[2]), P, Proc.online_thread_num); break; case SHLSINT: Proc.get_srint_ref(r[0]).SHL(Proc.read_srint(r[1]), n); break; case SHRSINT: Proc.get_srint_ref(r[0]).SHR(Proc.read_srint(r[1]), n); break; case NEG: Proc.get_srint_ref(r[0]).negate(Proc.read_srint(r[1]), P, Proc.online_thread_num); break; case SAND: Proc.get_srint_ref(r[0]).Bit_AND(Proc.read_srint(r[1]), Proc.read_sbit(r[2]), P, Proc.online_thread_num); break; case ANDSINT: Proc.get_srint_ref(r[0]).Bitwise_AND(Proc.read_srint(r[1]), Proc.read_srint(r[2]), P, Proc.online_thread_num); break; case ANDSINTC: Proc.get_srint_ref(r[0]).Bitwise_AND(Proc.read_srint(r[1]), Proc.read_Ri(r[2])); break; case ORSINT: Proc.get_srint_ref(r[0]).Bitwise_OR(Proc.read_srint(r[1]), Proc.read_srint(r[2]), P, Proc.online_thread_num); break; case ORSINTC: Proc.get_srint_ref(r[0]).Bitwise_OR(Proc.read_srint(r[1]), Proc.read_Ri(r[2])); break; case XORSINT: Proc.get_srint_ref(r[0]).Bitwise_XOR(Proc.read_srint(r[1]), Proc.read_srint(r[2])); break; case XORSINTC: Proc.get_srint_ref(r[0]).Bitwise_XOR(Proc.read_srint(r[1]), Proc.read_Ri(r[2])); break; case INVSINT: Proc.get_srint_ref(r[0]).Bitwise_Negate(Proc.read_srint(r[1])); break; case XORSB: Proc.get_sbit_ref(r[0]).add(Proc.read_sbit(r[1]), Proc.read_sbit(r[2])); break; case ANDSB: OTD.check(); Proc.temp.T= OTD.aAD.get_aAND(Proc.online_thread_num); Mult_aBit(Proc.get_sbit_ref(r[0]), Proc.read_sbit(r[1]), Proc.read_sbit(r[2]), Proc.temp.T, P); break; case ORSB: OTD.check(); Proc.temp.T= OTD.aAD.get_aAND(Proc.online_thread_num); Mult_aBit(Proc.temp.aB, Proc.read_sbit(r[1]), Proc.read_sbit(r[2]), Proc.temp.T, P); Proc.get_sbit_ref(r[0]).add(Proc.read_sbit(r[1]), Proc.read_sbit(r[2])); Proc.get_sbit_ref(r[0]).add(Proc.temp.aB); break; case NEGB: Proc.get_sbit_ref(r[0]).negate(Proc.read_sbit(r[1])); break; case LTZSINT: Proc.get_sbit_ref(r[0])= Proc.read_srint(r[1]).less_than_zero(); break; case EQZSINT: Proc.get_sbit_ref(r[0])= Proc.read_srint(r[1]).equal_zero(P, Proc.online_thread_num); break; case BITSINT: Proc.get_sbit_ref(r[0])= Proc.read_srint(r[1]).get_bit(n); break; case SINTBIT: Proc.get_srint_ref(r[0])= Proc.read_srint(r[1]); Proc.get_srint_ref(r[0]).set_bit(n, Proc.read_sbit(r[2])); break; case CONVSINTSREG: Proc.convert_sint_to_sregint(r[1], r[0], P); break; case CONVSREGSINT: Proc.convert_sregint_to_sint(r[1], r[0], P); break; case CONVSUREGSINT: Proc.convert_suregint_to_sint(r[1], r[0], P); break; case CONVREGSREG: Proc.write_srint(r[0], Proc.read_Ri(r[1])); break; case OPENSINT: Proc.write_Ri(r[0], Proc.read_srint(r[1]).Open(P)); break; case OPENSBIT: int t; Open_aBit(t, Proc.read_sbit(r[1]), P); Proc.write_Ri(r[0], t); break; case GC: Proc.apply_GC(n, P); break; case LF: Global_LF.apply_Function(n, Proc); break; default: printf("Invalid opcode=%d. Since it is not implemented\n", opcode); throw not_implemented(); break; } if (size > 1) { r[0]++; r[1]++; r[2]++; for (unsigned int j= 0; j < c_start.size(); j++) { c_start[j]++; } } } return restart; }
[ "nigel.smart@kuleuven.be" ]
nigel.smart@kuleuven.be
27aa4c4d41834822d4ef87813f962a4ff5effbc0
a718c284782aae0d99d2f4c2cec324002ba79584
/LuminaEngine/Material.cpp
99a70fe5bda060587364cf1277b39d8d3aae7fd0
[]
no_license
justinbonczek/LuminaEngine
a8b905099ba0489b6eb0bddd6c0bc4f936cdef25
2695c2e322bbfaa6e961e846dc480ae70de1d55a
refs/heads/master
2020-03-31T02:36:39.133748
2015-04-15T03:59:40
2015-04-15T03:59:40
31,181,728
0
1
null
null
null
null
UTF-8
C++
false
false
5,686
cpp
#include "Material.hpp" #include <WICTextureLoader.h> #include "Window.hpp" NS_BEGIN Material::Material(GraphicsDevice* graphicsDevice) : blendState(Transparency, graphicsDevice) { tileUV[0] = 1; tileUV[1] = 1; D3D11_SAMPLER_DESC wsd; ZeroMemory(&wsd, sizeof(D3D11_SAMPLER_DESC)); wsd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; wsd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; wsd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; wsd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; wsd.MaxAnisotropy = 0; wsd.ComparisonFunc = D3D11_COMPARISON_NEVER; wsd.MinLOD = 0; wsd.MaxLOD = 0; wsd.MipLODBias = 0; graphicsDevice->getDevice()->CreateSamplerState(&wsd, &sampler); } Material::Material(BlendType blendType, GraphicsDevice* graphicsDevice) : blendState(blendType, graphicsDevice) { tileUV[0] = 1; tileUV[1] = 1; D3D11_SAMPLER_DESC wsd; ZeroMemory(&wsd, sizeof(D3D11_SAMPLER_DESC)); wsd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; wsd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; wsd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; wsd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; wsd.MaxAnisotropy = 0; wsd.ComparisonFunc = D3D11_COMPARISON_NEVER; wsd.MinLOD = 0; wsd.MaxLOD = 0; wsd.MipLODBias = 0; graphicsDevice->getDevice()->CreateSamplerState(&wsd, &sampler); lightMat = new LightMaterial(); } Material::Material(wchar_t* filepath, ID3D11SamplerState* sampler, GraphicsDevice* graphicsDevice) : sampler(sampler), blendState(Transparency, graphicsDevice) { tileUV[0] = 1; tileUV[1] = 1; CreateWICTextureFromFile( graphicsDevice->getDevice(), filepath, 0, &srv); shader = new Shader(); } Material::Material(wchar_t* vertfilepath, wchar_t* pixelfilepath, GraphicsDevice* graphicsDevice) : blendState(Transparency, graphicsDevice) { tileUV[0] = 1; tileUV[1] = 1; D3D11_SAMPLER_DESC wsd; ZeroMemory(&wsd, sizeof(D3D11_SAMPLER_DESC)); wsd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; wsd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; wsd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; wsd.Filter = D3D11_FILTER_ANISOTROPIC; wsd.MaxAnisotropy = 8; wsd.ComparisonFunc = D3D11_COMPARISON_NEVER; wsd.MinLOD = 0; wsd.MaxLOD = 0; wsd.MipLODBias = 0; graphicsDevice->getDevice()->CreateSamplerState(&wsd, &sampler); shader = new Shader(); shader->LoadShader(vertfilepath, Vert, graphicsDevice); shader->LoadShader(pixelfilepath, Pixel, graphicsDevice); } Material::Material(wchar_t* vertfilepath, wchar_t* pixelfilepath, ID3D11SamplerState* _sampler, GraphicsDevice* graphicsDevice) : blendState(Transparency, graphicsDevice) { tileUV[0] = 1; tileUV[1] = 1; shader = new Shader(); shader->LoadShader(vertfilepath, Vert, graphicsDevice); shader->LoadShader(pixelfilepath, Pixel, graphicsDevice); sampler = _sampler; } Material::~Material() { delete shader; delete lightMat; DELETECOM(srv); DELETECOM(normalSrv); DELETECOM(sampler); } void Material::BindSRV(GraphicsDevice* graphicsDevice) { if (srv) { graphicsDevice->getDeviceContext()->VSSetShaderResources(0, 1, &srv); graphicsDevice->getDeviceContext()->PSSetShaderResources(0, 1, &srv); } if (normalSrv) { graphicsDevice->getDeviceContext()->VSSetShaderResources(1, 1, &normalSrv); graphicsDevice->getDeviceContext()->PSSetShaderResources(1, 1, &normalSrv); } } void Material::BindSRV(UINT index, GraphicsDevice* graphicsDevice) { if (srv) { graphicsDevice->getDeviceContext()->VSSetShaderResources(index, 1, &srv); graphicsDevice->getDeviceContext()->PSSetShaderResources(index, 1, &srv); } } void Material::BindShader(GraphicsDevice* graphicsDevice) { shader->BindShader(Vert, graphicsDevice); shader->BindShader(Pixel, graphicsDevice); shader->BindShader(Geometry, graphicsDevice); shader->BindShader(Compute, graphicsDevice); shader->BindShader(Domain, graphicsDevice); } void Material::UnbindPixelShader(GraphicsDevice* graphicsDevice) { shader->UnbindPixelShader(graphicsDevice); } void Material::BindSampler(GraphicsDevice* graphicsDevice) { if (sampler) { graphicsDevice->getDeviceContext()->VSSetSamplers(0, 1, &sampler); graphicsDevice->getDeviceContext()->PSSetSamplers(0, 1, &sampler); } } void Material::BindBlendState(GraphicsDevice* graphicsDevice) { blendState.BindBlendState(graphicsDevice); } void Material::LoadTexture(wchar_t* texturefilepath, GraphicsDevice* graphicsDevice) { CreateWICTextureFromFile(graphicsDevice->getDevice(), texturefilepath, 0, &srv); if (!srv) { printf("Failed to load texture: "); printf((char *)texturefilepath); printf("\n"); } } void Material::LoadNormal(wchar_t* texturefilepath, GraphicsDevice* graphicsDevice) { CreateWICTextureFromFile(graphicsDevice->getDevice(), texturefilepath, 0, &normalSrv); if (!srv) { printf("Failed to load texture: "); printf((char *)texturefilepath); printf("\n"); } } void Material::SetShader(Shader* shader) { this->shader = shader; } void Material::SetShader(wchar_t* filepath, ShaderType type, GraphicsDevice* graphicsDevice) { shader->LoadShader(filepath, type, graphicsDevice); } void Material::SetLightMaterial(LightMaterial* _lightMat) { lightMat = _lightMat; } LightMaterial Material::GetLightMaterial(void) { return *lightMat; } void Material::SetTextureTileU(UINT val) { tileUV[0] = val; } void Material::SetTextureTileV(UINT val) { tileUV[1] = val; } void Material::SetTextureTileUV(UINT val) { tileUV[0] = val; tileUV[1] = val; } void Material::SetTextureTileUV(UINT u, UINT v) { tileUV[0] = u; tileUV[1] = v; } UINT Material::GetTextureTileU() { return tileUV[0]; } UINT Material::GetTextureTileV() { return tileUV[1]; } ID3D11SamplerState* Material::Sampler(void) { return sampler; } ID3D11ShaderResourceView* Material::SRV(void) { return srv; } NS_END
[ "justin.bonczek@gmail.com" ]
justin.bonczek@gmail.com
9e3f5a67022102d32f3866ba246ea48ae5b30f51
8f7c8beaa2fca1907fb4796538ea77b4ecddc300
/ui/gl/gl_bindings_autogen_egl.h
834d697eb7918261562926c21a8ab71190f5a864
[ "BSD-3-Clause" ]
permissive
lgsvl/chromium-src
8f88f6ae2066d5f81fa363f1d80433ec826e3474
5a6b4051e48b069d3eacbfad56eda3ea55526aee
refs/heads/ozone-wayland-62.0.3202.94
2023-03-14T10:58:30.213573
2017-10-26T19:27:03
2017-11-17T09:42:56
108,161,483
8
4
null
2017-12-19T22:53:32
2017-10-24T17:34:08
null
UTF-8
C++
false
false
30,773
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This file is auto-generated from // ui/gl/generate_bindings.py // It's formatted by clang-format using chromium coding style: // clang-format -i -style=chromium filename // DO NOT EDIT! #ifndef UI_GL_GL_BINDINGS_AUTOGEN_EGL_H_ #define UI_GL_GL_BINDINGS_AUTOGEN_EGL_H_ #include <string> namespace gl { class GLContext; typedef EGLBoolean(GL_BINDING_CALL* eglBindAPIProc)(EGLenum api); typedef EGLBoolean(GL_BINDING_CALL* eglBindTexImageProc)(EGLDisplay dpy, EGLSurface surface, EGLint buffer); typedef EGLBoolean(GL_BINDING_CALL* eglChooseConfigProc)( EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config); typedef EGLint(GL_BINDING_CALL* eglClientWaitSyncKHRProc)(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout); typedef EGLBoolean(GL_BINDING_CALL* eglCopyBuffersProc)( EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target); typedef EGLContext(GL_BINDING_CALL* eglCreateContextProc)( EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint* attrib_list); typedef EGLImageKHR(GL_BINDING_CALL* eglCreateImageKHRProc)( EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint* attrib_list); typedef EGLSurface(GL_BINDING_CALL* eglCreatePbufferFromClientBufferProc)( EGLDisplay dpy, EGLenum buftype, void* buffer, EGLConfig config, const EGLint* attrib_list); typedef EGLSurface(GL_BINDING_CALL* eglCreatePbufferSurfaceProc)( EGLDisplay dpy, EGLConfig config, const EGLint* attrib_list); typedef EGLSurface(GL_BINDING_CALL* eglCreatePixmapSurfaceProc)( EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint* attrib_list); typedef EGLStreamKHR(GL_BINDING_CALL* eglCreateStreamKHRProc)( EGLDisplay dpy, const EGLint* attrib_list); typedef EGLBoolean( GL_BINDING_CALL* eglCreateStreamProducerD3DTextureNV12ANGLEProc)( EGLDisplay dpy, EGLStreamKHR stream, EGLAttrib* attrib_list); typedef EGLSyncKHR(GL_BINDING_CALL* eglCreateSyncKHRProc)( EGLDisplay dpy, EGLenum type, const EGLint* attrib_list); typedef EGLSurface(GL_BINDING_CALL* eglCreateWindowSurfaceProc)( EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list); typedef EGLBoolean(GL_BINDING_CALL* eglDestroyContextProc)(EGLDisplay dpy, EGLContext ctx); typedef EGLBoolean(GL_BINDING_CALL* eglDestroyImageKHRProc)(EGLDisplay dpy, EGLImageKHR image); typedef EGLBoolean(GL_BINDING_CALL* eglDestroyStreamKHRProc)( EGLDisplay dpy, EGLStreamKHR stream); typedef EGLBoolean(GL_BINDING_CALL* eglDestroySurfaceProc)(EGLDisplay dpy, EGLSurface surface); typedef EGLBoolean(GL_BINDING_CALL* eglDestroySyncKHRProc)(EGLDisplay dpy, EGLSyncKHR sync); typedef EGLBoolean(GL_BINDING_CALL* eglGetConfigAttribProc)(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint* value); typedef EGLBoolean(GL_BINDING_CALL* eglGetConfigsProc)(EGLDisplay dpy, EGLConfig* configs, EGLint config_size, EGLint* num_config); typedef EGLContext(GL_BINDING_CALL* eglGetCurrentContextProc)(void); typedef EGLDisplay(GL_BINDING_CALL* eglGetCurrentDisplayProc)(void); typedef EGLSurface(GL_BINDING_CALL* eglGetCurrentSurfaceProc)(EGLint readdraw); typedef EGLDisplay(GL_BINDING_CALL* eglGetDisplayProc)( EGLNativeDisplayType display_id); typedef EGLint(GL_BINDING_CALL* eglGetErrorProc)(void); typedef EGLDisplay(GL_BINDING_CALL* eglGetPlatformDisplayEXTProc)( EGLenum platform, void* native_display, const EGLint* attrib_list); typedef __eglMustCastToProperFunctionPointerType( GL_BINDING_CALL* eglGetProcAddressProc)(const char* procname); typedef EGLBoolean(GL_BINDING_CALL* eglGetSyncAttribKHRProc)(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value); typedef EGLBoolean(GL_BINDING_CALL* eglGetSyncValuesCHROMIUMProc)( EGLDisplay dpy, EGLSurface surface, EGLuint64CHROMIUM* ust, EGLuint64CHROMIUM* msc, EGLuint64CHROMIUM* sbc); typedef EGLBoolean(GL_BINDING_CALL* eglImageFlushExternalEXTProc)( EGLDisplay dpy, EGLImageKHR image, const EGLAttrib* attrib_list); typedef EGLBoolean(GL_BINDING_CALL* eglInitializeProc)(EGLDisplay dpy, EGLint* major, EGLint* minor); typedef EGLBoolean(GL_BINDING_CALL* eglMakeCurrentProc)(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); typedef EGLBoolean(GL_BINDING_CALL* eglPostSubBufferNVProc)(EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height); typedef EGLint(GL_BINDING_CALL* eglProgramCacheGetAttribANGLEProc)( EGLDisplay dpy, EGLenum attrib); typedef void(GL_BINDING_CALL* eglProgramCachePopulateANGLEProc)( EGLDisplay dpy, const void* key, EGLint keysize, const void* binary, EGLint binarysize); typedef void(GL_BINDING_CALL* eglProgramCacheQueryANGLEProc)( EGLDisplay dpy, EGLint index, void* key, EGLint* keysize, void* binary, EGLint* binarysize); typedef EGLint(GL_BINDING_CALL* eglProgramCacheResizeANGLEProc)(EGLDisplay dpy, EGLint limit, EGLenum mode); typedef EGLenum(GL_BINDING_CALL* eglQueryAPIProc)(void); typedef EGLBoolean(GL_BINDING_CALL* eglQueryContextProc)(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint* value); typedef EGLBoolean(GL_BINDING_CALL* eglQueryStreamKHRProc)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint* value); typedef EGLBoolean(GL_BINDING_CALL* eglQueryStreamu64KHRProc)( EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR* value); typedef const char*(GL_BINDING_CALL* eglQueryStringProc)(EGLDisplay dpy, EGLint name); typedef EGLBoolean(GL_BINDING_CALL* eglQuerySurfaceProc)(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint* value); typedef EGLBoolean(GL_BINDING_CALL* eglQuerySurfacePointerANGLEProc)( EGLDisplay dpy, EGLSurface surface, EGLint attribute, void** value); typedef EGLBoolean(GL_BINDING_CALL* eglReleaseTexImageProc)(EGLDisplay dpy, EGLSurface surface, EGLint buffer); typedef EGLBoolean(GL_BINDING_CALL* eglReleaseThreadProc)(void); typedef EGLBoolean(GL_BINDING_CALL* eglStreamAttribKHRProc)(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value); typedef EGLBoolean(GL_BINDING_CALL* eglStreamConsumerAcquireKHRProc)( EGLDisplay dpy, EGLStreamKHR stream); typedef EGLBoolean( GL_BINDING_CALL* eglStreamConsumerGLTextureExternalAttribsNVProc)( EGLDisplay dpy, EGLStreamKHR stream, EGLAttrib* attrib_list); typedef EGLBoolean(GL_BINDING_CALL* eglStreamConsumerGLTextureExternalKHRProc)( EGLDisplay dpy, EGLStreamKHR stream); typedef EGLBoolean(GL_BINDING_CALL* eglStreamConsumerReleaseKHRProc)( EGLDisplay dpy, EGLStreamKHR stream); typedef EGLBoolean(GL_BINDING_CALL* eglStreamPostD3DTextureNV12ANGLEProc)( EGLDisplay dpy, EGLStreamKHR stream, void* texture, const EGLAttrib* attrib_list); typedef EGLBoolean(GL_BINDING_CALL* eglSurfaceAttribProc)(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value); typedef EGLBoolean(GL_BINDING_CALL* eglSwapBuffersProc)(EGLDisplay dpy, EGLSurface surface); typedef EGLBoolean(GL_BINDING_CALL* eglSwapBuffersWithDamageKHRProc)( EGLDisplay dpy, EGLSurface surface, EGLint* rects, EGLint n_rects); typedef EGLBoolean(GL_BINDING_CALL* eglSwapIntervalProc)(EGLDisplay dpy, EGLint interval); typedef EGLBoolean(GL_BINDING_CALL* eglTerminateProc)(EGLDisplay dpy); typedef EGLBoolean(GL_BINDING_CALL* eglWaitClientProc)(void); typedef EGLBoolean(GL_BINDING_CALL* eglWaitGLProc)(void); typedef EGLBoolean(GL_BINDING_CALL* eglWaitNativeProc)(EGLint engine); typedef EGLint(GL_BINDING_CALL* eglWaitSyncKHRProc)(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags); struct ExtensionsEGL { bool b_EGL_EXT_platform_base; bool b_EGL_ANGLE_d3d_share_handle_client_buffer; bool b_EGL_ANGLE_program_cache_control; bool b_EGL_ANGLE_query_surface_pointer; bool b_EGL_ANGLE_stream_producer_d3d_texture_nv12; bool b_EGL_ANGLE_surface_d3d_texture_2d_share_handle; bool b_EGL_CHROMIUM_sync_control; bool b_EGL_EXT_image_flush_external; bool b_EGL_KHR_fence_sync; bool b_EGL_KHR_gl_texture_2D_image; bool b_EGL_KHR_image; bool b_EGL_KHR_image_base; bool b_EGL_KHR_stream; bool b_EGL_KHR_stream_consumer_gltexture; bool b_EGL_KHR_swap_buffers_with_damage; bool b_EGL_KHR_wait_sync; bool b_EGL_NV_post_sub_buffer; bool b_EGL_NV_stream_consumer_gltexture_yuv; bool b_GL_CHROMIUM_egl_khr_fence_sync_hack; }; struct ProcsEGL { eglBindAPIProc eglBindAPIFn; eglBindTexImageProc eglBindTexImageFn; eglChooseConfigProc eglChooseConfigFn; eglClientWaitSyncKHRProc eglClientWaitSyncKHRFn; eglCopyBuffersProc eglCopyBuffersFn; eglCreateContextProc eglCreateContextFn; eglCreateImageKHRProc eglCreateImageKHRFn; eglCreatePbufferFromClientBufferProc eglCreatePbufferFromClientBufferFn; eglCreatePbufferSurfaceProc eglCreatePbufferSurfaceFn; eglCreatePixmapSurfaceProc eglCreatePixmapSurfaceFn; eglCreateStreamKHRProc eglCreateStreamKHRFn; eglCreateStreamProducerD3DTextureNV12ANGLEProc eglCreateStreamProducerD3DTextureNV12ANGLEFn; eglCreateSyncKHRProc eglCreateSyncKHRFn; eglCreateWindowSurfaceProc eglCreateWindowSurfaceFn; eglDestroyContextProc eglDestroyContextFn; eglDestroyImageKHRProc eglDestroyImageKHRFn; eglDestroyStreamKHRProc eglDestroyStreamKHRFn; eglDestroySurfaceProc eglDestroySurfaceFn; eglDestroySyncKHRProc eglDestroySyncKHRFn; eglGetConfigAttribProc eglGetConfigAttribFn; eglGetConfigsProc eglGetConfigsFn; eglGetCurrentContextProc eglGetCurrentContextFn; eglGetCurrentDisplayProc eglGetCurrentDisplayFn; eglGetCurrentSurfaceProc eglGetCurrentSurfaceFn; eglGetDisplayProc eglGetDisplayFn; eglGetErrorProc eglGetErrorFn; eglGetPlatformDisplayEXTProc eglGetPlatformDisplayEXTFn; eglGetProcAddressProc eglGetProcAddressFn; eglGetSyncAttribKHRProc eglGetSyncAttribKHRFn; eglGetSyncValuesCHROMIUMProc eglGetSyncValuesCHROMIUMFn; eglImageFlushExternalEXTProc eglImageFlushExternalEXTFn; eglInitializeProc eglInitializeFn; eglMakeCurrentProc eglMakeCurrentFn; eglPostSubBufferNVProc eglPostSubBufferNVFn; eglProgramCacheGetAttribANGLEProc eglProgramCacheGetAttribANGLEFn; eglProgramCachePopulateANGLEProc eglProgramCachePopulateANGLEFn; eglProgramCacheQueryANGLEProc eglProgramCacheQueryANGLEFn; eglProgramCacheResizeANGLEProc eglProgramCacheResizeANGLEFn; eglQueryAPIProc eglQueryAPIFn; eglQueryContextProc eglQueryContextFn; eglQueryStreamKHRProc eglQueryStreamKHRFn; eglQueryStreamu64KHRProc eglQueryStreamu64KHRFn; eglQueryStringProc eglQueryStringFn; eglQuerySurfaceProc eglQuerySurfaceFn; eglQuerySurfacePointerANGLEProc eglQuerySurfacePointerANGLEFn; eglReleaseTexImageProc eglReleaseTexImageFn; eglReleaseThreadProc eglReleaseThreadFn; eglStreamAttribKHRProc eglStreamAttribKHRFn; eglStreamConsumerAcquireKHRProc eglStreamConsumerAcquireKHRFn; eglStreamConsumerGLTextureExternalAttribsNVProc eglStreamConsumerGLTextureExternalAttribsNVFn; eglStreamConsumerGLTextureExternalKHRProc eglStreamConsumerGLTextureExternalKHRFn; eglStreamConsumerReleaseKHRProc eglStreamConsumerReleaseKHRFn; eglStreamPostD3DTextureNV12ANGLEProc eglStreamPostD3DTextureNV12ANGLEFn; eglSurfaceAttribProc eglSurfaceAttribFn; eglSwapBuffersProc eglSwapBuffersFn; eglSwapBuffersWithDamageKHRProc eglSwapBuffersWithDamageKHRFn; eglSwapIntervalProc eglSwapIntervalFn; eglTerminateProc eglTerminateFn; eglWaitClientProc eglWaitClientFn; eglWaitGLProc eglWaitGLFn; eglWaitNativeProc eglWaitNativeFn; eglWaitSyncKHRProc eglWaitSyncKHRFn; }; class GL_EXPORT EGLApi { public: EGLApi(); virtual ~EGLApi(); virtual void SetDisabledExtensions(const std::string& disabled_extensions) {} virtual EGLBoolean eglBindAPIFn(EGLenum api) = 0; virtual EGLBoolean eglBindTexImageFn(EGLDisplay dpy, EGLSurface surface, EGLint buffer) = 0; virtual EGLBoolean eglChooseConfigFn(EGLDisplay dpy, const EGLint* attrib_list, EGLConfig* configs, EGLint config_size, EGLint* num_config) = 0; virtual EGLint eglClientWaitSyncKHRFn(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout) = 0; virtual EGLBoolean eglCopyBuffersFn(EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target) = 0; virtual EGLContext eglCreateContextFn(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint* attrib_list) = 0; virtual EGLImageKHR eglCreateImageKHRFn(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint* attrib_list) = 0; virtual EGLSurface eglCreatePbufferFromClientBufferFn( EGLDisplay dpy, EGLenum buftype, void* buffer, EGLConfig config, const EGLint* attrib_list) = 0; virtual EGLSurface eglCreatePbufferSurfaceFn(EGLDisplay dpy, EGLConfig config, const EGLint* attrib_list) = 0; virtual EGLSurface eglCreatePixmapSurfaceFn(EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint* attrib_list) = 0; virtual EGLStreamKHR eglCreateStreamKHRFn(EGLDisplay dpy, const EGLint* attrib_list) = 0; virtual EGLBoolean eglCreateStreamProducerD3DTextureNV12ANGLEFn( EGLDisplay dpy, EGLStreamKHR stream, EGLAttrib* attrib_list) = 0; virtual EGLSyncKHR eglCreateSyncKHRFn(EGLDisplay dpy, EGLenum type, const EGLint* attrib_list) = 0; virtual EGLSurface eglCreateWindowSurfaceFn(EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint* attrib_list) = 0; virtual EGLBoolean eglDestroyContextFn(EGLDisplay dpy, EGLContext ctx) = 0; virtual EGLBoolean eglDestroyImageKHRFn(EGLDisplay dpy, EGLImageKHR image) = 0; virtual EGLBoolean eglDestroyStreamKHRFn(EGLDisplay dpy, EGLStreamKHR stream) = 0; virtual EGLBoolean eglDestroySurfaceFn(EGLDisplay dpy, EGLSurface surface) = 0; virtual EGLBoolean eglDestroySyncKHRFn(EGLDisplay dpy, EGLSyncKHR sync) = 0; virtual EGLBoolean eglGetConfigAttribFn(EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint* value) = 0; virtual EGLBoolean eglGetConfigsFn(EGLDisplay dpy, EGLConfig* configs, EGLint config_size, EGLint* num_config) = 0; virtual EGLContext eglGetCurrentContextFn(void) = 0; virtual EGLDisplay eglGetCurrentDisplayFn(void) = 0; virtual EGLSurface eglGetCurrentSurfaceFn(EGLint readdraw) = 0; virtual EGLDisplay eglGetDisplayFn(EGLNativeDisplayType display_id) = 0; virtual EGLint eglGetErrorFn(void) = 0; virtual EGLDisplay eglGetPlatformDisplayEXTFn(EGLenum platform, void* native_display, const EGLint* attrib_list) = 0; virtual __eglMustCastToProperFunctionPointerType eglGetProcAddressFn( const char* procname) = 0; virtual EGLBoolean eglGetSyncAttribKHRFn(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint* value) = 0; virtual EGLBoolean eglGetSyncValuesCHROMIUMFn(EGLDisplay dpy, EGLSurface surface, EGLuint64CHROMIUM* ust, EGLuint64CHROMIUM* msc, EGLuint64CHROMIUM* sbc) = 0; virtual EGLBoolean eglImageFlushExternalEXTFn( EGLDisplay dpy, EGLImageKHR image, const EGLAttrib* attrib_list) = 0; virtual EGLBoolean eglInitializeFn(EGLDisplay dpy, EGLint* major, EGLint* minor) = 0; virtual EGLBoolean eglMakeCurrentFn(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx) = 0; virtual EGLBoolean eglPostSubBufferNVFn(EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height) = 0; virtual EGLint eglProgramCacheGetAttribANGLEFn(EGLDisplay dpy, EGLenum attrib) = 0; virtual void eglProgramCachePopulateANGLEFn(EGLDisplay dpy, const void* key, EGLint keysize, const void* binary, EGLint binarysize) = 0; virtual void eglProgramCacheQueryANGLEFn(EGLDisplay dpy, EGLint index, void* key, EGLint* keysize, void* binary, EGLint* binarysize) = 0; virtual EGLint eglProgramCacheResizeANGLEFn(EGLDisplay dpy, EGLint limit, EGLenum mode) = 0; virtual EGLenum eglQueryAPIFn(void) = 0; virtual EGLBoolean eglQueryContextFn(EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint* value) = 0; virtual EGLBoolean eglQueryStreamKHRFn(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint* value) = 0; virtual EGLBoolean eglQueryStreamu64KHRFn(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR* value) = 0; virtual const char* eglQueryStringFn(EGLDisplay dpy, EGLint name) = 0; virtual EGLBoolean eglQuerySurfaceFn(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint* value) = 0; virtual EGLBoolean eglQuerySurfacePointerANGLEFn(EGLDisplay dpy, EGLSurface surface, EGLint attribute, void** value) = 0; virtual EGLBoolean eglReleaseTexImageFn(EGLDisplay dpy, EGLSurface surface, EGLint buffer) = 0; virtual EGLBoolean eglReleaseThreadFn(void) = 0; virtual EGLBoolean eglStreamAttribKHRFn(EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value) = 0; virtual EGLBoolean eglStreamConsumerAcquireKHRFn(EGLDisplay dpy, EGLStreamKHR stream) = 0; virtual EGLBoolean eglStreamConsumerGLTextureExternalAttribsNVFn( EGLDisplay dpy, EGLStreamKHR stream, EGLAttrib* attrib_list) = 0; virtual EGLBoolean eglStreamConsumerGLTextureExternalKHRFn( EGLDisplay dpy, EGLStreamKHR stream) = 0; virtual EGLBoolean eglStreamConsumerReleaseKHRFn(EGLDisplay dpy, EGLStreamKHR stream) = 0; virtual EGLBoolean eglStreamPostD3DTextureNV12ANGLEFn( EGLDisplay dpy, EGLStreamKHR stream, void* texture, const EGLAttrib* attrib_list) = 0; virtual EGLBoolean eglSurfaceAttribFn(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value) = 0; virtual EGLBoolean eglSwapBuffersFn(EGLDisplay dpy, EGLSurface surface) = 0; virtual EGLBoolean eglSwapBuffersWithDamageKHRFn(EGLDisplay dpy, EGLSurface surface, EGLint* rects, EGLint n_rects) = 0; virtual EGLBoolean eglSwapIntervalFn(EGLDisplay dpy, EGLint interval) = 0; virtual EGLBoolean eglTerminateFn(EGLDisplay dpy) = 0; virtual EGLBoolean eglWaitClientFn(void) = 0; virtual EGLBoolean eglWaitGLFn(void) = 0; virtual EGLBoolean eglWaitNativeFn(EGLint engine) = 0; virtual EGLint eglWaitSyncKHRFn(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags) = 0; }; } // namespace gl #define eglBindAPI ::gl::g_current_egl_context->eglBindAPIFn #define eglBindTexImage ::gl::g_current_egl_context->eglBindTexImageFn #define eglChooseConfig ::gl::g_current_egl_context->eglChooseConfigFn #define eglClientWaitSyncKHR ::gl::g_current_egl_context->eglClientWaitSyncKHRFn #define eglCopyBuffers ::gl::g_current_egl_context->eglCopyBuffersFn #define eglCreateContext ::gl::g_current_egl_context->eglCreateContextFn #define eglCreateImageKHR ::gl::g_current_egl_context->eglCreateImageKHRFn #define eglCreatePbufferFromClientBuffer \ ::gl::g_current_egl_context->eglCreatePbufferFromClientBufferFn #define eglCreatePbufferSurface \ ::gl::g_current_egl_context->eglCreatePbufferSurfaceFn #define eglCreatePixmapSurface \ ::gl::g_current_egl_context->eglCreatePixmapSurfaceFn #define eglCreateStreamKHR ::gl::g_current_egl_context->eglCreateStreamKHRFn #define eglCreateStreamProducerD3DTextureNV12ANGLE \ ::gl::g_current_egl_context->eglCreateStreamProducerD3DTextureNV12ANGLEFn #define eglCreateSyncKHR ::gl::g_current_egl_context->eglCreateSyncKHRFn #define eglCreateWindowSurface \ ::gl::g_current_egl_context->eglCreateWindowSurfaceFn #define eglDestroyContext ::gl::g_current_egl_context->eglDestroyContextFn #define eglDestroyImageKHR ::gl::g_current_egl_context->eglDestroyImageKHRFn #define eglDestroyStreamKHR ::gl::g_current_egl_context->eglDestroyStreamKHRFn #define eglDestroySurface ::gl::g_current_egl_context->eglDestroySurfaceFn #define eglDestroySyncKHR ::gl::g_current_egl_context->eglDestroySyncKHRFn #define eglGetConfigAttrib ::gl::g_current_egl_context->eglGetConfigAttribFn #define eglGetConfigs ::gl::g_current_egl_context->eglGetConfigsFn #define eglGetCurrentContext ::gl::g_current_egl_context->eglGetCurrentContextFn #define eglGetCurrentDisplay ::gl::g_current_egl_context->eglGetCurrentDisplayFn #define eglGetCurrentSurface ::gl::g_current_egl_context->eglGetCurrentSurfaceFn #define eglGetDisplay ::gl::g_current_egl_context->eglGetDisplayFn #define eglGetError ::gl::g_current_egl_context->eglGetErrorFn #define eglGetPlatformDisplayEXT \ ::gl::g_current_egl_context->eglGetPlatformDisplayEXTFn #define eglGetProcAddress ::gl::g_current_egl_context->eglGetProcAddressFn #define eglGetSyncAttribKHR ::gl::g_current_egl_context->eglGetSyncAttribKHRFn #define eglGetSyncValuesCHROMIUM \ ::gl::g_current_egl_context->eglGetSyncValuesCHROMIUMFn #define eglImageFlushExternalEXT \ ::gl::g_current_egl_context->eglImageFlushExternalEXTFn #define eglInitialize ::gl::g_current_egl_context->eglInitializeFn #define eglMakeCurrent ::gl::g_current_egl_context->eglMakeCurrentFn #define eglPostSubBufferNV ::gl::g_current_egl_context->eglPostSubBufferNVFn #define eglProgramCacheGetAttribANGLE \ ::gl::g_current_egl_context->eglProgramCacheGetAttribANGLEFn #define eglProgramCachePopulateANGLE \ ::gl::g_current_egl_context->eglProgramCachePopulateANGLEFn #define eglProgramCacheQueryANGLE \ ::gl::g_current_egl_context->eglProgramCacheQueryANGLEFn #define eglProgramCacheResizeANGLE \ ::gl::g_current_egl_context->eglProgramCacheResizeANGLEFn #define eglQueryAPI ::gl::g_current_egl_context->eglQueryAPIFn #define eglQueryContext ::gl::g_current_egl_context->eglQueryContextFn #define eglQueryStreamKHR ::gl::g_current_egl_context->eglQueryStreamKHRFn #define eglQueryStreamu64KHR ::gl::g_current_egl_context->eglQueryStreamu64KHRFn #define eglQueryString ::gl::g_current_egl_context->eglQueryStringFn #define eglQuerySurface ::gl::g_current_egl_context->eglQuerySurfaceFn #define eglQuerySurfacePointerANGLE \ ::gl::g_current_egl_context->eglQuerySurfacePointerANGLEFn #define eglReleaseTexImage ::gl::g_current_egl_context->eglReleaseTexImageFn #define eglReleaseThread ::gl::g_current_egl_context->eglReleaseThreadFn #define eglStreamAttribKHR ::gl::g_current_egl_context->eglStreamAttribKHRFn #define eglStreamConsumerAcquireKHR \ ::gl::g_current_egl_context->eglStreamConsumerAcquireKHRFn #define eglStreamConsumerGLTextureExternalAttribsNV \ ::gl::g_current_egl_context->eglStreamConsumerGLTextureExternalAttribsNVFn #define eglStreamConsumerGLTextureExternalKHR \ ::gl::g_current_egl_context->eglStreamConsumerGLTextureExternalKHRFn #define eglStreamConsumerReleaseKHR \ ::gl::g_current_egl_context->eglStreamConsumerReleaseKHRFn #define eglStreamPostD3DTextureNV12ANGLE \ ::gl::g_current_egl_context->eglStreamPostD3DTextureNV12ANGLEFn #define eglSurfaceAttrib ::gl::g_current_egl_context->eglSurfaceAttribFn #define eglSwapBuffers ::gl::g_current_egl_context->eglSwapBuffersFn #define eglSwapBuffersWithDamageKHR \ ::gl::g_current_egl_context->eglSwapBuffersWithDamageKHRFn #define eglSwapInterval ::gl::g_current_egl_context->eglSwapIntervalFn #define eglTerminate ::gl::g_current_egl_context->eglTerminateFn #define eglWaitClient ::gl::g_current_egl_context->eglWaitClientFn #define eglWaitGL ::gl::g_current_egl_context->eglWaitGLFn #define eglWaitNative ::gl::g_current_egl_context->eglWaitNativeFn #define eglWaitSyncKHR ::gl::g_current_egl_context->eglWaitSyncKHRFn #endif // UI_GL_GL_BINDINGS_AUTOGEN_EGL_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d9784e5cf46c395c4e8ea281cfaa4fb47f1dd0bb
a04104fd9b4e19cbc13c048acdcfeed75b75e42a
/Documentation/Codes/ISR_matching.cpp
c55bde0e757596a3b5b493651b087365fdab1676
[]
no_license
andresfgarcia150/ISR_tagging_project
08fcb13fbe540dc97219ea363aebd3943907c213
0dfb79dcab994fd780a89aa3a0b416ad5c9a0913
refs/heads/master
2021-04-22T13:19:58.525891
2015-07-14T17:52:41
2015-07-14T17:52:41
35,492,042
0
2
null
null
null
null
UTF-8
C++
false
false
13,916
cpp
/* ------------------------------------------------- ------- Universidad de los Andes ------- ------- Departamento de Fisica ------- ------- Joven Investigador ------- ------- Andres Felipe Garcia Albarracin ------- ------- Juan Carlos Sanabria Arenas ------- ------------------------------------------------- This algorithm looks for the ISR parton into the pythia8 simulation file and then finds the corresponding ISR jet It also stores in a binary file the matching results To run, type ./ISR_matching_improved [config.txt] [000] where [config.txt] is the configuration file and [000] is the seed of the simulation under analysis */ #include <iostream> #include "ROOTFunctions.h" #include "graphs_Funcs.h" #include "functions.h" #include "DelphesFunctions.h" using namespace std; // Global Variables const Double_t PI = TMath::Pi(); int main(int argc, char **argv){ std::cout.precision(4); // Counting time Double_t initialTime = clock(); // Folder variables string head_folder = "/home/af.garcia1214/PhenoMCsamples/Simulations/MG_pythia8_delphes_parallel/_Tops_Events_WI_Matching/"; string current_folder = "_Tops_MG_1K_AG_WI_003/"; string head_folder_results = "/home/af.garcia1214/PhenoMCsamples/Results_Improved_Codes/matching_Results/_Tops_matchs_WI_Matching/"; string matching_name = "ISR_jets_Tops_WI_003.bn"; // Checking input parameters string config_file_name = "Debug/config_file.txt"; // Reading the file as first parameter if (argc>1){ config_file_name = argv[1]; } else{ cout << "It is necessary to type a configuration file as parameter. Execute as ./ISR_matching config_file.txt [000]" << endl; return 1; } cout << "Reading input parameters" << endl; cout << "\tUsing as parameters' file: " << config_file_name << endl; ifstream config_file (config_file_name); if (config_file.is_open()){ cout << "\tReading file" << endl; string line; int number_line = 1; while (getline(config_file,line)){ // Skipping commented lines if (line[0] == '!') continue; // Finding the position of the equal sign int pos_equal = -1; pos_equal = line.find('='); if (pos_equal == -1){ cout << "\tLine " << number_line << " is incorrect" << endl; continue; } // Splitting the line according to the position of equal sign string var_name = line.substr(0,pos_equal); string var_value = line.substr(pos_equal+1); // Reading head folder if(var_name.compare("head_folder") == 0){ head_folder = var_value; cout << "\tVariable head folder set as: " << head_folder << endl; } // Reading current folder else if (var_name.compare("current_folder") == 0){ current_folder = var_value; cout << "\tVariable current folder set as: " << current_folder <<endl; } // Reading head folder results else if (var_name.compare("head_folder_results") == 0){ head_folder_results = var_value; cout << "\tVariable head folder results set as: " << head_folder_results << endl; } // Reading matching name else if (var_name.compare("matching_name") == 0){ matching_name = var_value; cout << "\tVariable matching_name set as: " << matching_name << endl; } number_line ++; } } else { cout << "ERROR: File " << config_file_name << " does not exist. Terminating program" << endl; return 0; } // Reading the seed of the simulation. This parameter is optional and is the second of argv Char_t unidad = '3'; Char_t decena = '0'; Char_t centena = '0'; if (argc > 2){ cout << "\tRemember: The number of the simulation should consist of 3 digits" << endl; centena = argv[2][0]; decena = argv[2][1]; unidad = argv[2][2]; current_folder[current_folder.size()-4] = centena; current_folder[current_folder.size()-3] = decena; current_folder[current_folder.size()-2] = unidad; matching_name[matching_name.size()-6] = centena; matching_name[matching_name.size()-5] = decena; matching_name[matching_name.size()-4] = unidad; } cout << "\tThe seed of the simulation is: " << centena << decena << unidad << endl; // Full path name of pythia and Delphes simulations string file_pythia_str = head_folder + current_folder + "Events/run_01/output_pythia8.root"; Char_t *file_pythia = (Char_t *) file_pythia_str.c_str(); //Pass string to char_t * string file_delphes_str = head_folder + current_folder + "Events/run_01/output_delphes.root"; Char_t *file_delphes = (Char_t *) file_delphes_str.c_str(); if (argc > 2){ cout << "\n\tReading the files: \n\tPythia8: " << file_pythia << "\n\tDelphes: " << file_delphes << endl; } else cout << "\n\tReading the default files: \n\tPythia8: " << file_pythia << "\n\tDelphes: " << file_delphes << endl; // Loading simulations of Pythia and Delphes cout << "\nLoading simulations of Pythia and Delphes" << endl; // Create chains of root trees TChain chain_Pythia("STDHEP"); TChain chain_Delphes("Delphes"); chain_Pythia.Add(file_pythia); chain_Delphes.Add(file_delphes); // Objects of class ExRootTreeReader for reading the information ExRootTreeReader *treeReader_Pythia = new ExRootTreeReader(&chain_Pythia); ExRootTreeReader *treeReader_Delphes = new ExRootTreeReader(&chain_Delphes); Long64_t numberOfEntries = treeReader_Pythia->GetEntries(); Long64_t numberOfEntries_Delphes = treeReader_Delphes->GetEntries(); // Get pointers to branches used in this analysis TClonesArray *branchParticlePythia = treeReader_Pythia->UseBranch("GenParticle"); TClonesArray *branchJet = treeReader_Delphes->UseBranch("Jet"); TClonesArray *branchMissingET = treeReader_Delphes->UseBranch("MissingET"); cout << endl; cout << "\tNumber of Entries Pythia = " << numberOfEntries << endl; cout << "\tNumber of Entries Delphes = " << numberOfEntries_Delphes << endl; cout << endl; // particles, jets and vectors TRootGenParticle *particle_pythia; TRootGenParticle *ISR_particle; MissingET *METpointer; TLorentzVector *vect_ISR_particle = new TLorentzVector; // Temporary variables Bool_t ISR_parton_found = false; // true if the initial ISR_parton (with status 43) was found Int_t pos_ISR = -1; // position of the ISR_parton into the branchParticlePythia array Double_t MET = 0.0; // Missing transverse energy /* * Some variables used through the code */ Int_t NumEvents1ISRJet = 0; // Number of events where the number of ISR jets is 1 Int_t NumMatches = 0; // Number of matches Int_t NumJets = 0; Int_t ISR_match_index = -1; Double_t Cut_matching_DPT = 50.0; Double_t Cut_matching_DEta = 0.4; Double_t Cut_matching_DPhi = 0.4; Double_t Cut_matching_Dy = 0.4; Int_t ISR_jets[numberOfEntries]; /* * Main cycle of the program */ cout << "Running the matching algorithm" << endl; numberOfEntries = 100000; for (Int_t entry = 0; entry < numberOfEntries; ++entry){ // Progress if(numberOfEntries>10 && (entry%((int)numberOfEntries/10))==0.0){ cout<<"\tprogress = "<<(entry*100/numberOfEntries)<<"%\t"; cout<< "Time :"<< (clock()-initialTime)/double_t(CLOCKS_PER_SEC)<<"s"<<endl; } // Load selected branches with data from specified event treeReader_Pythia->ReadEntry(entry); treeReader_Delphes->ReadEntry(entry); // By default, the ISR jet was not matched ISR_jets[entry] = -1; // MET METpointer = (MissingET*) branchMissingET->At(0); MET = METpointer->MET; // Finding the ISR parton ISR_parton_found = false; pos_ISR = -1; for(Int_t iPart = 0; iPart < branchParticlePythia->GetEntries(); iPart++){ particle_pythia = (TRootGenParticle*) branchParticlePythia->At(iPart); if( abs(particle_pythia->Status) == 43){ pos_ISR = iPart; ISR_particle = (TRootGenParticle*) branchParticlePythia->At(pos_ISR); ISR_parton_found = true; // cout << pos_ISR << "\t\t" << ISR_particle->Status << "\t\t" << ISR_particle->PID // << "\t\t" << ISR_particle->M1 << "\t\t" << ISR_particle->M2 // << "\t\t" << ISR_particle->D1 << "\t\t" << ISR_particle->D2 << endl; } } // If there is not ISR parton, pass to the next event if (ISR_parton_found == false){ continue; } // Finding the last copy of the ISR_parton ISR_parton_found = false; while (!ISR_parton_found){ if (ISR_particle->D1 != ISR_particle->D2) ISR_parton_found = true; else{ pos_ISR = ISR_particle->D1; if(pos_ISR != -1) // To avoid an incoherent event ISR_particle = (TRootGenParticle*) branchParticlePythia->At(pos_ISR); else ISR_parton_found = true; // To end up the while loop } } if (pos_ISR == -1) // End the incoherent events continue; // Matching algorithm // Matching between the ISR parton and a jet // Auxiliary variables Double_t R_min = 2.0; Double_t r; // Current deltaR ISR_match_index = -1; Int_t mixJets = 0; TLorentzVector *vect_Jet1 = new TLorentzVector(); // Four-momentum of the jet of the 1st for TLorentzVector *vect_Jetc = new TLorentzVector(); // Four-momentum of the jet of the 2nd, 3rd ... for TLorentzVector *vect_Jets = new TLorentzVector(); // Four-momentum of the sum of jets TLorentzVector *vect_Jeto = new TLorentzVector(); // Four-momentum of the optimal combination Jet *jet = new Jet(); Jet *jet2 = new Jet(); NumJets = branchJet->GetEntries(); vect_ISR_particle->SetPtEtaPhiE(ISR_particle->PT,ISR_particle->Eta,ISR_particle->Phi,ISR_particle->E); if (NumJets < 3) // Minimun 3 jets per event continue; // Finding the jet with the minimum R to the ISR parton for ( Int_t j = 0; j < NumJets; j++ ) { // Loop over jets finding the one with the minimum R jet = (Jet*) branchJet->At(j); vect_Jet1->SetPtEtaPhiM(jet->PT, jet->Eta, jet->Phi, jet->Mass); r = vect_ISR_particle->DeltaR(*vect_Jet1); if ( r < R_min ) { R_min = r; ISR_match_index = j; mixJets = 1; *vect_Jeto = *vect_Jet1; } // Checking if there are two jets mixed for ( Int_t k = j+1; k<NumJets; k++){ jet2 = (Jet*) branchJet->At(k); vect_Jetc->SetPtEtaPhiM(jet2->PT, jet2->Eta, jet2->Phi, jet2->Mass); *vect_Jets = *vect_Jet1 + *vect_Jetc; r = vect_ISR_particle->DeltaR(*vect_Jets); if ( r < R_min ) { R_min = r; ISR_match_index = j; mixJets = 2; *vect_Jeto = *vect_Jets; } // Checking if there are three jets mixed for (Int_t m = k+1; m<NumJets; m++){ jet2 = (Jet*) branchJet->At(m); vect_Jetc->SetPtEtaPhiM(jet2->PT, jet2->Eta, jet2->Phi, jet2->Mass); *vect_Jets = *vect_Jets + *vect_Jetc; r = vect_ISR_particle->DeltaR(*vect_Jets); if ( r < R_min ) { R_min = r; ISR_match_index = j; mixJets = 3; *vect_Jeto = *vect_Jets; } // Checking if there are four jets mixed for (Int_t n = m+1; n<NumJets; n++){ jet2 = (Jet*) branchJet->At(n); vect_Jetc->SetPtEtaPhiM(jet2->PT, jet2->Eta, jet2->Phi, jet2->Mass); *vect_Jets = *vect_Jets + *vect_Jetc; r = vect_ISR_particle->DeltaR(*vect_Jets); if ( r < R_min ) { R_min = r; ISR_match_index = j; mixJets = 4; *vect_Jeto = *vect_Jets; } } } } } // Loop over jets finding the one with the minimum R if( (mixJets == 1) && (ISR_match_index >= 0) && (ISR_match_index < NumJets) ) { NumEvents1ISRJet++; Double_t Delta_PT = TMath::Abs(vect_Jeto->Pt() - vect_ISR_particle->Pt()); Double_t Delta_Eta = TMath::Abs(vect_Jeto->Eta() - vect_ISR_particle->Eta()); Double_t Delta_Phi = vect_Jeto->DeltaPhi(*vect_ISR_particle); Double_t Delta_y = TMath::Abs(vect_Jeto->Rapidity() - vect_ISR_particle->Rapidity()); if ( (Delta_PT > Cut_matching_DPT) || (Delta_Eta > Cut_matching_DEta) || (Delta_Phi > Cut_matching_DPhi ) || (Delta_y > Cut_matching_Dy) ) { ISR_jets[entry] = -1; } else { NumMatches++; ISR_jets[entry] = ISR_match_index; } } if (ISR_jets[entry] >= NumJets){ cout << "Error en el matching. Terminating program" << endl; return 1; } } cout<<"\tprogress = 100%\t"; cout<< "Time :"<< (clock()-initialTime)/double_t(CLOCKS_PER_SEC)<<"s"<<endl; /* * Writing results */ cout << "\nWriting files" << endl; string fileName_str = head_folder_results + matching_name; Char_t * fileName = (Char_t *) fileName_str.c_str(); if (argc > 2) cout << "\t Writing the binary file...:" << fileName << endl; else cout<<"\t Writing the default binary file...:" << fileName << endl; ofstream ofs(fileName,ios::out|ios::binary); if (!ofs){ cout << "Problemas al escribir el archivo" << endl; } else{ for(Int_t j = 0; j<numberOfEntries; j++){ ofs.write((Char_t *) (ISR_jets+j),sizeof(Int_t)); } } ofs.close(); cout << "\nSome overal results: " << endl; cout << "\tNumber of events with a single ISR jet = " << NumEvents1ISRJet <<endl; cout << "\tNumber of matches = " << NumMatches << endl; cout << endl; return 0; }
[ "andrespipe150@gmail.com" ]
andrespipe150@gmail.com
0202b99598ae678f6f5c0c7a5690a60d80ae032b
c488683f418bfc545fce509d215e08c6f483ee79
/libjingle/talk/examples/call/callclient.h
af27f340cfcb1b1da304ede661a8b211784ccef7
[ "BSD-3-Clause" ]
permissive
Ri0n/rion-pg
6ef7b49cd5e7e2332acdb90de2d4f481bd5da8b3
bcd1eacf94cc97bffb8de8ebca8236bb1a0f60f0
refs/heads/master
2021-01-21T04:27:28.977362
2018-11-12T22:00:02
2018-11-12T22:00:02
32,313,492
2
0
null
null
null
null
UTF-8
C++
false
false
5,969
h
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TALK_EXAMPLES_CALL_CALLCLIENT_H_ #define TALK_EXAMPLES_CALL_CALLCLIENT_H_ #include <map> #include <string> #include <vector> #include "talk/p2p/base/session.h" #include "talk/session/phone/mediachannel.h" #include "talk/xmpp/xmppclient.h" #include "talk/examples/call/status.h" #include "talk/examples/call/console.h" #ifdef USE_TALK_SOUND #include "talk/sound/soundsystemfactory.h" #endif namespace buzz { class PresencePushTask; class PresenceOutTask; class MucInviteRecvTask; class MucInviteSendTask; class FriendInviteSendTask; class VoicemailJidRequester; class DiscoInfoQueryTask; class Muc; class Status; class MucStatus; struct AvailableMediaEntry; } namespace talk_base { class Thread; class NetworkManager; } namespace cricket { class PortAllocator; class MediaEngine; class MediaSessionClient; class Receiver; class Call; class SessionManagerTask; } struct RosterItem { buzz::Jid jid; buzz::Status::Show show; std::string status; }; class NullRenderer; class CallClient: public sigslot::has_slots<> { public: explicit CallClient(buzz::XmppClient* xmpp_client); ~CallClient(); cricket::MediaSessionClient* media_client() const { return media_client_; } void SetMediaEngine(cricket::MediaEngine* media_engine) { media_engine_ = media_engine; } void SetAutoAccept(bool auto_accept) { auto_accept_ = auto_accept; } void SetPmucDomain(const std::string &pmuc_domain) { pmuc_domain_ = pmuc_domain; } void SetConsole(Console *console) { console_ = console; } void ParseLine(const std::string &str); void InviteFriend(const std::string& user); void JoinMuc(const std::string& room); void InviteToMuc(const std::string& user, const std::string& room); void LeaveMuc(const std::string& room); void SetPortAllocatorFlags(uint32 flags) { portallocator_flags_ = flags; } typedef std::map<buzz::Jid, buzz::Muc*> MucMap; const MucMap& mucs() const { return mucs_; } private: void AddStream(uint32 audio_src_id, uint32 video_src_id); void RemoveStream(uint32 audio_src_id, uint32 video_src_id); void OnStateChange(buzz::XmppEngine::State state); void InitPhone(); void InitPresence(); void RefreshStatus(); void OnRequestSignaling(); void OnCallCreate(cricket::Call* call); void OnCallDestroy(cricket::Call* call); void OnSessionState(cricket::Call* call, cricket::BaseSession* session, cricket::BaseSession::State state); void OnStatusUpdate(const buzz::Status& status); void OnMucInviteReceived(const buzz::Jid& inviter, const buzz::Jid& room, const std::vector<buzz::AvailableMediaEntry>& avail); void OnMucJoined(const buzz::Jid& endpoint); void OnMucStatusUpdate(const buzz::Jid& jid, const buzz::MucStatus& status); void OnMucLeft(const buzz::Jid& endpoint, int error); void OnDevicesChange(); void OnFoundVoicemailJid(const buzz::Jid& to, const buzz::Jid& voicemail); void OnVoicemailJidError(const buzz::Jid& to); static const std::string strerror(buzz::XmppEngine::Error err); void PrintRoster(); void MakeCallTo(const std::string& name, bool video); void PlaceCall(const buzz::Jid& jid, bool is_muc, bool video); void CallVoicemail(const std::string& name); void Accept(); void Reject(); void Quit(); void GetDevices(); void PrintDevices(const std::vector<std::string>& names); void SetVolume(const std::string& level); typedef std::map<std::string, RosterItem> RosterMap; Console *console_; buzz::XmppClient* xmpp_client_; talk_base::Thread* worker_thread_; talk_base::NetworkManager* network_manager_; cricket::PortAllocator* port_allocator_; cricket::SessionManager* session_manager_; cricket::SessionManagerTask* session_manager_task_; cricket::MediaEngine* media_engine_; cricket::MediaSessionClient* media_client_; MucMap mucs_; cricket::Call* call_; cricket::BaseSession *session_; bool incoming_call_; bool auto_accept_; std::string pmuc_domain_; NullRenderer* local_renderer_; NullRenderer* remote_renderer_; buzz::Status my_status_; buzz::PresencePushTask* presence_push_; buzz::PresenceOutTask* presence_out_; buzz::MucInviteRecvTask* muc_invite_recv_; buzz::MucInviteSendTask* muc_invite_send_; buzz::FriendInviteSendTask* friend_invite_send_; RosterMap* roster_; uint32 portallocator_flags_; #ifdef USE_TALK_SOUND cricket::SoundSystemFactory* sound_system_factory_; #endif }; #endif // TALK_EXAMPLES_CALL_CALLCLIENT_H_
[ "rion4ik@gmail.com" ]
rion4ik@gmail.com
379e81cc2ee2b4152c2cbd2b796464603c870cec
de30ec975aa47031c5c9c6ee0ab49931a99e5f22
/sources/GeneSplicer.cpp
5ec8fdb0e99fbf047233bfdef4dc323c743ab2da
[]
no_license
Nadavkeysar/Ariel_CPP_Ex4b
38e6ff914e67433db04bd1a13fa8ddf90b462af3
ffd29c3b7ea698ef368ebbdc8d17e147c5822ad1
refs/heads/main
2023-05-01T21:50:29.118360
2021-05-18T12:19:31
2021-05-18T12:19:31
364,899,290
0
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
#include "GeneSplicer.hpp" using namespace pandemic; GeneSplicer &GeneSplicer::discover_cure(pandemic::Color color) { bool researches = this->board.get_board()[this->cityNow].get_Station(); if (!researches) { string exp = "you don't in research station"; throw exp; } bool cure = this->board.get_madicines(color); int counter_cards = this->cards.size(); if (counter_cards >= CARDS_CURE) { if (!cure) { counter_cards = CARDS_CURE; for (auto itr = this->cards.begin(); itr != this->cards.end() && counter_cards > 0;) { itr = this->cards.erase(itr); counter_cards--; } this->board.set_madicines(color, true); } } else { string exp = "you don't have enough cards"; throw exp; } return *this; } string GeneSplicer::role() { return this->vox; }
[ "noreply@github.com" ]
noreply@github.com
06ac1355dac7d51417282453161479c8c7457712
809a9c17b1f5c858c4339cd051194fe20c6d32ed
/1.16.cpp
29e870c375fb5d70b510aab56f9f3e36695faebf
[]
no_license
SobczynskiEryk/Informatyka
39f4edda45cf487e23549d5b0579aa64edc7c850
8d1a268eaf86de8f2e6ca5e1c687ddcfaa9d7371
refs/heads/master
2021-06-10T06:05:36.865280
2019-12-10T13:56:14
2019-12-10T13:56:14
107,578,112
0
0
null
2017-12-07T22:18:02
2017-10-19T17:30:54
C++
UTF-8
C++
false
false
336
cpp
#include <iostream> #include <math.h> using namespace std; int x; int main() { cout<<"wypisz x:"; cin>>x; if (x<1) cout<<"f(x)="<<x*2; else if (x==1) cout<<"f(x)="<<-10; else if (x==3) cout<<"f(x)="<<(pow((x-1),4)); else if (x==6) cout<<"f(x)="<<(sqrt(x-4)); else cout<<"f(x)="<<0; return 0; }
[ "noreply@github.com" ]
noreply@github.com
8ad3c6b07234f8c8defcf505f9099c46e46d5872
73e89812a3e4f979641c7d8765b46ed0226e3dd9
/Test.Urasandesu.Swathe/Test/Urasandesu/Swathe/Metadata/BaseILGeneratorTest.cpp
b507c4afdf929a98d8ccf9a8f1d8601054134d97
[]
no_license
urasandesu/Swathe
c601244e7339c2d6fe5686a0ee2ca44732007d89
e086ede891a64d991f1f738b00eb158b44537d06
refs/heads/master
2021-01-19T00:52:31.845284
2017-03-17T11:32:51
2017-03-17T11:32:51
6,515,991
3
1
null
null
null
null
UTF-8
C++
false
false
10,757
cpp
/* * File: BaseILGeneratorTest.cpp * * Author: Akira Sugiura (urasandesu@gmail.com) * * * Copyright (c) 2014 Akira Sugiura * * This software is MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "stdafx.h" #ifndef URASANDESU_CPPANONYM_UTILITIES_ISANYT_H #include <Urasandesu/CppAnonym/Utilities/IsAnyT.h> #endif #ifndef URASANDESU_CPPANONYM_METADATA_BASEMETHODBODYWRITER_HPP #include <Urasandesu/CppAnonym/Metadata/BaseMethodBodyWriter.hpp> #endif #ifndef URASANDESU_CPPANONYM_METADATA_INTERFACES_METHODMETADATALABEL_HPP #include <Urasandesu/CppAnonym/Metadata/Interfaces/MethodMetadataLabel.hpp> #endif #ifndef URASANDESU_CPPANONYM_CPPANONYMEXCEPTION_H #include <Urasandesu/CppAnonym/CppAnonymException.h> #endif #ifndef URASANDESU_CPPANONYM_METADATA_OPCODES_H #include <Urasandesu/CppAnonym/Metadata/OpCodes.h> #endif #ifndef URASANDESU_CPPANONYM_CPPANONYMNOTIMPLEMENTEDEXCEPTION_H #include <Urasandesu/CppAnonym/CppAnonymNotImplementedException.h> #endif // Forward Declaration namespace MockC17C4C45 { typedef std::vector<boost::any> AnyVector; class ATL_NO_VTABLE MockTypeFindable; class MockMetadataDispenser; class MockAssemblyNameMetadata; class MockTypeNameMetadata; class MockMethodMetadata; class MockMethodNameMetadata; } // namespace MockC17C4C45 { namespace MockC17C4C45 { class ATL_NO_VTABLE MockTypeFindable : boost::noncopyable { public: template<class T> T const &Map() const { using namespace boost; using namespace Urasandesu::CppAnonym::Utilities; AnyVector::iterator result; result = std::find_if(m_typePtrs.begin(), m_typePtrs.end(), IsAnyT<shared_ptr<T> >()); _ASSERTE(result != m_typePtrs.end()); return any_cast<shared_ptr<T> >(*result).get(); } mutable AnyVector m_typePtrs; }; class MockMetadataDispenser : public MockTypeFindable { public: typedef MockAssemblyNameMetadata assembly_name_metadata_type; MockMetadataDispenser() { } assembly_name_metadata_type *NewAssemblyName(std::wstring const &name) const { using boost::shared_ptr; using boost::make_shared; shared_ptr<assembly_name_metadata_type> pAsmNameMeta(make_shared<assembly_name_metadata_type>()); m_asmNamePtrs.push_back(pAsmNameMeta); return pAsmNameMeta.get(); } mutable AnyVector m_asmNamePtrs; }; class MockAssemblyNameMetadata : public MockTypeFindable { public: typedef MockTypeNameMetadata type_name_metadata_type; MockAssemblyNameMetadata() { } type_name_metadata_type *NewTypeName(std::wstring const &name, Urasandesu::CppAnonym::Metadata::TypeKinds const &kind) const { using boost::shared_ptr; using boost::make_shared; shared_ptr<type_name_metadata_type> pTypeNameMeta(make_shared<type_name_metadata_type>()); m_typeNamePtrs.push_back(pTypeNameMeta); return pTypeNameMeta.get(); } mutable AnyVector m_typeNamePtrs; }; class MockTypeNameMetadata : public MockTypeFindable { public: typedef MockTypeNameMetadata this_type; typedef MockMethodNameMetadata method_name_metadata_type; MockTypeNameMetadata() { } method_name_metadata_type *NewMethodName(std::wstring const &name, Urasandesu::CppAnonym::Metadata::CallingConventions const &callingConvention, this_type const &retTypeName, std::vector<this_type const *> const &paramTypeNames) const { using boost::shared_ptr; using boost::make_shared; shared_ptr<method_name_metadata_type> pMethodNameMeta(make_shared<method_name_metadata_type>()); m_methodNamePtrs.push_back(pMethodNameMeta); return pMethodNameMeta.get(); } mutable AnyVector m_methodNamePtrs; }; class MockMethodMetadata : public MockTypeFindable { public: MockMethodMetadata() { } }; class MockMethodNameMetadata : public MockTypeFindable { public: MockMethodNameMetadata() { } }; } // namespace MockC17C4C45 { // Test.Urasandesu.CppAnonym.exe --gtest_filter=Urasandesu_CppAnonym_Metadata_BaseMethodBodyWriterTest.* namespace { CPPANONYM_TEST(Urasandesu_CppAnonym_Metadata_BaseMethodBodyWriterTest, OpCodesTest_01) { using namespace Urasandesu::CppAnonym; using namespace Urasandesu::CppAnonym::Metadata; typedef OpCodes OpCodes; ASSERT_STREQ(L"CEE_NOP,nop,Pop0,Push0,InlineNone,IPrimitive,1,0xFF,0x00,NEXT", OpCodes::Nop.CStr()); ASSERT_EQ(OpCodeTypes::CEE_NOP, OpCodes::Nop.GetType().Value()); ASSERT_STREQ(L"nop", OpCodes::Nop.GetName().c_str()); ASSERT_EQ(StackBehaviourTypes::SBT_POP0, OpCodes::Nop.GetBehaviour0().GetType().Value()); ASSERT_EQ(StackBehaviourTypes::SBT_PUSH0, OpCodes::Nop.GetBehaviour1().GetType().Value()); ASSERT_EQ(OperandParamTypes::OPT_INLINE_NONE, OpCodes::Nop.GetOperandParam().GetType().Value()); ASSERT_EQ(OpCodeKindTypes::OKT_I_PRIMITIVE, OpCodes::Nop.GetOpCodeKind().GetType().Value()); ASSERT_EQ(1, OpCodes::Nop.GetLength()); ASSERT_EQ(0xFF, OpCodes::Nop.GetByte1()); ASSERT_EQ(0x00, OpCodes::Nop.GetByte2()); ASSERT_EQ(ControlFlowTypes::CFT_NEXT, OpCodes::Nop.GetControlFlow().GetType().Value()); } CPPANONYM_TEST(Urasandesu_CppAnonym_Metadata_BaseMethodBodyWriterTest, StackBehavioursTest_01) { using namespace Urasandesu::CppAnonym; using namespace Urasandesu::CppAnonym::Metadata; StackBehaviour expected = StackBehaviours::PopRef(); expected += StackBehaviours::PopI(); expected += StackBehaviours::PopRef(); typedef OpCodes OpCodes; ASSERT_STREQ(L"CEE_STELEM_REF,stelem.ref,PopRef+PopI+PopRef" L",Push0,InlineNone,IObjModel,1,0xFF,0xA2,NEXT", OpCodes::Stelem_Ref.CStr()); ASSERT_TRUE(expected == OpCodes::Stelem_Ref.GetBehaviour0()); } CPPANONYM_TEST(Urasandesu_CppAnonym_Metadata_BaseMethodBodyWriterTest, StackBehavioursTest_02) { using namespace Urasandesu::CppAnonym; using namespace Urasandesu::CppAnonym::Metadata; StackBehaviour expected = StackBehaviours::PopRef(); expected += StackBehaviours::PopI(); typedef OpCodes OpCodes; ASSERT_TRUE(expected != OpCodes::Stfld.GetBehaviour0()); } CPPANONYM_TEST(Urasandesu_CppAnonym_Metadata_BaseMethodBodyWriterTest, EmitWriteLineTest_01) { namespace mpl = boost::mpl; using boost::any_cast; using boost::shared_ptr; using boost::make_shared; using namespace MockC17C4C45; using namespace Urasandesu::CppAnonym; using namespace Urasandesu::CppAnonym::Metadata; struct TestApiHolder { typedef mpl::map< mpl::pair<Interfaces::MetadataDispenserLabel, MockMetadataDispenser>, mpl::pair<Interfaces::AssemblyNameMetadataLabel, MockAssemblyNameMetadata>, mpl::pair<Interfaces::TypeNameMetadataLabel, MockTypeNameMetadata>, mpl::pair<Interfaces::MethodNameMetadataLabel, MockMethodNameMetadata>, mpl::pair<Interfaces::MethodMetadataLabel, MockMethodMetadata>, mpl::pair<IMetaDataImport2, IMetaDataImport2> > api_cartridges; }; typedef MockMetadataDispenser MetadataDispenser; typedef MockMethodMetadata MethodMetadata; typedef MockMethodNameMetadata MethodNameMetadata; typedef BaseMethodBodyWriter<TestApiHolder> MethodBodyWriter; shared_ptr<MetadataDispenser> pMetaDisp(make_shared<MetadataDispenser>()); shared_ptr<MethodMetadata> pMethodMeta(make_shared<MethodMetadata>()); pMethodMeta->m_typePtrs.push_back(pMetaDisp); shared_ptr<MethodBodyWriter> pGen(make_shared<MethodBodyWriter>()); pGen->Init(*pMethodMeta); pGen->EmitWriteLine(L"Hello, world!!"); pGen->Emit(OpCodes::Ret); std::vector<Instruction const *> const &insts = pGen->GetInstructions(); ASSERT_EQ(3, insts.size()); { OpCode const &op = insts[0]->GetOpCode(); std::wstring const &s = any_cast<std::wstring const &>(insts[0]->GetOprand()); ASSERT_EQ(&OpCodes::Ldstr, &op); ASSERT_STREQ(L"Hello, world!!", s.c_str()); } { OpCode const &op = insts[1]->GetOpCode(); MethodNameMetadata const *pMethodNameMeta = any_cast<MethodNameMetadata const *>(insts[1]->GetOprand()); ASSERT_EQ(&OpCodes::Call, &op); ASSERT_TRUE(pMethodNameMeta != NULL); } { OpCode const &op = insts[2]->GetOpCode(); ASSERT_EQ(&OpCodes::Ret, &op); } } }
[ "urasandesu@gmail.com" ]
urasandesu@gmail.com
d74eddd38770ab7b5f03afb1a5977344ed830e20
70708b2b3d5263f8428c490bbef54e4fcb8c1ef2
/include/lazy_matrix.h
a76eeb55b4ad58c7f952c2eefd81b86a6f360b7c
[ "Apache-2.0" ]
permissive
ssaahhaajj/uBLAS-Programming-Competency-Test
a3ed1c60872b3247c0b5500c5e568042bb8c712d
29d5a553120bee4700cc6f3f89257a4003924b0f
refs/heads/master
2021-04-02T17:08:50.592052
2019-03-13T18:32:15
2019-03-13T18:32:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,211
h
#pragma once #include <cassert> #include <iostream> #include <typeinfo> #include <vector> using sz_t = std::size_t; template <typename T> using TDVec = std::vector<std::vector<T>>; template <typename T> using List = std::initializer_list<std::initializer_list<T>>; namespace policy { /** * @brief policy that take row as first priority */ class row_major { public: template <typename R1> decltype(auto) operator()(const sz_t &i, const sz_t &j, const R1 &a) const { return a._array[i * a.size_y + j]; } template <typename R1> decltype(auto) operator()(const sz_t &i, const sz_t &j, R1 &a) { return a._array[i * a.size_y + j]; } }; /** * @brief policy that take column as first priority */ class column_major { public: template <typename R1> decltype(auto) operator()(const sz_t &i, const sz_t &j, const R1 &a) const { return a._array[j * a.size_x + i]; } template <typename R1> decltype(auto) operator()(const sz_t &i, const sz_t &j, R1 &a) { return a._array[j * a.size_x + i]; } }; }; // namespace policy /** * @brief Functor for adding corresponding position */ struct _add { template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &i, const sz_t &j) const { return op1(i, j) + op2(i, j); } }; /** * @brief Functor for subtracting corresponding position */ struct _sub { template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &i, const sz_t &j) const { return op1(i, j) - op2(i, j); } }; /** * @brief Functor for dividing corresponding position */ struct _ediv { template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &i, const sz_t &j) const { return op1(i, j) / op2(i, j); } }; /** * @brief Functor for diving with a scalar */ struct _sdiv { template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &i, const sz_t &j) const { return op1(i, j) / op2; } }; /** * @brief Functor for multiplying corresponding position */ struct _emul { template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &i, const sz_t &j) const { return op1(i, j) * op2(i, j); } }; /** * @brief Functor for multiplying with scalar */ struct _smul { template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &i, const sz_t &j) const { return op1(i, j) * op2; } }; /** * @brief Functor for getting (i,j)th element of Standard Matrix-Matrix * multiplication */ struct _std_mul { template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &i, const sz_t &j) const { return (_std_mul::operator()(op1, op2, op2.shape().first - 1, i, j)); } template <typename R1, typename R2> decltype(auto) operator()(const R1 &op1, const R2 &op2, const sz_t &k, const sz_t &i, const sz_t &j) const { if (k == 0) { #pragma omp parallel single { #pragma omp task decltype(auto) temp1 = op1(i, k); #pragma omp task decltype(auto) temp2 = op2(k, j); #pragma omp taskwait return temp1 * temp2; } } else { #pragma omp parallel single { #pragma omp task decltype(auto) temp1 = op1(i, k); #pragma omp task decltype(auto) temp2 = op2(k, j); #pragma omp task decltype(auto) temp3 = _std_mul::operator()(op1, op2, k - 1, i, j); #pragma omp taskwait return temp1 * temp2 + temp3; } } } }; /** * @brief Class for expression. * * @tparam R1 First Parameter * @tparam R2 Fecond Parameter * @tparam Op Functor for atithematic operations */ template <typename R1, typename R2, typename Op> class expr { private: const R1 &op1; const R2 &op2; const sz_t size_x; const sz_t size_y; Op op; public: /** * @brief Constructs the object. * * @param[in] a First Operand * @param[in] b Second Operand * @param[in] f Functor for Operator */ expr(const R1 &a, const R2 &b, Op f) : op1(a), op2(b), size_x(a.shape().first), size_y(b.shape().second), op(f) {} /** * @brief Gives the dimensions of the resultant expression * * @return return a pair whose first value is the number of rows and * the second value is the number of columns */ decltype(auto) shape() const { return std::make_pair(size_x, size_y); } /** * @brief Oveloading operator << to use std:: cout */ friend std::ostream &operator<<(std::ostream &out, expr<R1, R2, Op> &other) { sz_t size_x = other.shape().first; sz_t size_y = other.shape().second; #pragma omp parallel for for (sz_t i = 0; i < size_x; i++) { for (sz_t j = 0; j < size_y; j++) { out << other(i, j) << ' '; } out << std::endl; } return out; } /** * Operator + Overloading for Standard Matrix Addition */ template <typename F> decltype(auto) operator+(const F &other) { assert(shape() == other.shape()); return expr<expr<R1, R2, Op>, F, _add>(*this, other, _add()); } /** * Operator - Overloading for Standard Matrix Subtraction */ template <typename F> decltype(auto) operator-(const F &other) { assert(shape() == other.shape()); return expr<expr<R1, R2, Op>, F, _sub>(*this, other, _sub()); } /** * Operator / Overloading for Element-Wise Division */ template <typename F> decltype(auto) operator/(const F &other) { assert(shape() == other.shape()); return expr<expr<R1, R2, Op>, F, _ediv>(*this, other, _ediv()); } /** * Operator * Overloading for Element-Wise Multiplication */ template <typename F> decltype(auto) operator*(const F &other) { assert(shape() == other.shape()); return expr<expr<R1, R2, Op>, F, _emul>(*this, other, _emul()); } /** * Operator % Overloading for Standard Matrix Multiplication */ template <typename F> decltype(auto) operator%(const F &other) { assert(size_y == other.shape().second); return expr<expr<R1, R2, Op>, F, _std_mul>(*this, other, _std_mul()); } /** * Operator () overloading for gitting the (i,j)th element of the * expression */ decltype(auto) operator()(const sz_t &i, const sz_t &j) const { return op(op1, op2, i, j); } }; /** * @brief Class for lazy matrix. * * @tparam T Data type of the matrix * @tparam policy User case assign how data will be accessed takes * value policy:: row_major or policy::column_major */ template <typename T, typename ploy = policy::row_major> class lazy_matrix { private: std::vector<T> _array; const sz_t size_x; const sz_t size_y; friend ploy; ploy pol; public: /** * @brief Constructs the object. */ lazy_matrix() : size_x(0), size_y(0) {} /** * @brief Constructs the object. * * @param[in] n Number of rows in the matrix * @param[in] m Number of columns in the matrix */ lazy_matrix(const std::size_t &n, const std::size_t &m) : _array(n * m), size_x(n), size_y(m) {} /** * @brief Constructs the object. * * @param[in] n Number of rows in the matrix * @param[in] m Number of columns in the matrix * @param[in] val The initial value */ lazy_matrix(const std::size_t &n, const std::size_t &m, const T &val) : _array(n * m, val), size_x(n), size_y(m) {} /** * @brief Vector initialization * * @param[in] vec 2D Vector input */ lazy_matrix(const TDVec<T> &vec) : size_x(vec.size()), size_y((*vec.begin()).size()) { if (typeid(ploy) == typeid(policy::row_major)) { for (auto &it : vec) { _array.insert(_array.end(), it.begin(), it.end()); } } else { for (sz_t j = 0; j < size_y; j++) { for (sz_t i = 0; i < size_x; i++) { _array.push_back(vec[i][j]); } } } } /** * @brief Initialization with 2D list * * @param[in] l 2D Initializer_list input */ lazy_matrix(const List<T> &l) : size_x(l.size()), size_y((*l.begin()).size()) { if (typeid(ploy) == typeid(policy::row_major)) { for (auto &it : l) { _array.insert(_array.end(), it.begin(), it.end()); } } else { for (sz_t j = 0; j < size_y; j++) { for (sz_t i = 0; i < size_x; i++) { _array.push_back(*((*(l.begin() + i)).begin() + j)); } } } } /** * @brief Initialization with an expression * * @param[in] exp The expression initializer * * @tparam R1 Left operand of the expression * @tparam R2 Right operand of the expression * @tparam R3 Functor for performing arithematic operation */ template <typename R1, typename R2, typename R3> lazy_matrix(const expr<R1, R2, R3> &exp) : size_x(exp.shape().first), size_y(exp.shape().second) { if (typeid(ploy) == typeid(policy::row_major)) { for (sz_t i = 0; i < size_x; i++) { for (sz_t j = 0; j < size_y; j++) { _array.push_back(exp(i, j)); } } } else { for (sz_t j = 0; j < size_y; j++) { for (sz_t i = 0; i < size_x; i++) { _array.push_back(exp(i, j)); } } } } /** * @brief Gives the dimensions of the matrix */ decltype(auto) shape() const { return std::make_pair(size_x, size_y); } /** * @brief function for getting processed data i.e. member _array which is * processed under row_major or column_major; */ decltype(auto) pcd_data() const { return _array; } /** * Operator () Overloading for getting the (i,j)th element */ inline const T operator()(const std::size_t i, const std::size_t j) const { return pol(i, j, *this); } inline T &operator()(const std::size_t i, const std::size_t j) { return pol(i, j, *this); } /** * @brief Oveloading operator << to use std:: cout */ friend std::ostream &operator<<(std::ostream &out, lazy_matrix<T, ploy> &other) { sz_t size_x = other.shape().first; sz_t size_y = other.shape().second; #pragma omp parallel for for (sz_t i = 0; i < size_x; i++) { for (sz_t j = 0; j < size_y; j++) { out << other(i, j) << ' '; } out << std::endl; } return out; } /** * @brief Overloading operator = for a assignment of lazy matrix * * @param[in] other reference to the matrix or expression which is to be * assigned * * @tparam R1 expression type or matrix type */ template <typename R1> lazy_matrix operator=(const R1 &other) { assert(shape() == other.shape()); lazy_matrix<T, ploy> temp(size_x, size_y); #pragma omp parallel for for (sz_t i = 0; i < size_x; i++) { for (sz_t j = 0; j < size_y; j++) { temp(i, j) = other(i, j); } } #pragma omp parallel for for (sz_t i = 0; i < size_x; i++) { for (sz_t j = 0; j < size_y; j++) { (*this)(i, j) = temp(i, j); } } return *this; } /** * @brief Overloading operator == for a comparing equality with other * matrix * * @param[in] other reference to the matrix or expression which is to be * compared * * @tparam R2 matrix or expression * * @return true if eaual else false */ template <typename R1> bool operator==(const R1 &other) { if (shape() != other.shape() && typeid(T) != typeid(other(0, 0))) { return false; } for (sz_t i = 0; i < size_x; i++) { for (sz_t j = 0; j < size_y; j++) { if ((*this)(i, j) != other(i, j)) { return false; } } } return true; } /** * @brief Operator + Overloading for Standard Matrix Addition * * @param[in] other reference to the matrix or expression which is to be * added * * @tparam R1 matrix or expression */ template <typename R1> decltype(auto) operator+(const R1 &other) { assert(shape() == other.shape()); return expr<lazy_matrix<T, ploy>, R1, _add>(*this, other, _add()); } /** * @brief assignment after adding */ template <typename R1> void operator+=(const R1 &other) { *this = *this + other; } /** * @brief Operator - Overloading for Standard Matrix Subtraction * * @param[in] other reference to the matrix or expression which is to be * subtracted * * @tparam R1 matrix or expression */ template <typename R1> decltype(auto) operator-(const R1 &other) { assert(shape() == other.shape()); return expr<lazy_matrix<T, ploy>, R1, _sub>(*this, other, _sub()); } /** * @brief assignment after subtracting */ template <typename R1> void operator-=(const R1 &other) { *this = *this - other; } /** * @brief Operator / Overloading for Element-Wise Division * * @param[in] other reference to the matrix or expression which is to be * divided * * @tparam R1 matrix or expression */ template <typename R1> decltype(auto) operator/(const R1 &other) { assert(shape() == other.shape()); return expr<lazy_matrix<T, ploy>, R1, _ediv>(*this, other, _ediv()); } /** * @brief assignment after element-wise division */ template <typename R1> void operator/=(const R1 &other) { *this = *this / other; } /** * @brief Operator * Overloading for Element-Wise Multiplication * * @param[in] other reference to the matrix or expression which is to be * multiplied * * @tparam R1 matrix or expression */ template <typename R1> decltype(auto) operator*(const R1 &other) { assert(shape() == other.shape()); return expr<lazy_matrix<T, ploy>, R1, _emul>(*this, other, _emul()); } /** * @brief assignment after element-wise multiplication */ template <typename R1> void operator*=(const R1 &other) { auto temp = (*this) * other; *this = temp; } /** * @brief Operator -%Overloading for Standard Matrix Multiplication * * @param[in] other reference to the matrix or expression which is to be * multiplied * * @tparam R1 matrix or expression */ template <typename R1> decltype(auto) operator%(const R1 &other) { assert(shape().second == other.shape().first); return expr<lazy_matrix<T, ploy>, R1, _std_mul>(*this, other, _std_mul()); } /** * @brief assignment after standard matrix multiplication */ template <typename R1> void operator%=(const R1 &other) { auto temp = (*this) % other; *this = temp; } };
[ "navneetsurana.ase1@gmail.com" ]
navneetsurana.ase1@gmail.com
226526a2111efadb0d69a5fb841341b5cb6eb23c
1ea05e2d340580c8239575d1d4ae269593487c49
/Project 4/main.cpp
9a62c058be58b21431c031e1773b8cc066b4f09f
[]
no_license
helengracehuang/Data-Structures-and-Object-Oriented-Design
fb6eec323be5267b21665fcf45728104676caedf
8c9618e8da5dd277019ca4668d989bc869f080b6
refs/heads/master
2020-05-05T06:33:05.314027
2019-04-06T06:03:37
2019-04-06T06:03:37
179,792,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,523
cpp
#include "provided.h" #include <iostream> #include <string> #include <vector> #include <cstring> #include <cctype> #include <random> #include <algorithm> #include <numeric> using namespace std; const string WORDLIST_FILE = "wordlist.txt"; string encrypt(string plaintext) { // Generate a to z char plaintextAlphabet[26+1]; iota(plaintextAlphabet, plaintextAlphabet+26, 'a'); plaintextAlphabet[26] = '\0'; // Generate permutation string ciphertextAlphabet(plaintextAlphabet); default_random_engine e((random_device()())); shuffle(ciphertextAlphabet.begin(), ciphertextAlphabet.end(), e); // Run translator (opposite to the intended direction) Translator t; t.pushMapping(plaintextAlphabet, ciphertextAlphabet); return t.getTranslation(plaintext); } bool decrypt(string ciphertext) { Decrypter d; if ( ! d.load(WORDLIST_FILE)) { cout << "Unable to load word list file " << WORDLIST_FILE << endl; return false; } for (const auto& s : d.crack(ciphertext)) cout << s << endl; return true; } int main(int argc, char* argv[]) { if (argc == 3 && argv[1][0] == '-') { switch (tolower(argv[1][1])) { case 'e': cout << encrypt(argv[2]) << endl; return 0; case 'd': if (decrypt(argv[2])) { cout << argv[2] << endl; return 0; } return 1; } } cout << "Usage to encrypt: " << argv[0] << " -e \"Your message here.\"" << endl; cout << "Usage to decrypt: " << argv[0] << " -d \"Uwey tirrboi miyi.\"" << endl; return 1; }
[ "noreply@github.com" ]
noreply@github.com
99bf3be3883c7dc47a747edf1268e488240bc44e
b97524c7ce5e9464f870c1b07f178931a14e1807
/src/Editors/Grid.h
148cf67f7991dc43704f3a663e8943c1057625fc
[]
no_license
corea1314/delirium-wars
0ee939021ade5818818ba211ef6615adb009153b
69de79f1dd76dd60324bf4154138a7dc4789547c
refs/heads/master
2021-01-10T13:18:49.179388
2013-03-17T06:29:41
2013-03-17T06:29:41
36,844,912
0
0
null
null
null
null
UTF-8
C++
false
false
597
h
#pragma once #include "gfx.h" #include "Math/Vector2.h" #define MAX_GRID_SIZE 512 class Grid { public: Grid(); void IncreaseGridSize(); void DecreaseGridSize(); void UpdateGrid(); void ToggleSnap(); Vector2 Snap( const Vector2& inPos ); void Render(); int GetGridSize() { return mSize; } bool GetSnap() { return mIsSnapping; } void SetScale( float inScale ) { mScale = inScale; } private: int mSize; Vertex mVertexBuffer[(MAX_GRID_SIZE+1)*(MAX_GRID_SIZE+1)]; int mVertexBufferSize; bool mIsSnapping; float mScale; float mGridDelta; };
[ "jimmy.beaubien@8ee7db41-403f-03ee-0b30-02c333d15193" ]
jimmy.beaubien@8ee7db41-403f-03ee-0b30-02c333d15193
236e2671f57182c282d7add643aa50159806efc5
cdd45cad8525c94b8beb1b3e75c76b3c870ab084
/chapter1/jollo.cpp
29493a331070dc7b247eaf216bce947a50474c18
[]
no_license
kyro1202/Competitive-Programming-3
4fcf4e5516c83ce7dbfcb9084a6fa8e23b7d9dfe
1e1e784fac3f3db9117ebabca0486b0edffe149d
refs/heads/master
2021-03-22T00:16:20.365660
2018-06-06T05:02:07
2018-06-06T05:02:07
101,572,720
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
cpp
#include <bits/stdc++.h> using namespace std; int main() { while(true) { int g[3],b[2]; cin >> g[0] >> g[1] >> g[2] >> b[0] >> b[1]; if( g[0] + g[1] + g[2] + b[0] + b[1] == 0) return 0; bool deck[53]; memset(deck,1,53); for(int i = 0 ; i < 3 ; i++) { deck[g[i]] = false; if( i < 2) deck[b[i]] = false; } sort(g,g+3); sort(b,b+2); int b3 = 53; if( b[0] > g[2] ) { for(int i = 1 ; i < 53 && i < b3 ; i++ ) { if(deck[i]) b3 = i; } } if( b[1] > g[2] ) { for(int i = g[2] + 1 ; i < 53 && i < b3 ; i++ ) { if(deck[i]) b3 = i; } } if(b[0] > g[1]) { for(int i = g[1] + 1 ; i < 53 && i < b3 ; i++ ) { if(deck[i]) b3 = i; } } if( b3 == 53) b3 = -1; cout << b3 << endl; } }
[ "shivishiva2012@gmail.com" ]
shivishiva2012@gmail.com
76c19ed97eeaa60d79a650399a0baab91007cff0
862bc22c2491fca70087572890e7d994c0ebb45b
/array/rank_transform_of_array.cpp
450ca490b0a51aa167d189ac53bf0e32925271c0
[]
no_license
abhi2694/Data-Structures-Codes
58879bc28415d29df241bcbb4c42562c58879ba2
5cf17db4c489cf9feb82ae97d351e453a0912b04
refs/heads/master
2022-11-19T23:51:11.625306
2020-07-21T20:33:05
2020-07-21T20:33:05
263,261,126
1
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
class Solution { public: vector<int> arrayRankTransform(vector<int>& arr) { map<int,vector<int>> x; for(int i = 0;i<arr.size();i++){ x[arr[i]].push_back(i); } int i = 1; for(auto itr:x){ for(int j = 0;j<itr.second.size();j++){ arr[itr.second[j]] = i; } i++; } return arr; } };
[ "abhi2694@gmail.com" ]
abhi2694@gmail.com
3ffd16bd3eefda6227a5bedc6023236d1444c8bc
5876bbb5f18c6f9c1180481091716e1c055fb36b
/character/enemy/Merchant.h
8d04a81e1f1640b5796aceb2fa8275b4277f6103
[]
no_license
annanw4201/cc3k
08a7bd58aebf0a6126601807c39a41bfd1c59d3e
5cb74026346ef0d6c2c7051eaebe97a50b2773d9
refs/heads/master
2021-12-13T16:08:08.079755
2017-02-24T20:48:54
2017-02-24T20:48:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
451
h
#ifndef MERCHANT_H #define MERCHANT_H #include "enemy.h" class Merchant : public enemy { static bool hostile; public: /** Default constructor */ Merchant(); /** Default destructor */ ~Merchant(); void attack (Character *defender) override; void attackby (Character * attacker) override; void guardTreasure (Treasure *dh) override; bool is_hostile()const override; }; #endif // MERCHANT_H
[ "noreply@github.com" ]
noreply@github.com
57ef48f36747804067924dbeb4dac73a8f84c96a
eb28db2f1a4da8c59e3b709a304faa139e8d4fd9
/117PopulatingNextRightPointers2.h
ef070c113ec6782d0da27ffb0c0d92ebad5d8d03
[]
no_license
zhichaoh/LeetCode-2
39e74df380245d1a33f350a20163f16b094e8d11
bffafe1b7d979997ed46c5730868d4f502aaa5d7
refs/heads/master
2021-01-17T10:12:45.261077
2013-10-31T09:22:29
2013-10-31T09:22:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,070
h
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. TreeLinkNode *current_level = root, *next_level = new TreeLinkNode(0); while (current_level) { TreeLinkNode *tail = next_level; while (current_level) { if (current_level->left) { tail->next = current_level->left; tail = tail->next; } if (current_level->right) { tail->next = current_level->right; tail = tail->next; } current_level = current_level->next; } current_level = next_level->next; next_level->next = NULL; } delete next_level; } };
[ "wumalbert@gmail.com" ]
wumalbert@gmail.com
f2034272835505ee469de07ca69b5aee42942658
4f74a1d00e8253d229907d5c640e1a2eb5fd589a
/Accepted Code/UVA/10706 - Number Sequence.cpp
af3a7f07177161cb05bd9c81a6012b98b3d76505
[]
no_license
sunkuet02/problem-solving
012ea9d94412bf0400223e2af73c95bff049d0c9
49b24477acdf2bdffa9c78a907c9e06532403d40
refs/heads/master
2022-02-20T12:39:54.573009
2019-09-29T03:58:59
2019-09-29T03:58:59
63,452,400
2
0
null
null
null
null
UTF-8
C++
false
false
4,056
cpp
/* ****************************************************** * Md. Abdulla-Al-Sun * KUET, Bangladesh ****************************************************** */ #include <bits/stdc++.h> #define sc(a) scanf("%d",&a) #define rep0(i,n) for(int i = 0; i<n ;i++) #define rep(i,a,b) for(int i = a; i<=b ;i++) #define Read freopen("input.txt","r",stdin); #define Write freopen("output.txt","w",stdout); #define mem(a,val) memset(a,val, sizeof(a) ); #define LL long long int #define mxx 65536 #define sz 200005 #define MAX 109002 using namespace std; typedef pair<int, int> pii; template<class T> inline T power(T base, int p) { T f = 1 ; for(int i=1 ; i<=p ; i++) f*=base; return f; } template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } int setbit(int N,int pos) { return N = N|(1<<pos); } int resetbit(int N, int pos) { return N = N & ~(1<<pos) ; } bool checkbit(int N,int pos) { return (bool) (N & (1<<pos ) ) ; } int noofsetbits(int N) { return __builtin_popcount (N); } /*****************Seive Prime********************/ /* bool prime[MAX]; void seive() { for(int i=2;i<=MAX;i++) prime[i]=true; for(int i=4;i<=MAX;i+=2) prime[i]=false; for(int i=3;i<=sqrt(MAX);i+=2) { if(prime[i]==true) for(int j=i*i;j<MAX;j+=(2*i)) prime[j]=false; } } */ /*********************nCr**************************/ /* long long ncr[1005][1005]; void NCR() { rep0(i,1003) { ncr[i][0] = 1; } rep(i,1, 1003) { rep(j,1,1003) { ncr[i][j] = ncr[i-1][j] + ncr[i-1][j-1]; ncr[i][j] %=mod; } } } */ LL bigMod(LL N,LL M,LL MOD) { if(M==0) return 1; if((M/2)*2==M) { LL ret = bigMod(N,M/2,MOD)%MOD; return (ret*ret)%MOD; } else return ((N%MOD)*bigMod(N,M-1,MOD)%MOD)%MOD; } LL modInverseBigMod(LL a,LL m) //a*x=1(mod m) { return bigMod(a,m-2,m); } /****************************ExtendedEuclid&ModularInverse****/ pii extendedEuclid(LL a,LL b) { if(b==0) return pii(1,0); pii d = extendedEuclid(b,a%b); return pii( d.second, d.first - d.second *(a/b) ); } LL modularInverse(LL a,LL m) { pii ret = extendedEuclid(a,m); return ( (ret.first % m) + m ) %m ; } /*********************temp_Definition *************************/ /* int dx[] = {-1,0,1,0}; int dy[] = {0,1,0,-1}; // Knight Moves int dx[] = {1,1,2,2,-1,-1,-2,-2}; int dy[] = {2,-2,1,-1,2,-2,1,-1}; */ /***************************Implementation*********************/ LL digitsInANumber[100006], totalDigits[100005]; void precalculate() { LL power10 = 10; int digitsToAdd = 1; digitsInANumber[0] = 0; totalDigits[0] = 0; for(int i = 1 ; i<= 100000 ; i ++ ) { if(i>= power10) { digitsToAdd ++; power10 *= 10; } digitsInANumber[i] = digitsInANumber[i-1] + digitsToAdd; totalDigits[i] = totalDigits[i-1] + digitsInANumber[i]; } } int main() { precalculate(); //for(int i = 1; i<= 10 ; i++ ) cout << digitsInANumber[i] << " " << totalDigits[i] << endl; ; //ut << digitsInANumber[100000] << endl << totalDigits[100000] << endl;; int test; sc(test); rep(t,1,test) { int n ; sc(n); for(int i = 1 ; i ;i++ ) { if(totalDigits[i]>=n) { n -= totalDigits[i-1]; break; } } //cout << "value after sub totaldigits : " << n << endl; int cur = 1; for(int i = 1 ; i ;i++ ) { if(digitsInANumber[i]>=n) { n -= digitsInANumber[i-1]; cur = i; break; } } vector<int> digits; while(cur) { digits.push_back(cur%10); cur /= 10; } cout << digits[digits.size()-n] << endl; digits.clear(); //printf("%d\n",t); } }
[ "sunkuet02@gmail.com" ]
sunkuet02@gmail.com
cb28b40061bf03db717d458da97986ff986ee40b
01f5e1556203aa2b10285a97a06b8e9ed172fabf
/PO PROJEKT 1/Komentator.cpp
b04666cd35509286259a42005277265058f20656
[]
no_license
thewildhealer/PO-PROJEKT-1
aa910dbf1a0594dde47f8713e83c529f98d65258
fd0d88a79afbf386d316bcd2cf2667e3608dcc6b
refs/heads/master
2021-01-19T19:45:20.414479
2017-04-18T12:30:25
2017-04-18T12:30:25
88,437,605
0
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
#include "Komentator.h" Komentator::Komentator() { } Komentator::~Komentator() { } void Komentator::komentujTure() { for (std::string kom : komentarze) std::cout << kom << std::endl; wyczyscKomentarze(); } void Komentator::komentujSmierc(Organizm* napastnik, Organizm* ofiara) { std::string pos = "[" + std::to_string(ofiara->getX()) + "," + std::to_string(ofiara->getY()) + "] "; std::string komentarz = napastnik->getNazwa() + " annihiluje: " + ofiara->getNazwa(); komentarze.push_back(pos + komentarz); } void Komentator::komentujNarodziny(Organizm* org, int x, int y) { std::string pos = "[" + std::to_string(x) + "," + std::to_string(y) + "] "; std::string komentarz = "Narodzil/a sie nowy/a " + org->getNazwa() + "!"; komentarze.push_back(pos + komentarz); } void Komentator::komentujNowaRoslina(Organizm* org, int x, int y) { std::string pos = "[" + std::to_string(x) + "," + std::to_string(y) + "] "; std::string komentarz = "Urosla nowa roslina: " + org->getNazwa() + "!"; komentarze.push_back(pos + komentarz); } void Komentator::wyczyscKomentarze() { komentarze.erase(komentarze.begin(), komentarze.end()); }
[ "thewildhealer@outlook.com" ]
thewildhealer@outlook.com
8cab528ecb962b3678e1d0add80cd46658426344
f92b42b1f183870d1685c1b8514d0be002fd79a7
/USACO/2009/Gold/BAYING.CPP
b52b32ef7aad2fdb49d630f1018ed66ba7dff28f
[]
no_license
reiniermujica/algorithms-and-contests
7075f17b2d8e62c0bec5571bc394b5587552e8f2
7ce665cb26d7b97d99789a0704dd98fcfd3acf3c
refs/heads/master
2020-03-21T11:43:42.073645
2018-07-27T21:19:43
2018-07-27T21:19:43
138,519,203
1
0
null
null
null
null
IBM852
C++
false
false
953
cpp
/* Reinier CÚsar Mujica 31 - 3 - 2009 */ #include <cstdio> using namespace std; typedef long long int64; int64 C, N, M; int64 i, j, k; int64 a1, b1, d1; int64 a2, b2, d2; int64 *T; int64 f1( int64 c ) { return ( a1 * c ) / d1 + b1; } int64 f2( int64 c ) { return ( a2 * c ) / d2 + b2; } int main() { freopen( "baying.in", "r", stdin ); freopen( "baying.out", "w", stdout ); scanf( "%d %d", &C, &N ); scanf( "%d %d %d", &a1, &b1, &d1 ); scanf( "%d %d %d", &a2, &b2, &d2 ); int64 s1 = f1( C ); int64 s2 = f2( C ); int64 l1 = 1, l2 = 1; T = new int64[N + 1]; T[M = 1] = C; while ( M < N ) { int64 top = T[M]; if ( s1 < s2 ) { if ( s1 != top ) T[++M] = s1; s1 = f1( T[++l1] ); } else { if ( s2 != top ) T[++M] = s2; s2 = f2( T[++l2] ); } } printf( "%lld\n", T[N] ); return 0; }
[ "reinier.mujica@gmail.com" ]
reinier.mujica@gmail.com
1e718ec8f2d5ba8d85ae8619b1ddcf0540581cd0
2eba3b3b3f979c401de3f45667461c41f9b3537a
/root/io/prefetching/atlasFlushed/TrigT2MbtsBits_p1.h
6b86b19bcca8f74adc4e13daa5664bcc4f9e6929
[]
no_license
root-project/roottest
a8e36a09f019fa557b4ebe3dd72cf633ca0e4c08
134508460915282a5d82d6cbbb6e6afa14653413
refs/heads/master
2023-09-04T08:09:33.456746
2023-08-28T12:36:17
2023-08-29T07:02:27
50,793,033
41
105
null
2023-09-06T10:55:45
2016-01-31T20:15:51
C++
UTF-8
C++
false
false
725
h
////////////////////////////////////////////////////////// // This class has been generated by TFile::MakeProject // (Tue Jun 14 15:33:00 2011 by ROOT version 5.31/01) // from the StreamerInfo in file http://root.cern.ch/files/atlasFlushed.root ////////////////////////////////////////////////////////// #ifndef TrigT2MbtsBits_p1_h #define TrigT2MbtsBits_p1_h class TrigT2MbtsBits_p1; #include "Riostream.h" #include <vector> class TrigT2MbtsBits_p1 { public: // Nested classes declaration. public: // Data Members. unsigned int m_mbtsWord; // vector<float> m_triggerTimes; // TrigT2MbtsBits_p1(); TrigT2MbtsBits_p1(const TrigT2MbtsBits_p1 & ); virtual ~TrigT2MbtsBits_p1(); }; #endif
[ "pcanal@fnal.gov" ]
pcanal@fnal.gov
0a2dce0a87ec177342b157c2cdbaae0d84e4fd33
7df5fae6fc1ebd2c3896361a9eb2feea1f1a73df
/obs/src/cpp/FSM/DC_SM_PreSepFsmState.h
f7aee92e3a9514c452419dcf8cbad597240147f6
[]
no_license
jentlestea1/obs_xslt
bd7c35a71698a17d4e89c4122fbd8bb450f56ce9
d22394be1712f956fccf20e31204b8f961a8ee05
refs/heads/master
2021-05-11T06:50:25.310161
2018-01-18T15:13:28
2018-01-18T15:13:28
117,998,474
1
0
null
null
null
null
UTF-8
C++
false
false
2,587
h
// // Copyright 2004 P&P Software GmbH - All Rights Reserved // // DC_SM_PreSepFsmState.h // // This file was automatically generated by an XSL program #ifndef DC_SM_PreSepFsmStateH #define DC_SM_PreSepFsmStateH #include "../GeneralInclude/ForwardDeclarations.h" #include "../GeneralInclude/BasicTypes.h" #include "../FSM/FsmState.h" /** * Sample FsmState application class. FsmState component for the survival mode pre-separation * submode. * <p> * This is a stub class. It provides dummy implementations for some of the virtual * methods of its superclass. * This class was automatically generated by an XSL program that processes the * XML-based <i>target application model</i>. The XSL program * searches the application model for all "FsmState" elements * which have a "Custom" subelement that indicates that a custom FsmState * class must be created. For each such element a class header file is created. * The base class of the generated class is assumed to be the class in the * "type" attribute of the FsmState element. * The information in the application model is used to decide which virtual methods * should be overridden. * @todo Modify the generator meta-component generateRecoveryAction to generate the code * that sets the class identifier and to treat the default attributes in the custom recovery action description. * @author Automatically Generated Class * @version 1.0 */ class DC_SM_PreSepFsmState : public FsmState { public: /** * Stub constructor that returns without taking any action. */ DC_SM_PreSepFsmState(void); /** * Reset the telemetry manager, reset the telecommand manager. * <p> * This is a stub method that must be completed by the application developer. * This stub provides a default implementation that calls the <code>doInit</code> * method of the superclass. */ virtual void doInit(void); /** * Dummy implementation that returns without taking any action. There is no continuation * action associated to this class. */ virtual void doContinue(void); /** * Terminate when the separation is detected. * <p> * This is a stub method that must be completed by the application developer. * This stub provides a default implementation that calls the <code>isFinished</code> * method of the superclass. * @return true if the continuation action of this state has terminated, false otherwise */ virtual bool isFinished(void); }; #endif
[ "jentlestea@zju.edu.cn" ]
jentlestea@zju.edu.cn
dc5bb3d647566451b692b4eb349682a31454ac5e
32ad463b89a49b7aeeb4d6b4ecf2a4b3a95ad325
/3rdparty/mml/include/mml/window/window_handle.hpp
d6b4d1be678dd9b55c3971c5935d0f1ac9088ea6
[ "BSD-2-Clause" ]
permissive
ArnCarveris/EtherealEngine
d68725f3b782c73ed9b18beb0c928e9b3e952250
bb3f67c8d932d4c3497c7dae8f8e7d2ec17149bb
refs/heads/master
2021-01-19T13:46:11.011510
2017-11-15T00:10:05
2017-11-15T00:10:05
82,414,783
2
0
null
2017-02-18T20:42:19
2017-02-18T20:42:19
null
UTF-8
C++
false
false
826
hpp
#ifndef MML_WINDOWHANDLE_HPP #define MML_WINDOWHANDLE_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <mml/config.hpp> // Windows' HWND is a typedef on struct HWND__* #if defined(MML_SYSTEM_WINDOWS) struct HWND__; #endif namespace mml { #if defined(MML_SYSTEM_WINDOWS) // window handle is HWND (HWND__*) on Windows typedef HWND__* window_handle; #elif defined(MML_SYSTEM_LINUX) || defined(MML_SYSTEM_FREEBSD) // window handle is window (unsigned long) on Unix - X11 typedef unsigned long window_handle; #elif defined(MML_SYSTEM_MACOS) // window handle is NSWindow or NSView (void*) on Mac OS X - Cocoa typedef void* window_handle; #endif } // namespace mml #endif // MML_WINDOWHANDLE_HPP
[ "nikolai.p.ivanov@gmail.com" ]
nikolai.p.ivanov@gmail.com
5bce51e6853698de4037b9f9f5e94a26852bef26
7e99cc5af99ee2bdd6262dc46bc77357797956b6
/42.TrappingRainWater.cpp
c0dcf27187c1e751c1053a91e33af00b61d2cf30
[]
no_license
xqfqhu/Leetcode
c30ef8273a7797838c710665aa68602aced2833f
bd7f718ece21687b3e84e4d5e8699e4b12b78ceb
refs/heads/master
2023-04-11T16:49:15.689352
2021-05-11T10:46:57
2021-05-11T10:46:57
366,347,340
0
0
null
null
null
null
UTF-8
C++
false
false
2,339
cpp
''' Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. ''' class Solution1 { public: int trap(vector<int>& height) { int l = 0; vector<int> r; int n = height.size(); int res = 0; for (int i = n - 1; i >= 0; i--){ if (r.size() == 0 || height[i] > r.back()) r.push_back(height[i]); else r.push_back(r.back()); } for (int i = 0; i < n; i++){ int tmp = r.back(); (height[i] > l)? l = height[i] : l = l; (l > tmp)? res += (tmp - height[i]) : res += (l - height[i]); r.pop_back(); } return res; } }; class Solution2 { public: int trap(vector<int>& height) { int left = 0; int right = height.size() - 1; int leftMax = 0; int rightMax = 0; int res; while (left < right){ if (height[left] < height[right]){ (height[left] > leftMax)? leftMax = height[left] : leftMax = leftMax; res += (leftMax - height[left]); left++; } else{ (height[right] > rightMax)? rightMax = height[right] : rightMax = rightMax; res += (rightMax - height[right]); right--; } } return res; } }; ''' the obvious solution is solution1 more particularly: area = sum((min(leftMax[i], rightMax[i]) - height[i])) this solution takes O(2n) time (which is not bad) and O(n) space (which is bad) so our goal is to decrease space usage since we do not want to store reightMax, we will have to have another pointer which starts from right when we start from the left, we know leftMax[left] for height[left] and when we start from the right, we know rightMax[right] for height[right] area_i = leftMax[left] - height[left] if height[left] < height[right] rightMax[right] - height[right] if height[right] < height[left] because if the height of a bar is higher than any bar right to it, the water it traps is constrained by the height of itself and leftMax if the height of a bar is higher than any bar left to it, the water it traps is constrained by the height of itself and rightMax '''
[ "xqfqhu@gmail.com" ]
xqfqhu@gmail.com
a10d5e1df5b06b5266c2ae5ac83f2250e9872e52
c758dd0f16dffdf79a77dc8f4fdc4c2f7af4f7b8
/c++/src/ndlite.h
f803bac65bd06370cb287329631213090b9678b0
[]
no_license
jcapoduri/ndlite
8023c8e0d8b0096c854fcd81982d39539e477c35
a28ddf13ca828889dc6d2bb8035643e9bc354f56
refs/heads/master
2021-01-02T08:40:30.109515
2013-11-28T23:56:27
2013-11-28T23:56:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
351
h
#ifndef NDLITE_H #define NDLITE_H #include "ndlite_global.h" #include <QJsonDocument> #include <QObject> #include "app.h" namespace nd { template <class T> T* startApp( QJsonDocument &doc, QObject *parent = 0) { if (doc.isNull()) return 0; QJsonValue obj(doc.object()); new T(obj, parent); } } #endif // NDLITE_H
[ "jcapoduril@gmail.com" ]
jcapoduril@gmail.com
1f37ee6e0c6670707e1109c1b1932df341e3c0f5
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/base/win/startup_information_unittest.cc
5002a22ca83a24ed2521adc187a9781f9a3db11f
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
2,960
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <stddef.h> #include <string> #include "base/command_line.h" #include "base/test/multiprocess_test.h" #include "base/win/scoped_handle.h" #include "base/win/scoped_process_information.h" #include "base/win/startup_information.h" #include "base/win/windows_version.h" #include "testing/multiprocess_func_list.h" const wchar_t kSectionName[] = L"EventTestSection"; const size_t kSectionSize = 4096; MULTIPROCESS_TEST_MAIN(FireInheritedEvents) { HANDLE section = ::OpenFileMappingW(PAGE_READWRITE, false, kSectionName); HANDLE* events = reinterpret_cast<HANDLE*>(::MapViewOfFile(section, PAGE_READWRITE, 0, 0, kSectionSize)); // This event should not be valid because it wasn't explicitly inherited. if (::SetEvent(events[1])) return -1; // This event should be valid because it was explicitly inherited. if (!::SetEvent(events[0])) return -1; return 0; } class StartupInformationTest : public base::MultiProcessTest {}; // Verify that only the explicitly specified event is inherited. TEST_F(StartupInformationTest, InheritStdOut) { if (base::win::GetVersion() < base::win::VERSION_VISTA) return; base::win::StartupInformation startup_info; HANDLE section = ::CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, kSectionSize, kSectionName); ASSERT_TRUE(section); HANDLE* events = reinterpret_cast<HANDLE*>(::MapViewOfFile(section, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, kSectionSize)); // Make two inheritable events. SECURITY_ATTRIBUTES security_attributes = { sizeof(security_attributes), NULL, true }; events[0] = ::CreateEvent(&security_attributes, false, false, NULL); ASSERT_TRUE(events[0]); events[1] = ::CreateEvent(&security_attributes, false, false, NULL); ASSERT_TRUE(events[1]); ASSERT_TRUE(startup_info.InitializeProcThreadAttributeList(1)); ASSERT_TRUE(startup_info.UpdateProcThreadAttribute( PROC_THREAD_ATTRIBUTE_HANDLE_LIST, &events[0], sizeof(events[0]))); std::wstring cmd_line = MakeCmdLine("FireInheritedEvents").GetCommandLineString(); PROCESS_INFORMATION temp_process_info = {}; ASSERT_TRUE(::CreateProcess(NULL, &cmd_line[0], NULL, NULL, true, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, startup_info.startup_info(), &temp_process_info)) << ::GetLastError(); base::win::ScopedProcessInformation process_info(temp_process_info); // Only the first event should be signalled EXPECT_EQ(WAIT_OBJECT_0, ::WaitForMultipleObjects(2, events, false, 4000)); }
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
ec4d46e92362a9cb54340a15d060cece059cff90
15e4be492be47216ac22a84230de1e19cbc4e6ec
/include/fx/Envelope.h
3d44e897b3ac15038d5fa4d38543e3dd4cd70a25
[ "Apache-2.0" ]
permissive
audaspace/audaspace
921fcaa08adc5a04af7926c2c2b1fda4b6daf81e
5f745ff3707552b090ea19c3839c70ca68b5429d
refs/heads/master
2023-08-03T23:08:43.036694
2023-07-24T14:18:02
2023-07-24T14:18:02
28,258,026
10
4
Apache-2.0
2023-08-05T09:01:45
2014-12-20T05:33:57
C++
UTF-8
C++
false
false
2,515
h
/******************************************************************************* * Copyright 2009-2016 Jörg Müller * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ #pragma once /** * @file Envelope.h * @ingroup fx * The Envelope class. */ #include "fx/Effect.h" AUD_NAMESPACE_BEGIN class CallbackIIRFilterReader; struct EnvelopeParameters; /** * This sound creates an envelope follower reader. */ class AUD_API Envelope : public Effect { private: /** * The attack value in seconds. */ const float m_attack; /** * The release value in seconds. */ const float m_release; /** * The threshold value. */ const float m_threshold; /** * The attack/release threshold value. */ const float m_arthreshold; // delete copy constructor and operator= Envelope(const Envelope&) = delete; Envelope& operator=(const Envelope&) = delete; public: /** * Creates a new envelope sound. * \param sound The input sound. * \param attack The attack value in seconds. * \param release The release value in seconds. * \param threshold The threshold value. * \param arthreshold The attack/release threshold value. */ Envelope(std::shared_ptr<ISound> sound, float attack, float release, float threshold, float arthreshold); virtual std::shared_ptr<IReader> createReader(); /** * The envelopeFilter function implements the doFilterIIR callback * for the callback IIR filter. * @param reader The CallbackIIRFilterReader that executes the callback. * @param param The envelope parameters. * @return The filtered sample. */ static sample_t AUD_LOCAL envelopeFilter(CallbackIIRFilterReader* reader, EnvelopeParameters* param); /** * The endEnvelopeFilter function implements the endFilterIIR callback * for the callback IIR filter. * @param param The envelope parameters. */ static void AUD_LOCAL endEnvelopeFilter(EnvelopeParameters* param); }; AUD_NAMESPACE_END
[ "nexyon@gmail.com" ]
nexyon@gmail.com
f95a0d5db47a67cc7610f325d34c464692031896
f499428e5e647d3bea7de52e39b70952994101cd
/Jass/src/Platform/DirectX11/ShaderReflection/VariableDescription.cpp
8c41d04564c1970b784312849decaa330c56d907
[]
no_license
cyandestructor/Sandbox3DX
03573a459cd60234cd204a870aa3be7752fd3cf6
6045a252b937c5ffb78174642408a6de0ee2b880
refs/heads/master
2023-05-13T19:37:44.974052
2021-05-26T15:33:09
2021-05-26T15:33:09
346,238,651
0
0
null
null
null
null
UTF-8
C++
false
false
479
cpp
#include "jasspch.h" #include "VariableDescription.h" namespace Jass { VariableDescription::VariableDescription(ID3D11ShaderReflectionVariable* variableReflection) :m_variableReflection(variableReflection) { JASS_CORE_ASSERT(m_variableReflection != nullptr, "Variable reflection is nullptr"); m_variableReflection->GetDesc(&m_description); ID3D11ShaderReflectionType* typeReflection = m_variableReflection->GetType(); m_typeDescription.Set(typeReflection); } }
[ "dellinspiron15BEDL@outlook.com" ]
dellinspiron15BEDL@outlook.com
aa488c8f65daff97bab207d98268bc62547b8349
74837fe7d0c359f6648c623e5c3bbd5c2125e3c0
/core/logging.hpp
f7a68d31eee61015afc787f43228d6f432fdf973
[]
no_license
sempuki/code
7b46d4a38a68707c1399c3231b05c44ff1fa10a4
7fcc3ec6e86bfd338c3cb7e6c9202f33e5871c42
refs/heads/main
2023-08-16T08:55:00.979327
2023-08-02T19:59:58
2023-08-02T19:59:58
698,803
3
2
null
null
null
null
UTF-8
C++
false
false
4,836
hpp
#ifndef SRC_CORE_LOGGING_HPP_ #define SRC_CORE_LOGGING_HPP_ #ifdef __GNUC__ // clang supports this header #include <cxxabi.h> inline std::string demangle(const std::string &name) { size_t size = 1024; // we *don't* want realloc() to be called char buffer[size]; // NOLINT int status = 0; abi::__cxa_demangle(name.c_str(), buffer, &size, &status); assert(status == 0 && "Demanging failed"); return buffer; } #else inline std::string demangle(const std::string &name) { return name; } #endif // __GNUC__ // Only supports maximum 8 arguments // Zero arguments are also *not* supported // recurse down from given argument count #define PRINT_ARG_1(argument) #argument ": " << argument #define PRINT_ARG_2(argument, ...) #argument ": " << argument << ", " << PRINT_ARG_1(__VA_ARGS__) #define PRINT_ARG_3(argument, ...) #argument ": " << argument << ", " << PRINT_ARG_2(__VA_ARGS__) #define PRINT_ARG_4(argument, ...) #argument ": " << argument << ", " << PRINT_ARG_3(__VA_ARGS__) #define PRINT_ARG_5(argument, ...) #argument ": " << argument << ", " << PRINT_ARG_4(__VA_ARGS__) #define PRINT_ARG_6(argument, ...) #argument ": " << argument << ", " << PRINT_ARG_5(__VA_ARGS__) #define PRINT_ARG_7(argument, ...) #argument ": " << argument << ", " << PRINT_ARG_6(__VA_ARGS__) #define PRINT_ARG_8(argument, ...) #argument ": " << argument << ", " << PRINT_ARG_7(__VA_ARGS__) // varargs displaces count so that N aligns with the correct size #define COUNT_ARGS(...) COUNT_ARGS_(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0) #define COUNT_ARGS_(_1, _2, _3, _4, _5, _6, _7, _8, N, ...) N // magic to make nested macro evaluations complete #define CONCAT(lhs, rhs) CONCAT1(lhs, rhs) #define CONCAT1(lhs, rhs) CONCAT2(lhs, rhs) #define CONCAT2(lhs, rhs) lhs##rhs // print all args with name label and output stream operator #define PRINT_ARGS(...) CONCAT(PRINT_ARG_, COUNT_ARGS(__VA_ARGS__))(__VA_ARGS__) // Uniform logging macros (assumes the loging object is called "logger") #define LOG_METHOD_CALL()\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << PRINT_ARG_1(this) \ ) #define LOG_METHOD_CALL_(LEVEL)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << PRINT_ARG_1(this) \ ) #define LOG_METHOD_ARGS(...)\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << PRINT_ARGS(this, __VA_ARGS__) \ ) #define LOG_METHOD_ARGS_(LEVEL, ...)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << PRINT_ARGS(this, __VA_ARGS__) \ ) #define LOG_METHOD_MESG(message)\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ << ", " << PRINT_ARG_1(this) \ ) #define LOG_METHOD_MESG_(LEVEL, message)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ << ", " << PRINT_ARG_1(this) \ ) #define LOG_METHOD_FULL(message, ...)\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ << ", " << PRINT_ARGS(this, __VA_ARGS__) \ ) #define LOG_METHOD_FULL_(LEVEL, message, ...)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ << ", " << PRINT_ARGS(this, __VA_ARGS__) \ ) #define LOG_CALL()\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ ) #define LOG_CALL_(LEVEL)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ ) #define LOG_ARGS(...)\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << PRINT_ARGS(__VA_ARGS__) \ ) #define LOG_ARGS_(LEVEL, ...)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << PRINT_ARGS(__VA_ARGS__) \ ) #define LOG_MESG(message)\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ ) #define LOG_MESG_(LEVEL, message)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ ) #define LOG_FULL(message, ...)\ LOG4CXX_DEBUG(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ << ", " << PRINT_ARGS(__VA_ARGS__) \ ) #define LOG_FULL_(LEVEL, message, ...)\ LOG4CXX_ ## LEVEL(logger, \ __FUNCTION__ << '[' << __LINE__ << ']' \ << ": " << message \ << ", " << PRINT_ARGS(__VA_ARGS__) \ ) #define LOG(message, ...)\ LOG4CXX_DEBUG(logger, \ message << ": " << PRINT_ARGS(__VA_ARGS__) \ ) #define LOG_(LEVEL, message, ...)\ LOG4CXX_ ## LEVEL(logger, \ message << ": " << PRINT_ARGS(__VA_ARGS__) \ ) #endif
[ "ryan@tokbox.com" ]
ryan@tokbox.com
e284899129987d55f2c8e496db47458ea9866ac5
998500fbaf71fa6f3399ea45bd987a60e160f6ef
/dmoj/coci16c6p5.cpp
e5727051b3fe027bb9b23dcb6ddfb660a976916e
[]
no_license
rHermes/contests
ea94beeef559ded11fc9bb3680c78f0bfa4dbc56
b7e621f52c9d2c08f90d12c89bf0abf53a519836
refs/heads/master
2022-07-23T03:47:34.380740
2022-07-11T09:30:26
2022-07-11T09:30:26
124,693,122
0
0
null
null
null
null
UTF-8
C++
false
false
1,832
cpp
/** * coci16c6p5 - COCI '16 Contest 6 #5 Sirni * * This has something to do with sets I think? * */ #include <cstdio> #include <vector> #include <algorithm> #include <cstdint> #include <cinttypes> #include <limits> #include <set> #include <iterator> #include <tuple> #include <utility> std::vector<uint32_t> read_input() { uint32_t N; scanf("%" SCNu32, &N); std::vector<uint32_t> ins; for (uint32_t i = 0; i < N; i++) { uint32_t in; scanf("%" SCNu32, &in); ins.push_back(in); } return ins; } // Solve this using a minimal spanning tree uint32_t solve_with_mst(std::vector<uint32_t> input) { // Special case if we only have one if (input.size() < 2) { return 0; } std::set<std::pair<uint32_t,uint32_t>> Q; for (const auto d : input) { Q.insert(std::make_pair(std::numeric_limits<uint32_t>::max(),d)); } // printf("%ld\n", Q.size()); bool first = true; // the accumulator for the answer uint32_t ans = 0; while (!Q.empty()) { const auto elem = Q.extract(Q.begin()); // cheat on the first one and set it to 0 if (first) { elem.value().first = 0; first = false; } const auto [cost, node] = elem.value(); // printf("Node: %u, Cost: %u, Total: %u\n", node, cost, ans); // Now we must update the other weights auto cur = Q.begin(); while (cur != Q.end()) { const auto [acost, bnode] = *cur; cur++; // New cost const auto newcost = std::max(node,bnode) % std::min(node,bnode); if (newcost < acost) { auto aanode = Q.extract(std::prev(cur,1)); aanode.value().first = newcost; Q.insert(move(aanode)); } } // The answer is the cost ans += cost; } return ans; } int main() { auto ins = read_input(); auto ans = solve_with_mst(ins); // printf("mst: %" PRIu32 "\n", ans); printf("%" PRIu32 "\n", ans); return 0; }
[ "teodor@sparen.no" ]
teodor@sparen.no
f62eda87470b6c262d186fee53a37177f894f2c3
b8e8197db52941e1694d91b992c218974d0c0048
/MFCTest/CPopDlg.cpp
a8469292257828e72c3885da6aca0997829a4630
[]
no_license
hitblda/MFCTest
a790de318af7cd32d9c879598b338fd0776b9c66
e66dd3ed76e383fe026ee6201e153f88164569be
refs/heads/master
2021-02-08T12:30:35.483040
2020-03-02T23:08:40
2020-03-02T23:08:40
244,151,680
0
0
null
null
null
null
UTF-8
C++
false
false
469
cpp
// CPopDlg.cpp: 实现文件 // #include "pch.h" #include "MFCTest.h" #include "CPopDlg.h" #include "afxdialogex.h" // CPopDlg 对话框 IMPLEMENT_DYNAMIC(CPopDlg, CDialogEx) CPopDlg::CPopDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_PopDlg, pParent) { } CPopDlg::~CPopDlg() { } void CPopDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CPopDlg, CDialogEx) END_MESSAGE_MAP() // CPopDlg 消息处理程序
[ "hitblda@163.com" ]
hitblda@163.com
4dd13b92e0340d1dd7ea2e0c8401108f9a937026
ec33bd48223e25c4528e15a2fbd847dd3f85e3bf
/CPP_projects/RapidBackend/sources/ConfigHelper.cpp
cc1523ab0eea51ccec83ba6b681139379e2cd246
[]
no_license
y-vyrovoy/misc_projects
21b5e07674ceda6cb24696c3ec289fa3d0cb8c68
e2d6db318bd5e24914dfa1212252e32fbb34f0a9
refs/heads/master
2021-10-25T06:27:31.653299
2019-04-02T08:34:11
2019-04-02T08:34:11
93,945,971
0
0
null
null
null
null
UTF-8
C++
false
false
2,443
cpp
#include "stdafx.h" #include "ConfigHelper.h" #include <iterator> #include <iostream> #include "Logger.h" #include "MessageException.h" void ConfigHelper::parseCmdLine( const int argn, const char * const argv[] ) { if ( argn < 1 ) { return; } m_params["binaryName"] = argv[0]; for ( int iParameter = 1; iParameter < argn; ++iParameter ) { std::string paramName; size_t paramStart = 0; size_t paramEnd = 0; // parameter name should start with '-' if ( argv[iParameter][0] == '-' ) { paramName.assign( &argv[iParameter][1] ); } else { continue; } // if parameter name is last without value if ( iParameter + 1 >= argn ) { return; } std::string paramValue; paramValue.assign( argv[iParameter + 1] ); ParameterContainer::iterator it = m_params.find( paramName ); if ( it != m_params.end() ) { WARN_LOG_F << "Overwirting parameter [" << paramName << "]." " old value [" << it->second << "]" " new value [" << paramValue << "]"; it->second = paramValue; } else { m_params[paramName] = paramValue; } iParameter++; } } void ConfigHelper::dump() const { INFO_LOG_F << ""; for ( std::pair<std::string, std::string> p : m_params ) { INFO_LOG << '\t' << p.first << " : " << p.second; } } const std::string ConfigHelper::get( const char * paramName ) const { ParameterContainer::const_iterator it = m_params.find( paramName ); if ( it == m_params.end() ) { std::stringstream ssError; ssError << "Cant't find config parameter [" << paramName << "]"; throw std::runtime_error( ssError.str() ); } return it->second; } const bool ConfigHelper::getOptional( const char * paramName, std::string & paramValue ) const { try { paramValue = get( paramName ); return true; } catch( const std::exception & ) { paramValue = ""; return false; } } const bool ConfigHelper::getOptional( const char * paramName, int & paramValue ) const { try { paramValue = std::stoi( get( paramName ) ); return true; } catch( const std::exception & ) { paramValue = 0; return false; } } std::string ConfigHelper::getLogFilename() const { std::string logFilename; if( getOptional("log", logFilename) ) { return logFilename; } return std::string(); } std::string ConfigHelper::getRootFolder() const { std::string logFilename; if( getOptional("root", logFilename) ) { return logFilename; } return std::string(); }
[ "y.vyrovoy@gmail.com" ]
y.vyrovoy@gmail.com
4a44757cd9d0479ee49f857345c5c5802fe4b9ea
f6e823da0a29309cb7a2afe8745b983dc791ecad
/class/resource/GPIO/setter/GPIOSetter.h
149c53a29c77537a4b88be60aefcc640cb856ef9
[]
no_license
umberLLaJYL/mcsg
52e31f68d7288e31bd13b54170d17202c3522cd1
b6549c480be768ba5b33c105f4962eed0649d145
refs/heads/master
2021-07-06T15:40:05.971275
2019-02-27T02:32:09
2019-02-27T02:32:09
136,575,294
0
0
null
null
null
null
UTF-8
C++
false
false
919
h
#if !defined(_GPIOSetter_) #define _GPIOSetter_ #include "../../IResourceSetter.h" #define DirGPIO "/sys/class/gpio/gpiox/" #if !defined(WriteLen) #define WriteLen 8 #endif // WRLen #if !defined(WritePos) #define WritePos 20 #endif // WritePos class GPIOSetter : public IResourceSetter { private: int handle; protected: static std::string &_setDirectory(std::string &dir, const std::string &idx, const std::string &key){ dir = DirGPIO; return dir.replace(WritePos, dir.find_last_of("/")-WritePos, idx) += key; } bool _setHandle(int newHandle) { this->handle = newHandle; } const int _getHandle() { return this->handle; } public: GPIOSetter() { } virtual ~GPIOSetter() { } bool set(const std::string &direction) override { return !(write(this->handle, direction.c_str(), WriteLen) < 0); } }; #endif // _GPIOSetter_
[ "umbrella.jyl@hotmail.com" ]
umbrella.jyl@hotmail.com
09d2933b81c529c6d4f0834adddaf55b11115549
ad1a653e4bd00871e9c18d7a3ba6c89e0a807585
/scite/src/FileWorker.cxx
73632c4023ba6253371970d2bfea31deac5b7d61
[ "LicenseRef-scancode-scintilla" ]
permissive
pantelic-dusan/Scintilla-SciTE
98482524c4213b1a5e3af3020507c70b2d1c441a
9b9cfa836300225e92de860821167606c8ad2fb4
refs/heads/master
2020-04-08T19:30:21.800897
2019-04-22T15:01:50
2019-04-22T15:01:50
159,658,351
1
0
null
null
null
null
UTF-8
C++
false
false
4,676
cxx
// SciTE - Scintilla based Text Editor /** @file FileWorker.cxx ** Implementation of classes to perform background file tasks as threads. **/ // Copyright 2011 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <cstdlib> #include <cstring> #include <cstdio> #include <string> #include <vector> #include <memory> #include "ILoader.h" #include "Scintilla.h" #include "GUI.h" #include "ScintillaWindow.h" #include "FilePath.h" #include "Mutex.h" #include "Cookie.h" #include "Worker.h" #include "FileWorker.h" #include "Utf8_16.h" const double timeBetweenProgress = 0.4; FileWorker::FileWorker(WorkerListener *pListener_, const FilePath &path_, size_t size_, FILE *fp_) : pListener(pListener_), path(path_), size(size_), err(0), fp(fp_), sleepTime(0), nextProgress(timeBetweenProgress) { } FileWorker::~FileWorker() { } double FileWorker::Duration() { return et.Duration(); } FileLoader::FileLoader(WorkerListener *pListener_, ILoader *pLoader_, const FilePath &path_, size_t size_, FILE *fp_) : FileWorker(pListener_, path_, size_, fp_), pLoader(pLoader_), readSoFar(0), unicodeMode(uni8Bit) { SetSizeJob(size); } FileLoader::~FileLoader() { } void FileLoader::Execute() { if (fp) { Utf8_16_Read convert; std::vector<char> data(blockSize); size_t lenFile = fread(&data[0], 1, blockSize, fp); const UniMode umCodingCookie = CodingCookieValue(&data[0], lenFile); while ((lenFile > 0) && (err == 0) && (!Cancelling())) { GUI::SleepMilliseconds(sleepTime); lenFile = convert.convert(&data[0], lenFile); const char *dataBlock = convert.getNewBuf(); err = pLoader->AddData(dataBlock, static_cast<int>(lenFile)); IncrementProgress(static_cast<int>(lenFile)); if (et.Duration() > nextProgress) { nextProgress = et.Duration() + timeBetweenProgress; pListener->PostOnMainThread(WORK_FILEPROGRESS, this); } lenFile = fread(&data[0], 1, blockSize, fp); if ((lenFile == 0) && (err == 0)) { // Handle case where convert is holding a lead surrogate but no more data const size_t lenFileTrail = convert.convert(nullptr, lenFile); if (lenFileTrail) { const char *dataTrail = convert.getNewBuf(); err = pLoader->AddData(dataTrail, static_cast<int>(lenFileTrail)); } } } fclose(fp); fp = nullptr; unicodeMode = static_cast<UniMode>( static_cast<int>(convert.getEncoding())); // Check the first two lines for coding cookies if (unicodeMode == uni8Bit) { unicodeMode = umCodingCookie; } } SetCompleted(); pListener->PostOnMainThread(WORK_FILEREAD, this); } void FileLoader::Cancel() { FileWorker::Cancel(); pLoader->Release(); pLoader = nullptr; } FileStorer::FileStorer(WorkerListener *pListener_, const char *documentBytes_, const FilePath &path_, size_t size_, FILE *fp_, UniMode unicodeMode_, bool visibleProgress_) : FileWorker(pListener_, path_, size_, fp_), documentBytes(documentBytes_), writtenSoFar(0), unicodeMode(unicodeMode_), visibleProgress(visibleProgress_) { SetSizeJob(size); } FileStorer::~FileStorer() { } static bool IsUTF8TrailByte(int ch) { return (ch >= 0x80) && (ch < (0x80 + 0x40)); } void FileStorer::Execute() { if (fp) { Utf8_16_Write convert; if (unicodeMode != uniCookie) { // Save file with cookie without BOM. convert.setEncoding(static_cast<Utf8_16::encodingType>( static_cast<int>(unicodeMode))); } convert.setfile(fp); std::vector<char> data(blockSize + 1); const size_t lengthDoc = size; size_t grabSize; for (size_t i = 0; i < lengthDoc && (!Cancelling()); i += grabSize) { GUI::SleepMilliseconds(sleepTime); grabSize = lengthDoc - i; if (grabSize > blockSize) grabSize = blockSize; if ((unicodeMode != uni8Bit) && (i + grabSize < lengthDoc)) { // Round down so only whole characters retrieved. size_t startLast = grabSize; while ((startLast > 0) && ((grabSize - startLast) < 6) && IsUTF8TrailByte(static_cast<unsigned char>(documentBytes[i + startLast]))) startLast--; if ((grabSize - startLast) < 5) grabSize = startLast; } memcpy(&data[0], documentBytes+i, grabSize); const size_t written = convert.fwrite(&data[0], grabSize); IncrementProgress(grabSize); if (et.Duration() > nextProgress) { nextProgress = et.Duration() + timeBetweenProgress; pListener->PostOnMainThread(WORK_FILEPROGRESS, this); } if (written == 0) { err = 1; break; } } if (convert.fclose() != 0) { err = 1; } } SetCompleted(); pListener->PostOnMainThread(WORK_FILEWRITTEN, this); } void FileStorer::Cancel() { FileWorker::Cancel(); }
[ "pantelic.dusan@protonmail.com" ]
pantelic.dusan@protonmail.com
a0b0d89d01f6df76cc406462d2299773b1d0821d
eb5909d3dc534d531a0229bdf4824356aa646f9c
/SimpleOpenCLLib/header/abstract/ISimpleCLExecutorFactory.h
95ab47d3d6b0c44d1f6f453aa4772bf0db70141b
[]
no_license
wws2003/StudyProjectL2.1
f406edfddd13a6bc325aaace1f5d252bde7240c3
9971e686ef987d7aaed1222a7e61066adb66e01f
refs/heads/master
2021-04-28T09:08:18.282389
2019-05-19T15:50:20
2019-05-19T15:50:20
122,032,840
0
0
null
null
null
null
UTF-8
C++
false
false
529
h
// // ISimpleCLExecutorFactory.h // OpenCLHelloWorld // // Created by wws2003 on 3/29/16. // Copyright © 2016 tbg. All rights reserved. // #ifndef ISimpleCLExecutorFactory_h #define ISimpleCLExecutorFactory_h #include "ISimpleCLExecutor.h" class ISimpleCLExecutorFactory { public: virtual ~ISimpleCLExecutorFactory(){}; virtual SimpleCLExecutorPtr getSimpleCLExecutor(cl_device_type deviceType) = 0; }; typedef ISimpleCLExecutorFactory* SimpleCLExecutorFactoryPtr; #endif /* ISimpleCLExecutorFactory_h */
[ "wws2003@phams-MacBook-Pro.local" ]
wws2003@phams-MacBook-Pro.local
190b2a72d72fc8ab262ba1de976c9f5743099d2b
2fa9ab0af65a3fa9eead8cb426af4b60a2a67eac
/src/model/paging.hpp
9abb1c9aceb234d1a2d08f193620a27a3aae7e1d
[]
no_license
avs009/Scheid-Spotify
24d7d79a88a86ed13db7470ddce5f903c75371db
2dd790e235b450c30c6b5174b5c691f369408591
refs/heads/master
2023-06-09T19:54:22.811616
2021-07-02T02:00:43
2021-07-02T02:00:43
377,685,520
0
0
null
null
null
null
UTF-8
C++
false
false
4,971
hpp
#ifndef PAGINGOBJECT_H #define PAGINGOBJECT_H #include <QVector> #include <QString> #include <QMetaType> #include "track.h" /*! * \brief Classe para suportar a paginação ao efetuar uma busca no spotify */ template<class T> class Paging { public: /*! * \brief Paging Construtor padrão */ explicit Paging() { } /*! * \brief ~Paging Destrutor padrão */ virtual ~Paging() { items.clear(); } /*! * \brief Paging Construtor de cópia da classe * \param org Objeto original a ser copiado */ Paging(const Paging & org) { href = org.getHref(); items = org.getItems(); limit = org.getLimit(); next = org.getNext(); offset = org.getOffset(); previous = org.getPrevious(); total = org.getTotal(); } /*! * \brief getHref Retorna o link de referência ao qual foi obtido este objeto * \return */ const QString &getHref() const { return href; } /*! * \brief setHref Ajusta o link de referência ao qual foi obtido este objeto * \param newHref Novo link */ void setHref(const QString &newHref) { href = newHref; } /*! * \brief getItems Retorna os items obtidos de acordo com o deslocamento e limite * \return */ const QVector<T> &getItems() const { return items; } /*! * \brief setItems Ajusta os itens obtidos * \param newItems Novos itens */ void setItems(const QVector<T> &newItems) { items = newItems; } /*! * \brief addItem Adiciona um novo item a lista de items obitidos * \param newItem Novo Item */ void addItem(T newItem) { items.push_back(newItem); } /*! * \brief getLimit Retorna o limite de Resultados solicitados * \return */ const int getLimit() const { return limit; } /*! * \brief setLimit Ajusta o limite de resultados solicitados * \param newLimit Novo limite */ void setLimit(int newLimit) { limit = newLimit; } /*! * \brief getNext * \return */ const QString &getNext() const { return next; } /*! * \brief setNext * \param newNext */ void setNext(const QString &newNext) { next = newNext; } /*! * \brief getOffset Retorn o número de deslocamentos até chegar nesta página * \return */ const int getOffset() const { return offset; } /*! * \brief setOffset Ajusta o número de deslocamentos até chegar nesta página * \param newOffset Número de deslocamentos */ void setOffset(int newOffset) { offset = newOffset; } /*! * \brief getPrevious * \return */ const QString getPrevious() const { return previous; } /*! * \brief setPrevious * \param newPrevious */ void setPrevious(const QString &newPrevious) { previous = newPrevious; } /*! * \brief getTotal Retorna o total de resultados encontrados na busca * \return */ const int getTotal() const { return total; } /*! * \brief setTotal Ajusta o total de resultados encontrados na busca * \param newTotal */ void setTotal(int newTotal) { total = newTotal; } /*! * \brief operator QString Converte o objeto atual para string, de modo a ver as informações armazenadas. */ operator QString() const { QString ret; QTextStream(&ret) << "Object: Paging - \n" << "href='" << href << "'\n" << "limit='" << limit << "'\n" << "next='" << next << "'\n" << "previous='" << previous << "'\n" << "offset='" << offset << "'\n" << "total='" << total << "'" << "items:" << "\n"; foreach(auto i, items) QTextStream(&ret) << "\t" << i << "\n"; return ret; } private: /*! * \brief href Link utilizado para obter esta paginação. */ QString href; /*! * \brief items Items desta página de acordo com o offset e limite. */ QVector<T> items; /*! * \brief limit Limite de itens por página. */ int limit; /*! * \brief next */ QString next; /*! * \brief offset Deslocamento utilizado até chegar nesta página. */ int offset; /*! * \brief previous */ QString previous; /*! * \brief total Total de resultados encontrados na busca. */ int total; }; //Q_DECLARE_METATYPE_TEMPLATE_1ARG(Paging); typedef Paging<Track> PagingForTrack; Q_DECLARE_METATYPE(PagingForTrack); #endif // PAGINGOBJECT_H
[ "avs.009@gmail.com" ]
avs.009@gmail.com
99a49b87657a35a45a75dbc4b89849f46f10d259
3113b3ed92063987040a652a1ca19231c33afc2c
/Stone Age/Stone Age - Qt Application/model/Places/ForestPlace.h
8c9fdc0eeba31d4e78fbb53979bdd83cb7748de6
[]
no_license
kristofleroux/uh-ogp1-project
1e61a198219e6d7ee62b3a67847e40ccc34b66ba
90047d39eb4cc14df9815decc472caf86a05d7b5
refs/heads/master
2022-01-24T23:07:06.643206
2019-07-16T08:44:41
2019-07-16T08:44:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
552
h
#ifndef FORESTPLACE_H #define FORESTPLACE_H #include <QString> #include "../Place.h" #include "ResourcePlace.h" #include "../../config.h" class Worker; class Player; class Game; class ForestPlace : public Place, public ResourcePlace { public: // Constructor ForestPlace(QString name, int maximumWorkerAmount, Game* game); // Utils void calculateMaterials(Player* player, int currentWorkers); void updateCalcView(Player* player, int toolLevel); void claimResources(); }; #endif // FORESTPLACE_H
[ "michiel.swaanen.gsm@gmail.com" ]
michiel.swaanen.gsm@gmail.com
281477f89e0ec717e022dcebd7379799f7f03f2e
da1ba0378e1ed8ff8380afb9072efcd3bbead74e
/google/cloud/internal/curl_wrappers_test.cc
3d918e5e00b3defa88ee7dd6837c8f30d65fdb19
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Jseph/google-cloud-cpp
76894af7ce744cd44304b48bea32d5116ded7497
fd8e70650ebac0c10bac4b293972e79eef46b128
refs/heads/master
2022-10-18T13:07:01.710328
2022-10-01T18:16:16
2022-10-01T18:16:16
192,397,663
0
0
null
2019-06-17T18:22:36
2019-06-17T18:22:35
null
UTF-8
C++
false
false
5,075
cc
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/internal/curl_wrappers.h" #include "google/cloud/internal/curl_options.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace rest_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { TEST(CurlWrappers, VersionToCurlCode) { struct Test { std::string version; std::int64_t expected; } cases[] = { {"", CURL_HTTP_VERSION_NONE}, {"default", CURL_HTTP_VERSION_NONE}, {"1.0", CURL_HTTP_VERSION_1_0}, {"1.1", CURL_HTTP_VERSION_1_1}, #if CURL_AT_LEAST_VERSION(7, 33, 0) {"2.0", CURL_HTTP_VERSION_2_0}, #endif // CURL >= 7.33.0 #if CURL_AT_LEAST_VERSION(7, 47, 0) {"2TLS", CURL_HTTP_VERSION_2TLS}, #endif // CURL >= 7.47.0 #if CURL_AT_LEAST_VERSION(7, 66, 0) {"3", CURL_HTTP_VERSION_3}, #endif // CURL >= 7.66.0 }; for (auto const& test : cases) { SCOPED_TRACE("Testing with <" + test.version + ">"); EXPECT_EQ(test.expected, VersionToCurlCode(test.version)); } } TEST(CurlWrappers, DebugSendHeader) { struct TestCasse { std::string input; std::string expected; } cases[] = { {R"""(header1: no-marker-no-nl)""", R"""(>> curl(Send Header): header1: no-marker-no-nl)"""}, {R"""(header1: no-marker-w-nl )""", R"""(>> curl(Send Header): header1: no-marker-w-nl )"""}, {R"""(header1: no-marker-w-nl-and-data header2: value2 )""", R"""(>> curl(Send Header): header1: no-marker-w-nl-and-data header2: value2 )"""}, {R"""(header1: short-no-nl authorization: Bearer 012345678901234567890123456789)""", R"""(>> curl(Send Header): header1: short-no-nl authorization: Bearer 012345678901234567890123456789)"""}, {R"""(header1: short-w-nl authorization: Bearer 012345678901234567890123456789 )""", R"""(>> curl(Send Header): header1: short-w-nl authorization: Bearer 012345678901234567890123456789 )"""}, {R"""(header1: short-w-nl-and-data authorization: Bearer 012345678901234567890123456789 header2: value2 )""", R"""(>> curl(Send Header): header1: short-w-nl-and-data authorization: Bearer 012345678901234567890123456789 header2: value2 )"""}, {R"""(header1: exact-no-nl authorization: Bearer 01234567890123456789012345678912)""", R"""(>> curl(Send Header): header1: exact-no-nl authorization: Bearer 01234567890123456789012345678912)"""}, {R"""(header1: exact-w-nl authorization: Bearer 01234567890123456789012345678912 )""", R"""(>> curl(Send Header): header1: exact-w-nl authorization: Bearer 01234567890123456789012345678912 )"""}, {R"""(header1: exact-w-nl-and-data authorization: Bearer 01234567890123456789012345678912 header2: value2 )""", R"""(>> curl(Send Header): header1: exact-w-nl-and-data authorization: Bearer 01234567890123456789012345678912 header2: value2 )"""}, {R"""(header1: long-no-nl authorization: Bearer 012345678901234567890123456789123456)""", R"""(>> curl(Send Header): header1: long-no-nl authorization: Bearer 01234567890123456789012345678912...<truncated>...)"""}, {R"""(header1: long-w-nl authorization: Bearer 012345678901234567890123456789123456 )""", R"""(>> curl(Send Header): header1: long-w-nl authorization: Bearer 01234567890123456789012345678912...<truncated>... )"""}, {R"""(header1: long-w-nl-and-data authorization: Bearer 012345678901234567890123456789123456 header2: value2 )""", R"""(>> curl(Send Header): header1: long-w-nl-and-data authorization: Bearer 01234567890123456789012345678912...<truncated>... header2: value2 )"""}, }; for (auto const& test : cases) { EXPECT_EQ(test.expected, DebugSendHeader(test.input.data(), test.input.size())); } } TEST(CurlWrappers, CurlInitializeOptions) { auto defaults = CurlInitializeOptions({}); EXPECT_TRUE(defaults.get<EnableCurlSslLockingOption>()); EXPECT_TRUE(defaults.get<EnableCurlSigpipeHandlerOption>()); auto override1 = CurlInitializeOptions(Options{}.set<EnableCurlSslLockingOption>(false)); EXPECT_FALSE(override1.get<EnableCurlSslLockingOption>()); EXPECT_TRUE(override1.get<EnableCurlSigpipeHandlerOption>()); auto override2 = CurlInitializeOptions( Options{}.set<EnableCurlSigpipeHandlerOption>(false)); EXPECT_TRUE(override2.get<EnableCurlSslLockingOption>()); EXPECT_FALSE(override2.get<EnableCurlSigpipeHandlerOption>()); } } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace rest_internal } // namespace cloud } // namespace google
[ "noreply@github.com" ]
noreply@github.com
910c28bfb2ecc46e5c323550a8da64ef260a5615
f3ab266533181f161da1138ae5e1cdc64e7ee207
/Graphics/SkinFactory/ConvexPolygonSkinFactory.cpp
6e93be5e0799a431278ab75fb9dc824a273273cb
[]
no_license
jsj2008/framework2d
dba47068163da74f844fb292091fbaea7d06be7b
b3f355f0a0dcf8ffec90b8e95b7535fa35744a80
refs/heads/master
2020-12-25T10:37:32.924083
2012-03-01T08:01:30
2012-03-01T08:01:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
782
cpp
#include "ConvexPolygonSkinFactory.h" #include <Graphics/Skins/ConvexPolygonSkin.h> #include <Graphics/GraphicsManager.h> /// FIXME ConvexPolygonSkinFactory::ConvexPolygonSkinFactory() { //ctor } ConvexPolygonSkinFactory::~ConvexPolygonSkinFactory() { //dtor } void ConvexPolygonSkinFactory::init(FactoryLoader* _loader, AbstractFactories* factories) { //ctor materialName = _loader->get<std::string>("materialName","player"); } Skin* ConvexPolygonSkinFactory::useFactory(FactoryParameters* _parameters) { std::vector<Vec2f> points = _parameters->getArray<Vec2f>("points",{{0,0},{1,1},{-2,1}}); Skin* skin = new ConvexPolygonSkin(&points[0],points.size()); skin->material = g_GraphicsManager.getMaterial(materialName.c_str()); return skin; }
[ "deek0146@gmail.com" ]
deek0146@gmail.com
b3163fa309cdb0f283840b7b848366cad5571ce8
7bee58d3d9240b0d0af96be9284ae1f97dcb0d51
/testing/opae-c/test_event_c.cpp
81b1748529684a68a744dd94edfa2557a0bb7fca
[ "BSD-3-Clause", "MIT" ]
permissive
kaankara/opae-sdk
65719c81c113dc66256a8b4f298a47d10604ad60
38af85fd850fca771c2d02fd4f09a32d284620d7
refs/heads/master
2020-04-08T19:31:49.399284
2019-01-30T13:26:29
2019-01-30T13:26:29
159,659,490
0
0
NOASSERTION
2018-11-29T11:59:39
2018-11-29T11:59:38
null
UTF-8
C++
false
false
8,944
cpp
// Copyright(c) 2018, Intel Corporation // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. extern "C" { #include <json-c/json.h> #include <uuid/uuid.h> #include "opae_int.h" #include "fpgad/config_int.h" #include "fpgad/log.h" #include "fpgad/srv.h" } #include <opae/fpga.h> #include "intel-fpga.h" #include <linux/ioctl.h> #include <array> #include <cstdlib> #include <cstring> #include <chrono> #include <thread> #include <unistd.h> #include "gtest/gtest.h" #include "test_system.h" using namespace opae::testing; class event_c_p : public ::testing::TestWithParam<std::string> { protected: event_c_p() : tokens_{{nullptr, nullptr}} {} virtual void SetUp() override { strcpy(tmpfpgad_log_, "tmpfpgad-XXXXXX.log"); strcpy(tmpfpgad_pid_, "tmpfpgad-XXXXXX.pid"); close(mkstemps(tmpfpgad_log_, 4)); close(mkstemps(tmpfpgad_pid_, 4)); ASSERT_TRUE(test_platform::exists(GetParam())); platform_ = test_platform::get(GetParam()); system_ = test_system::instance(); system_->initialize(); system_->prepare_syfs(platform_); ASSERT_EQ(fpgaInitialize(NULL), FPGA_OK); ASSERT_EQ(fpgaGetProperties(nullptr, &filter_), FPGA_OK); ASSERT_EQ(fpgaPropertiesSetObjectType(filter_, FPGA_ACCELERATOR), FPGA_OK); num_matches_ = 0; ASSERT_EQ(fpgaEnumerate(&filter_, 1, tokens_.data(), tokens_.size(), &num_matches_), FPGA_OK); EXPECT_GT(num_matches_, 0); accel_ = nullptr; ASSERT_EQ(fpgaOpen(tokens_[0], &accel_, 0), FPGA_OK); event_handle_ = nullptr; EXPECT_EQ(fpgaCreateEventHandle(&event_handle_), FPGA_OK); config_ = { .verbosity = 0, .poll_interval_usec = 100 * 1000, .daemon = 0, .directory = { 0, }, .logfile = { 0, }, .pidfile = { 0, }, .filemode = 0, .running = true, .socket = "/tmp/fpga_event_socket", .null_gbs = {0}, .num_null_gbs = 0, }; strcpy(config_.logfile, tmpfpgad_log_); strcpy(config_.pidfile, tmpfpgad_pid_); open_log(tmpfpgad_log_); fpgad_ = std::thread(server_thread, &config_); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } virtual void TearDown() override { config_.running = false; EXPECT_EQ(fpgaDestroyEventHandle(&event_handle_), FPGA_OK); EXPECT_EQ(fpgaDestroyProperties(&filter_), FPGA_OK); if (accel_) { EXPECT_EQ(fpgaClose(accel_), FPGA_OK); accel_ = nullptr; } for (auto &t : tokens_) { if (t) { EXPECT_EQ(fpgaDestroyToken(&t), FPGA_OK); t = nullptr; } } fpgad_.join(); close_log(); fpgaFinalize(); system_->finalize(); if (!::testing::Test::HasFatalFailure() && !::testing::Test::HasNonfatalFailure()) { unlink(tmpfpgad_log_); unlink(tmpfpgad_pid_); } } std::array<fpga_token, 2> tokens_; char tmpfpgad_log_[20]; char tmpfpgad_pid_[20]; struct config config_; std::thread fpgad_; fpga_properties filter_; fpga_handle accel_; fpga_event_handle event_handle_; test_platform platform_; uint32_t num_matches_; test_system *system_; }; /** * @test get_obj_err01 * @brief Test: fpgaGetOSObjectFromEventHandle * @details When fpgaGetOSObjectFromEventHandle is called prior<br> * to registering an event type,<br> * the fn returns FPGA_INVALID_PARAM.<br> */ TEST_P(event_c_p, get_obj_err01) { int fd = -1; EXPECT_EQ(fpgaGetOSObjectFromEventHandle(event_handle_, &fd), FPGA_INVALID_PARAM); } /** * @test get_obj_err02 * @brief Test: fpgaGetOSObjectFromEventHandle * @details When fpgaGetOSObjectFromEventHandle is called with a wrapped<br> * event handle that has a NULL opae_event_handle,<br> * the fn returns FPGA_INVALID_PARAM.<br> */ TEST_P(event_c_p, get_obj_err02) { EXPECT_EQ(fpgaRegisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_, 0), FPGA_OK); opae_wrapped_event_handle *wrapped_evt_handle = opae_validate_wrapped_event_handle(event_handle_); ASSERT_NE(wrapped_evt_handle, nullptr); fpga_event_handle eh = wrapped_evt_handle->opae_event_handle; wrapped_evt_handle->opae_event_handle = nullptr; int fd = -1; EXPECT_EQ(fpgaGetOSObjectFromEventHandle(event_handle_, &fd), FPGA_INVALID_PARAM); wrapped_evt_handle->opae_event_handle = eh; EXPECT_EQ(fpgaUnregisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_), FPGA_OK); } /** * @test get_obj_success * @brief Test: fpgaRegisterEvent, fpgaUnregisterEvent, fpgaGetOSObjectFromEventHandle * @details When fpgaGetOSObjectFromEventHandle is called after<br> * registering an event type,<br> * the fn returns FPGA_OK.<br> */ TEST_P(event_c_p, get_obj_success) { int fd = -1; EXPECT_EQ(fpgaRegisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_, 0), FPGA_OK); EXPECT_EQ(fpgaGetOSObjectFromEventHandle(event_handle_, &fd), FPGA_OK); EXPECT_EQ(fpgaUnregisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_), FPGA_OK); } /** * @test unreg_err01 * @brief Test: fpgaUnregisterEvent * @details When fpgaUnregisterEvent is called before<br> * registering an event type,<br> * the fn returns FPGA_INVALID_PARAM.<br> */ TEST_P(event_c_p, unreg_err01) { EXPECT_EQ(fpgaUnregisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_), FPGA_INVALID_PARAM); } /** * @test unreg_err02 * @brief Test: fpgaUnregisterEvent * @details When fpgaUnregisterEvent is called on a wrapped<br> * event handle object with a NULL opae_event_handle,<br> * the fn returns FPGA_INVALID_PARAM.<br> */ TEST_P(event_c_p, unreg_err02) { EXPECT_EQ(fpgaRegisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_, 0), FPGA_OK); opae_wrapped_event_handle *wrapped_evt_handle = opae_validate_wrapped_event_handle(event_handle_); ASSERT_NE(wrapped_evt_handle, nullptr); fpga_event_handle eh = wrapped_evt_handle->opae_event_handle; wrapped_evt_handle->opae_event_handle = nullptr; EXPECT_EQ(fpgaUnregisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_), FPGA_INVALID_PARAM); wrapped_evt_handle->opae_event_handle = eh; EXPECT_EQ(fpgaUnregisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_), FPGA_OK); } /** * @test destroy_err * @brief Test: fpgaDestroyEventHandle * @details When fpgaDestroyEventHandle is called on a wrapped<br> * event handle object with a NULL opae_event_handle,<br> * the fn returns FPGA_INVALID_PARAM.<br> */ TEST_P(event_c_p, destroy_err) { EXPECT_EQ(fpgaRegisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_, 0), FPGA_OK); opae_wrapped_event_handle *wrapped_evt_handle = opae_validate_wrapped_event_handle(event_handle_); ASSERT_NE(wrapped_evt_handle, nullptr); fpga_event_handle eh = wrapped_evt_handle->opae_event_handle; wrapped_evt_handle->opae_event_handle = nullptr; EXPECT_EQ(fpgaDestroyEventHandle(&event_handle_), FPGA_INVALID_PARAM); wrapped_evt_handle->opae_event_handle = eh; EXPECT_EQ(fpgaUnregisterEvent(accel_, FPGA_EVENT_ERROR, event_handle_), FPGA_OK); } INSTANTIATE_TEST_CASE_P(event_c, event_c_p, ::testing::ValuesIn(test_platform::platforms({})));
[ "noreply@github.com" ]
noreply@github.com
b7df86dd0579b9d1d2fb1078757ba92798e9c4b1
5793887005d7507a0a08dc82f389d8b8849bc4ed
/vendor/mediatek/proprietary/hardware/mtkcam/middleware/v1/LegacyPipeline/mfc/LegacyPipelineMFC.cpp
16bf8d9df886f88e85dd953e56c38f6f4910c129
[]
no_license
wangbichao/dual_camera_x
34b0e70bf2dc294c7fa077c637309498654430fa
fa4bf7e6d874adb7cf4c658235a8d24399f29f30
refs/heads/master
2020-04-05T13:40:56.119933
2017-07-10T13:57:33
2017-07-10T13:57:33
94,966,927
3
0
null
null
null
null
UTF-8
C++
false
false
15,246
cpp
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. */ /* MediaTek Inc. (C) 2015. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ #define LOG_TAG "MtkCam/LPipelineMFC" #include "LegacyPipelineMFC.h" #include "MyUtils.h" #include <mtkcam/middleware/v1/LegacyPipeline/NodeId.h> #include <mtkcam/middleware/v1/LegacyPipeline/StreamId.h> #include <mtkcam/utils/metadata/hal/mtk_platform_metadata_tag.h> #include <mtkcam/pipeline/hwnode/P1Node.h> #include <mtkcam/pipeline/hwnode/HDRNode.h> #include <mtkcam/pipeline/hwnode/MfllNode.h> #include <mtkcam/pipeline/hwnode/JpegNode.h> #include <mtkcam/utils/std/Log.h> #include <mtkcam/utils/std/Trace.h> #define FUNCTION_LOG_START CAM_LOGD("[%s] - E.", __FUNCTION__) #define FUNCTION_LOG_END CAM_LOGD("[%s] - X. ret: %d.", __FUNCTION__, ret) #define FUNCTION_LOG_END_MUM CAM_LOGD("[%s] - X.", __FUNCTION__) /** * For BSP, MFNR is not built-in feature */ #if MTKCAM_HAVE_MFB_SUPPORT typedef MfllNode MfllNode_T; #else typedef MFCNode MfllNode_T; #endif // --------------------------------------------------------------------------- using namespace NSCam; using namespace NSCam::Utils; using namespace NSCam::v1; using namespace NSCam::v1::NSLegacyPipeline; using namespace NSCam::v3; using namespace NSCam::v3::Utils; using namespace NSCam::v3::NSPipelineContext; using namespace NS3Av3; // --------------------------------------------------------------------------- #define MY_LOGV(fmt, arg...) CAM_LOGV("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGD(fmt, arg...) CAM_LOGD("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGI(fmt, arg...) CAM_LOGI("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGW(fmt, arg...) CAM_LOGW("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGE(fmt, arg...) CAM_LOGE("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGA(fmt, arg...) CAM_LOGA("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGF(fmt, arg...) CAM_LOGF("[%s] " fmt, __FUNCTION__, ##arg) #define MY_LOGV_IF(cond, ...) do { if ( (cond) ) { MY_LOGV(__VA_ARGS__); } }while(0) #define MY_LOGD_IF(cond, ...) do { if ( (cond) ) { MY_LOGD(__VA_ARGS__); } }while(0) #define MY_LOGI_IF(cond, ...) do { if ( (cond) ) { MY_LOGI(__VA_ARGS__); } }while(0) #define MY_LOGW_IF(cond, ...) do { if ( (cond) ) { MY_LOGW(__VA_ARGS__); } }while(0) #define MY_LOGE_IF(cond, ...) do { if ( (cond) ) { MY_LOGE(__VA_ARGS__); } }while(0) #define MY_LOGA_IF(cond, ...) do { if ( (cond) ) { MY_LOGA(__VA_ARGS__); } }while(0) #define MY_LOGF_IF(cond, ...) do { if ( (cond) ) { MY_LOGF(__VA_ARGS__); } }while(0) #define FUNC_START MY_LOGD("+") #define FUNC_END MY_LOGD("-") // --------------------------------------------------------------------------- struct LegacyPipelineUtil { static inline MVOID addStream( LegacyPipelineMFC * const lp, const sp<IMetaStreamInfo>& info) { if (info.get()) lp->setMetaStreamInfo(info); } static inline MVOID addStream( LegacyPipelineMFC * const lp, const sp<IImageStreamInfo>& info) { if (info.get()) lp->setImageStreamInfo(info); } }; static MVOID dumpConfiguration(const sp<Configuration>& config) { if (config == NULL) return; #define DUMP_STREAMINFO(name, msg) \ do { \ if (name.get()) \ msg.appendFormat("\n(%#" PRIxPTR ") %s", \ name->getStreamId(), \ name->getStreamName()); \ } while(0) String8 msg; msg.append("\ninput"); DUMP_STREAMINFO(config->controlMeta_App, msg); DUMP_STREAMINFO(config->controlMeta_Hal, msg); msg.append("\noutput (metadata)"); DUMP_STREAMINFO(config->resultMeta_P1_App, msg); DUMP_STREAMINFO(config->resultMeta_P1_Hal, msg); DUMP_STREAMINFO(config->resultMeta_MFC_App, msg); DUMP_STREAMINFO(config->resultMeta_MFC_Hal, msg); DUMP_STREAMINFO(config->resultMeta_Jpeg_App, msg); msg.append("\noutput (image)"); DUMP_STREAMINFO(config->imageInfo_imgoRaw, msg); DUMP_STREAMINFO(config->imageInfo_rrzoRaw, msg); DUMP_STREAMINFO(config->imageInfo_yuv00, msg); DUMP_STREAMINFO(config->imageInfo_yuvJpeg, msg); DUMP_STREAMINFO(config->imageInfo_yuvThumbnail, msg); DUMP_STREAMINFO(config->imageInfo_jpeg, msg); MY_LOGD("%s", msg.string()); #undef DUMP_STREAMINFO } static sp<HalMetaStreamBuffer> createMetaStreamBuffer( android::sp<IMetaStreamInfo>& streamInfo, const IMetadata& metadata, const MBOOL repeating __attribute__((unused))) { HalMetaStreamBuffer* pStreamBuffer = HalMetaStreamBuffer::Allocator(streamInfo.get())(metadata); return pStreamBuffer; } // --------------------------------------------------------------------------- LegacyPipelineMFC::LegacyPipelineMFC() { mTimestamp = TimeTool::getReadableTime(); } LegacyPipelineMFC::~LegacyPipelineMFC() { } MVOID LegacyPipelineMFC::setRequestBuilder( sp<RequestBuilder> const /*pRequestBuilder*/) { MY_LOGE("Unsupport setRequestBuilder without keyedvector input"); } MERROR LegacyPipelineMFC::waitUntilDrainedAndFlush() { CAM_TRACE_CALL(); if (mPipelineContext == NULL) { MY_LOGW("get pipeline context failed"); return UNKNOWN_ERROR; } MERROR err = OK; // P1 if (mConfiguration->configFlag & eNodeConfigP1) err |= drainAndFlushNode<P1Node>(eNODEID_P1Node); // HDR if (mConfiguration->configFlag & eNodeConfigHdr) err |= drainAndFlushNode<HDRNode>(eNODEID_HdrNode); // Mfll if (mConfiguration->configFlag & eNodeConfigMfll) err |= drainAndFlushNode<MfllNode_T>(eNODEID_MfllNode); // Jpeg if (mConfiguration->configFlag & eNodeConfigJpeg) err |= drainAndFlushNode<JpegNode>(eNODEID_JpegNode); return (err == OK) ? OK : INVALID_OPERATION; } MERROR LegacyPipelineMFC::submitSetting( MINT32 const requestNo, IMetadata& appMeta, IMetadata& halMeta, ResultSet* /*pResultSet*/) { FUNCTION_LOG_START; CAM_TRACE_CALL(); if ((mvRequestBuilder.isEmpty()) || (mPipelineContext == NULL)) { MY_LOGE_IF(mvRequestBuilder.isEmpty(), "request builder is not set yet"); MY_LOGE_IF(mPipelineContext == NULL, "pipeline contest is not set yet"); return NO_INIT; } // get timstamp (Epoch time) as an unique pipeline key if (!trySetMetadata<MINT32>(halMeta, MTK_PIPELINE_UNIQUE_KEY, mTimestamp)) MY_LOGE("set unique key failed"); // build and get pipeline frame sp<IPipelineFrame> frame = createRequest(requestNo, appMeta, halMeta); // queue pipeline frame into pipeline context if (frame.get()) { if (OK != mPipelineContext->queue(frame)) { MY_LOGE("queue pipeline frame failed"); } } else { MY_LOGE("build request(%d) failed", requestNo); } // clear frame frame.clear(); FUNCTION_LOG_END_MUM; return OK; } MERROR LegacyPipelineMFC::submitRequest( MINT32 const requestNo __attribute__((__unused__)), IMetadata& appMeta __attribute__((__unused__)), IMetadata& halMeta __attribute__((__unused__)), Vector<BufferSet> vDstStreams __attribute__((__unused__))) { CAM_TRACE_CALL(); MY_LOGE("implementation needed"); // TODO: implementation needed return INVALID_OPERATION; } MVOID LegacyPipelineMFC::onLastStrongRef( const void* id __attribute__((__unused__))) { CAM_TRACE_CALL(); // flush all currently in-flight captures and all buffers in the pipeline if (mPipelineContext.get()) { mPipelineContext->flush(); mPipelineContext->waitUntilDrained(); mPipelineContext.clear(); } if (mResultProcessor.get()) mResultProcessor->flush(); // remove reference mConfiguration.clear(); // empty vectors mvRequestBuilder.clear(); const size_t count = mvStreamBufferProvider.size(); for (size_t i = 0; i < count; i++) { if (mvStreamBufferProvider.editValueAt(i).get()) mvStreamBufferProvider.editValueAt(i)->flush(); } mvStreamBufferProvider.clear(); mvMetaStreamInfo.clear(); mvImageStreamInfo.clear(); } MVOID LegacyPipelineMFC::setConfiguration(const sp<Configuration>& config) { if (config == NULL) { MY_LOGE("configuration is null"); return; } mConfiguration = config; // input LegacyPipelineUtil::addStream(this, config->controlMeta_App); LegacyPipelineUtil::addStream(this, config->controlMeta_Hal); // output (metadata) LegacyPipelineUtil::addStream(this, config->resultMeta_P1_App); LegacyPipelineUtil::addStream(this, config->resultMeta_P1_App); LegacyPipelineUtil::addStream(this, config->resultMeta_P1_Hal); LegacyPipelineUtil::addStream(this, config->resultMeta_MFC_App); LegacyPipelineUtil::addStream(this, config->resultMeta_MFC_Hal); LegacyPipelineUtil::addStream(this, config->resultMeta_Jpeg_App); // output (image) LegacyPipelineUtil::addStream(this, config->imageInfo_imgoRaw); LegacyPipelineUtil::addStream(this, config->imageInfo_rrzoRaw); LegacyPipelineUtil::addStream(this, config->imageInfo_yuv00); LegacyPipelineUtil::addStream(this, config->imageInfo_yuvJpeg); LegacyPipelineUtil::addStream(this, config->imageInfo_yuvThumbnail); LegacyPipelineUtil::addStream(this, config->imageInfo_jpeg); } MVOID LegacyPipelineMFC::setImageStreamInfo( const sp<IImageStreamInfo>& pImageStreamInfo) { if (pImageStreamInfo == NULL) { MY_LOGE("ImageStreamInfo is NULL"); return; } mvImageStreamInfo.add(pImageStreamInfo->getStreamId(), pImageStreamInfo); } MVOID LegacyPipelineMFC::setMetaStreamInfo( const sp<IMetaStreamInfo>& pMetaStreamInfo) { if (pMetaStreamInfo == NULL) { MY_LOGE("MetaStreamInfo is NULL"); return; } mvMetaStreamInfo.add(pMetaStreamInfo->getStreamId(), pMetaStreamInfo); } MVOID LegacyPipelineMFC::setStreamBufferProvider( const sp<StreamBufferProvider>& pStreamBufferProvider) { if (pStreamBufferProvider == NULL) { MY_LOGE("StreamBufferProvider is NULL"); return; } mvStreamBufferProvider.add( pStreamBufferProvider->queryImageStreamInfo()->getStreamId(), pStreamBufferProvider); } sp<IPipelineFrame> LegacyPipelineMFC::createRequest( const MINT32 requestNo, const IMetadata& appMeta, const IMetadata& halMeta) { FUNCTION_LOG_START; CAM_TRACE_CALL(); if (requestNo < 0) { MY_LOGE("invalid request number(%d)", requestNo); return NULL; } // NOTE: the request number is used to judge whether to // create a main request (0) or a subrequest (> 0) MBOOL isMainRequest = (requestNo == 0) ? MTRUE : MFALSE; MY_LOGD("create %srequest", isMainRequest ? "main " : "sub"); // build request and return the corresponding pipeline frame sp<RequestBuilder> requestBuilder = mvRequestBuilder[isMainRequest ? 0 : 1]; // create meta stream buffers and set them into request builder { sp<IMetaStreamBuffer> appMetaStreamBuffer; sp<HalMetaStreamBuffer> halMetaStreamBuffer; appMetaStreamBuffer = createMetaStreamBuffer(mConfiguration->controlMeta_App, appMeta, false); halMetaStreamBuffer = createMetaStreamBuffer(mConfiguration->controlMeta_Hal, halMeta, false); // set meta stream buffer requestBuilder->setMetaStreamBuffer( mConfiguration->controlMeta_App->getStreamId(), appMetaStreamBuffer); requestBuilder->setMetaStreamBuffer( mConfiguration->controlMeta_Hal->getStreamId(), halMetaStreamBuffer); } dumpConfiguration(mConfiguration); FUNCTION_LOG_END_MUM; return requestBuilder->build(requestNo, mPipelineContext); } template <typename TNode> MERROR LegacyPipelineMFC::drainAndFlushNode(const NodeId_T nodeId) { CAM_TRACE_CALL(); sp< NodeActor< TNode > > nodeActor; // query node actor MERROR err = mPipelineContext->queryNodeActor(nodeId, nodeActor); if ((err != OK) || (nodeActor == NULL)) { MY_LOGW("query node(%#" PRIxPTR ") failed(%s)", nodeId, strerror(-err)); return NAME_NOT_FOUND; } // drain node err = mPipelineContext->waitUntilNodeDrained(nodeId); if (err != OK) { MY_LOGW("drain node(%#" PRIxPTR ") failed(%s)", nodeId, strerror(-err)); return err; } // flush pipeline node IPipelineNode* node = nodeActor->getNode(); if (node == NULL) { MY_LOGW("get node(%d) failed(%s)", nodeId, strerror(-err)); return UNKNOWN_ERROR; } if (node->flush() != OK) { MY_LOGW("flush node(%#" PRIxPTR ") failed(%s)", nodeId, strerror(-err)); return err; } return OK; }
[ "wangbichao@live.com" ]
wangbichao@live.com
f60c4ecdf583f8e55931f1fc66093acd383f4481
586cb1bbd3c37088fe973ede4dbdecc360f1cf75
/Kernel/VM/InodeVMObject.cpp
eb8f9d39f684dfb1470f20de4bcc3cb2cf610bc2
[ "BSD-2-Clause" ]
permissive
OhadRau/serenity
be9a24f93528fe639081ebeaf4d228eb07e43645
56657f1ea7df7c6884196414c671a587df4f8e59
refs/heads/master
2020-11-25T06:11:56.372506
2019-12-17T04:46:39
2019-12-17T04:46:39
228,534,299
0
0
BSD-2-Clause
2019-12-17T04:44:18
2019-12-17T04:44:17
null
UTF-8
C++
false
false
3,024
cpp
#include <Kernel/FileSystem/Inode.h> #include <Kernel/VM/InodeVMObject.h> #include <Kernel/VM/MemoryManager.h> #include <Kernel/VM/Region.h> NonnullRefPtr<InodeVMObject> InodeVMObject::create_with_inode(Inode& inode) { InterruptDisabler disabler; if (inode.vmobject()) return *inode.vmobject(); auto vmo = adopt(*new InodeVMObject(inode)); vmo->inode().set_vmo(*vmo); return vmo; } NonnullRefPtr<VMObject> InodeVMObject::clone() { return adopt(*new InodeVMObject(*this)); } InodeVMObject::InodeVMObject(Inode& inode) : VMObject(inode.size()) , m_inode(inode) { } InodeVMObject::InodeVMObject(const InodeVMObject& other) : VMObject(other) , m_inode(other.m_inode) { } InodeVMObject::~InodeVMObject() { ASSERT(inode().vmobject() == this); } void InodeVMObject::inode_size_changed(Badge<Inode>, size_t old_size, size_t new_size) { dbgprintf("VMObject::inode_size_changed: {%u:%u} %u -> %u\n", m_inode->fsid(), m_inode->index(), old_size, new_size); InterruptDisabler disabler; auto new_page_count = PAGE_ROUND_UP(new_size) / PAGE_SIZE; m_physical_pages.resize(new_page_count); // FIXME: Consolidate with inode_contents_changed() so we only do a single walk. for_each_region([](auto& region) { region.remap(); }); } void InodeVMObject::inode_contents_changed(Badge<Inode>, off_t offset, ssize_t size, const u8* data) { (void)size; (void)data; InterruptDisabler disabler; ASSERT(offset >= 0); // FIXME: Only invalidate the parts that actually changed. for (auto& physical_page : m_physical_pages) physical_page = nullptr; #if 0 size_t current_offset = offset; size_t remaining_bytes = size; const u8* data_ptr = data; auto to_page_index = [] (size_t offset) -> size_t { return offset / PAGE_SIZE; }; if (current_offset & PAGE_MASK) { size_t page_index = to_page_index(current_offset); size_t bytes_to_copy = min(size, PAGE_SIZE - (current_offset & PAGE_MASK)); if (m_physical_pages[page_index]) { auto* ptr = MM.quickmap_page(*m_physical_pages[page_index]); memcpy(ptr, data_ptr, bytes_to_copy); MM.unquickmap_page(); } current_offset += bytes_to_copy; data += bytes_to_copy; remaining_bytes -= bytes_to_copy; } for (size_t page_index = to_page_index(current_offset); page_index < m_physical_pages.size(); ++page_index) { size_t bytes_to_copy = PAGE_SIZE - (current_offset & PAGE_MASK); if (m_physical_pages[page_index]) { auto* ptr = MM.quickmap_page(*m_physical_pages[page_index]); memcpy(ptr, data_ptr, bytes_to_copy); MM.unquickmap_page(); } current_offset += bytes_to_copy; data += bytes_to_copy; } #endif // FIXME: Consolidate with inode_size_changed() so we only do a single walk. for_each_region([](auto& region) { region.remap(); }); }
[ "awesomekling@gmail.com" ]
awesomekling@gmail.com
d28c4e6fae341ba7b4c686dc0cc555e27f9ca495
9e52c7284e4c969edd192420dc0c53025c885c12
/ARACrypt.cpp
ee2cc1903ffaa432bc3e5d24f76d264a5ae06979
[ "Unlicense" ]
permissive
Jaguarhl/Fallout--The-X-Project
6f1128bfc4cf3e27a2908eda77fbdce89b740bd1
e4eb4119afda0bd9a3128dba8f787674b31457a8
refs/heads/master
2021-01-20T17:20:48.197644
2017-06-07T18:55:52
2017-06-07T18:55:52
64,749,836
19
1
null
null
null
null
UTF-8
C++
false
false
9,432
cpp
// ARACrypt.cpp : implementation file // // Note: A Special Thanks to Mr. Warren Ward for his Sept. 1998 CUJ article: // "Stream Encryption" Copyright (c) 1998 by Warren Ward #include "NukeDX.h" #include "ARACrypt.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // ARACrypt ARACrypt::ARACrypt() : // Initialize the shift registers to non-zero // values. If the shift register contains all // 0's when the generator starts, it will not // produce a usable sequence of bits. The // numbers used here have no special features // except for being non-zero. m_LFSR_A( 0x13579BDF ), m_LFSR_B( 0x2468ACE0 ), m_LFSR_C( 0xFDB97531 ), // Initialize the masks to magic numbers. // These values are primitive polynomials mod // 2, described in Applied Cryptography, // second edition, by Bruce Schneier (New York: // John Wiley and Sons, 1994). See Chapter 15: // Random Sequence Generators and Stream // Ciphers, particularly the discussion on // Linear Feedback Shift Registers. // // The primitive polynomials used here are: // Register A: ( 32, 7, 6, 2, 0 ) // Register B: ( 31, 6, 0 ) // Register C: ( 29, 2, 0 ) // // The bits that must be set to "1" in the // XOR masks are: // Register A: ( 31, 6, 5, 1 ) // Register B: ( 30, 5 ) // Register C: ( 28, 1 ) // // Developer's Note // DO NOT CHANGE THESE NUMBERS WITHOUT // REFERRING TO THE DISCUSSION IN SCHNEIER'S // BOOK. They are some of very few // near-32-bit values that will act as // maximal-length random generators. m_Mask_A( 0x80000062 ), m_Mask_B( 0x40000020 ), m_Mask_C( 0x10000002 ), // Set up LFSR "rotate" masks. // These masks limit the number of bits // used in the shift registers. Each one // provides the most-significant bit (MSB) // when performing a "rotate" operation. Here // are the shift register sizes and the byte // mask needed to place a "1" bit in the MSB // for Rotate-1, and a zero in the MSB for // Rotate-0. All the shift registers are stored // in an unsigned 32-bit integer, but these // masks effectively make the registers 32 // bits (A), 31 bits (B), and 29 bits (C). // // Bit | 3 2 1 0 // Pos'n | 1098 7654 3210 9876 5432 1098 7654 3210 // ===== | ========================================== // Value | 8421-8421 8421-8421 8421-8421 8421-8421 // ===== | ========================================== // | // A-Rot0 | 0111 1111 1111 1111 1111 1111 1111 1111 // A-Rot1 | 1000 0000 0000 0000 0000 0000 0000 0000 // | // B-Rot0 | 0011 1111 1111 1111 1111 1111 1111 1111 // B-Rot1 | 1100 0000 0000 0000 0000 0000 0000 0000 // | // C-Rot0 | 0000 1111 1111 1111 1111 1111 1111 1111 // C-Rot1 | 1111 0000 0000 0000 0000 0000 0000 0000 // // // Reg Size MSB Position Rotate-0 Mask Rotate-1 Mask // A 32 31 0x7FFFFFFF 0x80000000 // B 31 30 0x3FFFFFFF 0xC0000000 // C 29 28 0x0FFFFFFF 0xF0000000 // m_Rot0_A( 0x7FFFFFFF ), m_Rot0_B( 0x3FFFFFFF ), m_Rot0_C( 0x0FFFFFFF ), m_Rot1_A( 0x80000000 ), m_Rot1_B( 0xC0000000 ), m_Rot1_C( 0xF0000000 ) { m_csKey = _T(""); } // Everything is on the frame. ARACrypt::~ARACrypt() { } ///////////////////////////////////////////////////////////////////////////// // ARACrypt operations void ARACrypt::SetKey(LPCTSTR csKey) { CString csSeed; m_csKey = csKey; if (m_csKey.IsEmpty()) { //Put some really outrageous characters in seed just in case. csSeed = "\x43\xC8\x21\xD3\xF4\xB3\x10\x27\x09\xAA\x18\x56"; //TO DO: Add Message to Event Log and/or window when there is one. // AfxMessageBox("WARNING: Missing Pass Phrase. Default in effect!"); } else { csSeed = m_csKey; } // Make sure seed is at least 12 bytes long . int nIdx = 0; for (nIdx = 0; csSeed.GetLength() < 12; nIdx++) { csSeed += csSeed[nIdx]; } // LFSR A, B, and C get the first, second, and // third four bytes of the seed, respectively. for (nIdx = 0; nIdx < 4; nIdx++) { m_LFSR_A = ((m_LFSR_A <<= 8) | ((unsigned long int) csSeed[nIdx + 0])); m_LFSR_B = (( m_LFSR_B <<= 8) | ((unsigned long int) csSeed[nIdx + 4])); m_LFSR_C = (( m_LFSR_C <<= 8) | ((unsigned long int) csSeed[nIdx + 8])); } // If any LFSR contains 0x00000000, load a // non-zero default value instead. There is // no particular "good" value. The ones here // were selected to be distinctive during // testing and debugging. if (0x00000000 == m_LFSR_A) m_LFSR_A = 0x13579BDF; if (0x00000000 == m_LFSR_B) m_LFSR_B = 0x2468ACE0; if (0x00000000 == m_LFSR_C) m_LFSR_C = 0xFDB97531; return; } void ARACrypt::GetKey(CString& csKey) { csKey = m_csKey; } //*********************************************** // ARACrypt::TransformChar //*********************************************** // Transform a single character. If it is // plaintext, it will be encrypted. If it is // encrypted, and if the LFSRs are in the same // state as when it was encrypted (that is, the // same keys loaded into them and the same number // of calls to TransformChar after the keys // were loaded), the character will be decrypted // to its original value. // // DEVELOPER'S NOTE // This code contains corrections to the LFSR // operations that supercede the code examples // in Applied Cryptography (first edition, up to // at least the 4th printing, and second edition, // up to at least the 6th printing). More recent // errata sheets may show the corrections. //*********************************************** void ARACrypt::TransformChar(unsigned char& cTarget) { int Counter = 0; unsigned char Crypto = '\0'; unsigned long int Out_B = (m_LFSR_B & 0x00000001); unsigned long int Out_C = (m_LFSR_C & 0x00000001); // Cycle the LFSRs eight times to get eight // pseudo-random bits. Assemble these into // a single random character (Crypto). for (Counter = 0; Counter < 8; Counter++) { if (m_LFSR_A & 0x00000001) { // The least-significant bit of LFSR // A is "1". XOR LFSR A with its // feedback mask. m_LFSR_A = (((m_LFSR_A ^ m_Mask_A) >> 1) | m_Rot1_A); // Clock shift register B once. if ( m_LFSR_B & 0x00000001 ) { // The LSB of LFSR B is "1". XOR // LFSR B with its feedback mask. m_LFSR_B = (((m_LFSR_B ^ m_Mask_B) >> 1) | m_Rot1_B); Out_B = 0x00000001; } else { // The LSB of LFSR B is "0". Rotate // the LFSR contents once. m_LFSR_B = (( m_LFSR_B >> 1) & m_Rot0_B); Out_B = 0x00000000; } } else { // The LSB of LFSR A is "0". // Rotate the LFSR contents once. m_LFSR_A = (( m_LFSR_A >> 1) & m_Rot0_A); // Clock shift register C once. if ( m_LFSR_C & 0x00000001 ) { // The LSB of LFSR C is "1". // XOR LFSR C with its feedback mask. m_LFSR_C = ((( m_LFSR_C ^ m_Mask_C) >> 1) | m_Rot1_C); Out_C = 0x00000001; } else { // The LSB of LFSR C is "0". Rotate // the LFSR contents once. m_LFSR_C = ((m_LFSR_C >> 1) & m_Rot0_C); Out_C = 0x00000000; } } // XOR the output from LFSRs B and C and // rotate it into the right bit of Crypto. //The follwing conversion warning is unecessary here as //'loss of data' is a side effect and harmless. #pragma warning(disable : 4244) Crypto = ((Crypto << 1) | (Out_B ^ Out_C)); #pragma warning(default : 4244) } // XOR the resulting character with the // input character to encrypt/decrypt it. //The follwing conversion warning not necessary here either. //The 'loss of data', so to speak is a side effect and harmless. #pragma warning(disable : 4244) cTarget = ( cTarget ^ Crypto ); if (cTarget == NULL) //No nulls allowed here. There is cTarget = ( cTarget ^ Crypto ); //no working std::string available. #pragma warning( default : 4244 ) return; } //*********************************************** // ARACrypt::TransformString //*********************************************** // Encrypt or decrypt a standard string in place. // The string to transform is passed in as // Target. //*********************************************** void ARACrypt::TransformString(LPCTSTR csKey, CString& csTarget) { // Reset the shift registers. SetKey(csKey); // Transform each character in the string. // // DEVELOPER'S NOTE // ========================================== // DO NOT TREAT THE OUTPUT STRING AS A NULL- // TERMINATED STRING. // ========================================== // The transformation process can create '\0' // characters in the output string. Always // use the length() method to retrieve the full // string when it has been transformed. // bek NOTE: The above note does not apply to this // implementation of Warren Ward's method. // ARACrypt knows about NULLs and transforms them // into XOR NULLs so the entire result can be // treated as a 'normal' NULL terminated string. int nLen = csTarget.GetLength(); for (int nPos = 0; nPos < nLen; nPos++) { //The follwing conversion warning not necessary here either. //The 'loss of data', so to speak is a side effect and harmless. #pragma warning(disable : 4244) unsigned char cBuff = csTarget.GetAt(nPos); TransformChar((unsigned char&) cBuff); csTarget.SetAt(nPos, cBuff); } return; }
[ "dek.alpha@gmail.com" ]
dek.alpha@gmail.com
c6472bfd4026cfa3f8680582a908c2586c8178c2
c54e2d37b75177ef9aeff6913b4be7e6ea8f8101
/include/WSMath.h
8c7481f10ff9648c641e026b7e932ae7734e11c7
[]
no_license
CGTGPY3G1/TheWeiSungEngine
ab321eec941b3a83acd22b157fc65791ff0b5c65
ca497e663166148135dbaaba70cb082d58d50595
refs/heads/master
2021-09-27T01:07:45.442601
2018-11-05T05:29:23
2018-11-05T05:29:23
73,290,451
0
0
null
null
null
null
UTF-8
C++
false
false
241
h
#pragma once #ifndef WS_MATH_H #define WS_MATH_H namespace WeiSungEngine { class WSMath { public: static float PI(); static float TAU(); static float RadiansToDegrees(); static float DegreesToRadians(); }; } #endif // !WS_MATH_H
[ "b00289996@studentmail.uws.ac.uk" ]
b00289996@studentmail.uws.ac.uk
bf52c70ec147f2f0d4c5ca50787f5b49dbe0db99
1688e83af83afff94d1e38123e382b40bd0528c3
/code/lucky/widget/mytablemodel.cpp
ca8201016fcd39d58f2e060ecfec9d6c1aba9490
[]
no_license
wangsidi/hengsheng-client-include-deploy-
5e48081e9bd6404dc60d962b90e98c4ee23f4edb
914577ee5a0a49136ef26cdec466cb123d421119
refs/heads/main
2023-03-29T04:32:01.384645
2021-03-26T16:46:36
2021-03-26T16:46:36
351,836,390
0
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
#include "mytablemodel.h" MyTableModel::MyTableModel(): QStandardItemModel() { } QVariant MyTableModel::data(const QModelIndex &index, int role) const { //获取处理role QVariant value = QStandardItemModel::data(index, role); //判断role switch (role) { case Qt::TextAlignmentRole: { //设置居中 value = Qt::AlignCenter; //返回 return value; } } //如果是文字布局处理项 //其他直接返回 return value; }
[ "noreply@github.com" ]
noreply@github.com
74624535f7e4c4200cad2dc5f432f2c0e87fa82c
9005c48f442c6317966c8c10fee6310a2c76bdd5
/src/singletri/singletri.cpp
39b6c52cbe7932507aead6be46a1e914836fca18
[]
no_license
rveens/sb6code
7d2ddac3849fd3a67b35ab978ad56df91404f994
8b9a81db6603d0ca67e43c58c680ffe603a91f74
refs/heads/master
2021-01-17T05:28:29.035985
2013-12-26T16:42:19
2013-12-26T16:42:19
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,118
cpp
/* * Copyright © 2012-2013 Graham Sellers * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <sb6.h> class singlepoint_app : public sb6::application { void init() { static const char title[] = "OpenGL SuperBible - Single Triangle"; sb6::application::init(); memcpy(info.title, title, sizeof(title)); } virtual void startup() { static const char * vs_source[] = { "#version 430 core \n" " \n" "void main(void) \n" "{ \n" " const vec4 vertices[] = vec4[](vec4( 0.25, -0.25, 0.5, 1.0), \n" " vec4(-0.25, -0.25, 0.5, 1.0), \n" " vec4( 0.25, 0.25, 0.5, 1.0)); \n" " \n" " gl_Position = vertices[gl_VertexID]; \n" "} \n" }; static const char * fs_source[] = { "#version 420 core \n" " \n" "out vec4 color; \n" " \n" "void main(void) \n" "{ \n" " color = vec4(0.0, 0.8, 1.0, 1.0); \n" "} \n" }; program = glCreateProgram(); GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, vs_source, NULL); glCompileShader(vs); GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, fs_source, NULL); glCompileShader(fs); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glGenVertexArrays(1, &vao); glBindVertexArray(vao); } virtual void render(double currentTime) { static const GLfloat green[] = { 0.0f, 0.25f, 0.0f, 1.0f }; glClearBufferfv(GL_COLOR, 0, green); glUseProgram(program); glDrawArrays(GL_TRIANGLES, 0, 3); } virtual void shutdown() { glDeleteVertexArrays(1, &vao); glDeleteProgram(program); } private: GLuint program; GLuint vao; }; DECLARE_MAIN(singlepoint_app)
[ "rickveens92@gmail.com" ]
rickveens92@gmail.com
624885d4f3c484f315422772f1b4dc8018c9feb2
d6b4bdf418ae6ab89b721a79f198de812311c783
/vod/include/tencentcloud/vod/v20180717/model/DescribeVodDomainsRequest.h
df0978be48d63ad9453a7b2f3f52a61030b83aa8
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
7,337
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_VOD_V20180717_MODEL_DESCRIBEVODDOMAINSREQUEST_H_ #define TENCENTCLOUD_VOD_V20180717_MODEL_DESCRIBEVODDOMAINSREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Vod { namespace V20180717 { namespace Model { /** * DescribeVodDomains request structure. */ class DescribeVodDomainsRequest : public AbstractModel { public: DescribeVodDomainsRequest(); ~DescribeVodDomainsRequest() = default; std::string ToJsonString() const; /** * 获取List of domain names. If this parameter is left empty, all domain names will be listed. <li>Maximum number of domain names listed: 20</li> * @return Domains List of domain names. If this parameter is left empty, all domain names will be listed. <li>Maximum number of domain names listed: 20</li> * */ std::vector<std::string> GetDomains() const; /** * 设置List of domain names. If this parameter is left empty, all domain names will be listed. <li>Maximum number of domain names listed: 20</li> * @param _domains List of domain names. If this parameter is left empty, all domain names will be listed. <li>Maximum number of domain names listed: 20</li> * */ void SetDomains(const std::vector<std::string>& _domains); /** * 判断参数 Domains 是否已赋值 * @return Domains 是否已赋值 * */ bool DomainsHasBeenSet() const; /** * 获取Maximum results to return for pulling paginated queries. Default value: 20 * @return Limit Maximum results to return for pulling paginated queries. Default value: 20 * */ uint64_t GetLimit() const; /** * 设置Maximum results to return for pulling paginated queries. Default value: 20 * @param _limit Maximum results to return for pulling paginated queries. Default value: 20 * */ void SetLimit(const uint64_t& _limit); /** * 判断参数 Limit 是否已赋值 * @return Limit 是否已赋值 * */ bool LimitHasBeenSet() const; /** * 获取Page number offset from the beginning of paginated queries. Default value: 0 * @return Offset Page number offset from the beginning of paginated queries. Default value: 0 * */ uint64_t GetOffset() const; /** * 设置Page number offset from the beginning of paginated queries. Default value: 0 * @param _offset Page number offset from the beginning of paginated queries. Default value: 0 * */ void SetOffset(const uint64_t& _offset); /** * 判断参数 Offset 是否已赋值 * @return Offset 是否已赋值 * */ bool OffsetHasBeenSet() const; /** * 获取VOD [subapplication](https://intl.cloud.tencent.com/document/product/266/14574?from_cn_redirect=1) ID. If you need to access a resource in a subapplication, set this parameter to the subapplication ID; otherwise, leave it empty. * @return SubAppId VOD [subapplication](https://intl.cloud.tencent.com/document/product/266/14574?from_cn_redirect=1) ID. If you need to access a resource in a subapplication, set this parameter to the subapplication ID; otherwise, leave it empty. * */ uint64_t GetSubAppId() const; /** * 设置VOD [subapplication](https://intl.cloud.tencent.com/document/product/266/14574?from_cn_redirect=1) ID. If you need to access a resource in a subapplication, set this parameter to the subapplication ID; otherwise, leave it empty. * @param _subAppId VOD [subapplication](https://intl.cloud.tencent.com/document/product/266/14574?from_cn_redirect=1) ID. If you need to access a resource in a subapplication, set this parameter to the subapplication ID; otherwise, leave it empty. * */ void SetSubAppId(const uint64_t& _subAppId); /** * 判断参数 SubAppId 是否已赋值 * @return SubAppId 是否已赋值 * */ bool SubAppIdHasBeenSet() const; private: /** * List of domain names. If this parameter is left empty, all domain names will be listed. <li>Maximum number of domain names listed: 20</li> */ std::vector<std::string> m_domains; bool m_domainsHasBeenSet; /** * Maximum results to return for pulling paginated queries. Default value: 20 */ uint64_t m_limit; bool m_limitHasBeenSet; /** * Page number offset from the beginning of paginated queries. Default value: 0 */ uint64_t m_offset; bool m_offsetHasBeenSet; /** * VOD [subapplication](https://intl.cloud.tencent.com/document/product/266/14574?from_cn_redirect=1) ID. If you need to access a resource in a subapplication, set this parameter to the subapplication ID; otherwise, leave it empty. */ uint64_t m_subAppId; bool m_subAppIdHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_VOD_V20180717_MODEL_DESCRIBEVODDOMAINSREQUEST_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
6d14625cf495e6975c86350c5144227f060a1d5f
c125969ec6203b548d642c4cf3596702f87fd3d8
/line_searches/nonmonotone.h
2fe67274cbe270216fb8499ea1e0b21c5aaaf831
[]
no_license
todorovicnenad/NumericalOptimization
2c0b9c73d09f84cbbaf84dcdf94734d7797761a9
7b6d7bdffdfd2d4ad060ecb395d871b9351f4b75
refs/heads/master
2022-12-25T01:29:16.295232
2020-10-04T17:17:26
2020-10-04T17:17:26
299,573,983
0
0
null
null
null
null
UTF-8
C++
false
false
2,778
h
#ifndef NONMONOTONE_H #define NONMONOTONE_H #include "base_line_search.h" #include<vector> namespace opt { namespace line_search { template <class real> class nonmonotone : public base_line_search<real> { private: real steepness; real initial_step; int M; public: nonmonotone(std::map<std::string, real>& params) { std::map<std::string, real> p; p["steepness"] = 1e-4; p["initial_step"] = 1; p["M"] = 10; this->rest(p, params); steepness = p["steepness"]; initial_step = p["initial_step"]; M = p["M"]; params = p; } real operator()(function::function<real>& f, arma::Col<real>& x, arma::Col<real>& d) { this->iter_count = 0; real f0 = this->current_f_val; real pad = arma::dot(this->current_g_val, d); real a_curr = this->f_values.size() >= 2 ? this->compute_initial_step(this->f_values.end()[-1], this->f_values.end()[-2], this->current_g_val, d) : initial_step; real f_curr, f_prev, a_prev; f_curr = f(x + d * a_curr); vector<real> curr_values; curr_values.push_back(f0); curr_values.push_back(f_curr); real maxval = f_curr > f0 ? f_curr : f0; while (f_curr > maxval + steepness * pad * a_curr) { ++this->iter_count; real a_new; if (this->iter_count == 1) { a_new = pad * a_curr * a_curr / 2 / (f0 - f_curr + pad * a_curr); } else { real cubic = a_prev * a_prev * (f_curr - f0); cubic -= a_curr * a_prev * a_prev * pad; cubic += a_curr * a_curr * (f0 - f_prev + a_prev * pad); cubic /= a_curr * a_curr * (a_curr - a_prev) * a_prev * a_prev; real quadr = -cubic * a_curr * a_curr * a_curr - f0 + f_curr - a_curr * pad; quadr /= a_curr * a_curr; a_new = (-quadr + sqrt(quadr * quadr - 3 * cubic * pad)) / (3 * cubic); } a_prev = a_curr; a_curr = a_new; f_prev = f_curr; f_curr = f(x + a_new * d); curr_values.push_back(f_curr); // calculating new maximum of last M iterations and erasing first value if needed if (curr_values.size() > M) // f_values should not contain values from more then last M iterations { curr_values.erase(f_values.begin()); if (curr_values.end()[0] > maxval) { maxval = curr_values.end()[0]; } else { maxval = curr_values[0]; for (size_t i = 1; i < curr_values.size(); i++) if (curr_values[i] > maxval)maxval = curr_values[i]; } } else { if (curr_values.end()[0] > maxval)maxval = curr_values.end()[0]; } } this->current_f_val = f_curr; this->current_g_val = f.gradient(x + d * a_curr); return a_curr; } }; } } #endif //NONMONOTONE_H
[ "nesafirst@gmail.com" ]
nesafirst@gmail.com
c4e0fa6c6a2186b1872fb6b10beeb279b96e64ba
42e988b3a0fae9526e10962568d6e3532351afd8
/system/classification.cpp
a7048e47a915c70850202bbfc54662e34461fb0a
[]
no_license
rafaelalmeida/poc
d2e82aadda058c68fae79a0c28e48fd31feb03cc
a980d5757d2dba5647528250619e638868229f47
refs/heads/master
2021-01-17T06:06:38.554289
2014-11-26T17:56:37
2014-11-26T17:56:37
22,820,999
0
0
null
null
null
null
UTF-8
C++
false
false
5,342
cpp
#include "classification.h" using namespace cv; using namespace std; using namespace classification; using namespace segmentation; Classifier::Classifier(ClassifierEngine engine, VISImage *vis, Descriptor *descriptor) : _engine(engine), _vis(vis), _descriptor(descriptor), _type(VIS) { } Classifier::Classifier(ClassifierEngine engine, LWIRImage *lwir, Descriptor *descriptor) : _engine(engine), _lwir(lwir), _descriptor(descriptor), _type(LWIR) { } void Classifier::train(Mat labels, Segmentation S) { // Get features Mat features = S.getDescription(_descriptor->getID()); // Train the correct classifier _swatchTraining.start(); if (_engine == SVM) { CvSVMParams params; params.svm_type = CvSVM::C_SVC; params.kernel_type = CvSVM::LINEAR; params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6); _svm.train(features, labels, Mat(), Mat(), params); } else if (_engine == NBC) { _nbc.train(features, labels, Mat(), Mat(), false); } else if (_engine == KNN) { _knn.train(features, labels); } else if (_engine == DTREE) { CvDTreeParams params; // Initialize with default parameters params.cv_folds = 1; // Disable k-fold cross-validation params.min_sample_count = DTREE_MIN_SAMPLE_SIZE; // Include the class probabilities, if available vector<float> *prob = NULL; float probF[CLASS_COUNT]; if (_trainingMap != NULL) { prob = _trainingMap->classProbabilities(); int idx = 0; for (auto p : *prob) { probF[idx++] = p; } params.priors = probF; } _dtree.train(features, CV_ROW_SAMPLE, labels, Mat(), Mat(), Mat(), Mat(), params); // Free class probabilities vector if (prob != NULL) { delete prob; } } else if (_engine == GBT) { _gbtrees.train(features, CV_ROW_SAMPLE, labels); } else if (_engine == RTREES) { _rtrees.train(features, CV_ROW_SAMPLE, labels); } else if (_engine == ERTREES) { _ertrees.train(features, CV_ROW_SAMPLE, labels); } else if (_engine == MLP) { Mat layers(3, 1, CV_32S); layers.at<int>(0, 0) = features.cols; layers.at<int>(1, 0) = MLP_HIDDEN_LAYER_SIZE; layers.at<int>(2, 0) = CLASS_COUNT; // Since MLPs can't handle categorical data, we encode it as a vector v // of CLASS_COUNT elements. If the class is c, then v(c) = 1 and all // other elements of v are 0. Mat encodedLabels = Mat::zeros(labels.rows, CLASS_COUNT, CV_32F); for (int i = 0; i < labels.rows; i++) { int c = (int) (labels.at<float>(i, 0) - 1); // Classes are 1-index encodedLabels.at<float>(i, c) = 1.0; } _mlp.create(layers, CvANN_MLP::SIGMOID_SYM); _mlp.train(features, encodedLabels, Mat()); } else { FATAL_ERROR("Unknown classifier engine"); } _swatchTraining.stop(); } Mat Classifier::classify(Region region) { // Get features Mat features = region.getDescription(_descriptor->getID()); // Predict the class _swatchClassification.start(); float theClass; if (_engine == SVM) { theClass = _svm.predict(features); } else if (_engine == NBC) { theClass = _nbc.predict(features); } else if (_engine == KNN) { theClass = _knn.find_nearest(features, KNN_K); } else if (_engine == DTREE) { theClass = _dtree.predict(features)->value; } else if (_engine == GBT) { theClass = _gbtrees.predict(features); } else if (_engine == RTREES) { theClass = _rtrees.predict(features); } else if (_engine == ERTREES) { theClass = _ertrees.predict(features); } else if (_engine == MLP) { Mat classification; _mlp.predict(features, classification); // Find the class with highest weight int maxIndex[2]; minMaxIdx(classification, NULL, NULL, NULL, maxIndex); // The predicted class is the 1-based (since we don't include the // 0 (unclassified) class) index of the output layer element with // maximal value. theClass = (float) (maxIndex[1] + 1); } else { FATAL_ERROR("Unknown classifier engine"); } _swatchClassification.stop(); // Create the classification matrix assert(_vis != NULL || _lwir != NULL); Size S = (_vis != NULL) ? _vis->size() : _lwir->size(); Mat classification = Mat::zeros(S, CV_8UC1); // Fill the classification matrix if (region.getRepresentationMode() == PIXEL) { classification.at<unsigned char>(region.getPoint()) = (unsigned char) theClass; } else { Mat mask = densify(region.getMask()); classification += theClass * (mask / 255); } return classification; } string Classifier::getID() { string id; // Place the classifier identification if (_engine == SVM) { id += "SVM-"; } else if (_engine == NBC) { id += "NBC-"; } else if (_engine == KNN) { id += "KNN-"; } else if (_engine == DTREE) { id += "DTREE-"; } else if (_engine == GBT) { id += "GBT-"; } else if (_engine == RTREES) { id += "RTREES-"; } else if (_engine == ERTREES) { id += "ERTREES-"; } else if (_engine == MLP) { id += "MLP-"; } // Place the descriptor identification id += _descriptor->getID(); return id; } ImageType Classifier::getType() { return _type; } double Classifier::getDescriptionTime() { return _swatchDescription.read(); } double Classifier::getTrainingTime() { return _swatchTraining.read(); } double Classifier::getClassificationTime() { return _swatchClassification.read(); } void Classifier::setTrainingMap(ThematicMap *map) { _trainingMap = map; }
[ "almeidabatista@gmail.com" ]
almeidabatista@gmail.com
a7ab9afab6c4577b590ba5e5074236a3161af5f3
2f4e1455e35d031a4724e50447fb3848d0a20e3b
/src/main/include/commands/RotateCargoForLevelOneRocket.h
2681b3ec4d8d020e1da1d6d6d2d199bb6e8b64c4
[ "BSD-3-Clause" ]
permissive
PhyXTGears-programming/2019-RobotCode
94dc4be551b7503068f6843462cea042bc4595ae
34473345d812f2db14f801cf82515ce7add5618b
refs/heads/master
2020-04-17T06:17:00.661538
2019-07-24T17:26:34
2019-07-24T17:26:34
166,318,639
0
0
null
null
null
null
UTF-8
C++
false
false
366
h
#pragma once #include <frc/commands/Command.h> class RotateCargoForLevelOneRocket : public frc::Command { public: RotateCargoForLevelOneRocket(); void Initialize() override; void Execute() override; bool IsFinished() override; bool IsInterruptible(); void End() override; void Interrupted() override; };
[ "phyxtgearspro@gmail.com" ]
phyxtgearspro@gmail.com
bf0244eaba93484fd67ae58afce106ee7dedd5fd
89b9a43789a05688f9aa3f0554cd2762f6240720
/anagrAmble/anagrAmble/anagrAmble/MainGame/MainGame.cpp
921b481d03d224608243d5f51b934199f83e545a
[]
no_license
Sharoku-haga/anagrAmble
2850f712976c7f6ae2eabf60332e7d68b614cb0d
c536a0d6b8f94254c9a572d5f7c5b46d7cb6eda7
refs/heads/master
2020-12-30T14:19:42.445592
2017-09-21T03:55:08
2017-09-21T03:55:08
91,281,469
0
0
null
2017-05-15T03:12:02
2017-05-15T00:56:27
C++
UTF-8
C++
false
false
6,935
cpp
//==================================================================================================================================// //!< @file MainGame.cpp //!< @brief ar::MainGameクラス実装 //!< @author T.Haga //==================================================================================================================================// /* Includes --------------------------------------------------------------------------------------------------- */ #include "MainGame.h" #include "../SharokuLibrary/sl/sl.h" #include "SceneManager/SceneManager.h" #include "ControllerEnum.h" namespace ar { /* Public Functions ------------------------------------------------------------------------------------------- */ MainGame::MainGame(void) : m_pLibrary(nullptr) , m_pSceneManager(nullptr) { sl::ISharokuLibrary::Create(); m_pLibrary = sl::ISharokuLibrary::Instance(); // ライブラリの初期化 sl::t_char* windowTitle = "anagrAmble"; // ウィンドウのタイトル int windowWidth = 1920; // ウィンドウの横幅 int windowHeight = 1080; // ウィンドウの縦幅 m_pLibrary->Initialize(windowTitle, windowWidth, windowHeight); // デバイスインプットのカスタマイズ CustomizeInput(); #ifdef _DEBUG CutomizeInputDebug(); #endif // _DEBUG m_pSceneManager = new SceneManager(); } MainGame::~MainGame(void) { sl::DeleteSafely(&m_pSceneManager); sl::ISharokuLibrary::Delete(); } void MainGame::Loop(void) { while(true) { if(m_pLibrary->UpdateWindow()) { break; } else { if(m_pSceneManager->Updtae()) { break; } } } } /* Private Functions------------------------------------------------------------------------------------------- */ void MainGame::CustomizeInput(void) { // 上ボタン: UP { m_pLibrary->RegisterCustomizeType(UP, sl::GAMEPAD, sl::XIGAMEPAD_LSTICK_UP); m_pLibrary->RegisterCustomizeType(UP, sl::GAMEPAD, sl::XIGAMEPAD_DPAD_UP ); } // 下のボタン : DOWN { m_pLibrary->RegisterCustomizeType(DOWN, sl::GAMEPAD, sl::XIGAMEPAD_LSTICK_DOWN); m_pLibrary->RegisterCustomizeType(DOWN, sl::GAMEPAD, sl::XIGAMEPAD_DPAD_DOWN ); } // 右ボタン : RIGHT { m_pLibrary->RegisterCustomizeType(RIGHT, sl::GAMEPAD, sl::XIGAMEPAD_LSTICK_RIGHT); m_pLibrary->RegisterCustomizeType(RIGHT, sl::GAMEPAD, sl::XIGAMEPAD_DPAD_RIGHT ); } // 左ボタン : LEFT { m_pLibrary->RegisterCustomizeType(LEFT, sl::GAMEPAD, sl::XIGAMEPAD_LSTICK_LEFT); m_pLibrary->RegisterCustomizeType(LEFT, sl::GAMEPAD, sl::XIGAMEPAD_DPAD_LEFT ); m_pLibrary->RegisterCustomizeType(LEFT, sl::KEYBOARD, sl::K_LEFT); } // 決定 : ENTER { m_pLibrary->RegisterCustomizeType(ENTER, sl::GAMEPAD, sl::XIGAMEPAD_A ); } // プレイヤーのモード切替 : MODE_CHANGE { m_pLibrary->RegisterCustomizeType(MODE_CHANGE, sl::GAMEPAD, sl::XIGAMEPAD_Y ); } // プレイヤーのモード解除 : MODE_RELEASE { m_pLibrary->RegisterCustomizeType(MODE_RELEASE, sl::GAMEPAD, sl::XIGAMEPAD_Y ); } // 空間入れ替え : SPACE_CHANGE { m_pLibrary->RegisterCustomizeType(SPACE_CHANGE, sl::GAMEPAD, sl::XIGAMEPAD_RTRIGGER); } // アンカ-セット : ANCHOR_SET { m_pLibrary->RegisterCustomizeType(ANCHOR_SET, sl::GAMEPAD, sl::XIGAMEPAD_B ); } // アンカー回収 : ANCHOR_RETRIEVE { m_pLibrary->RegisterCustomizeType(ANCHOR_RETRIEVE, sl::GAMEPAD, sl::XIGAMEPAD_X ); } // ダッシュ : DASH { m_pLibrary->RegisterCustomizeType(DASH, sl::GAMEPAD, sl::XIGAMEPAD_LTRIGGER ); } // ジャンプ : JUMP { m_pLibrary->RegisterCustomizeType(JUMP, sl::GAMEPAD, sl::XIGAMEPAD_A); } // しゃがむ : SQUAT { m_pLibrary->RegisterCustomizeType(SQUAT, sl::GAMEPAD, sl::XIGAMEPAD_LSTICK_DOWN); m_pLibrary->RegisterCustomizeType(SQUAT, sl::GAMEPAD, sl::XIGAMEPAD_DPAD_DOWN ); } // 特殊アクション : SPECIAL_ACTION { m_pLibrary->RegisterCustomizeType(SPECIAL_ACTION, sl::GAMEPAD, sl::XIGAMEPAD_B); } // 時もどしの左ボタン : TIME_RETURN_L { m_pLibrary->RegisterCustomizeType(TIME_RETURN_L, sl::GAMEPAD, sl::XIGAMEPAD_LEFT_SHOULDER ); } // 時もどしの右ボタン : TIME_RETURN_R { m_pLibrary->RegisterCustomizeType(TIME_RETURN_R, sl::GAMEPAD, sl::XIGAMEPAD_RIGHT_SHOULDER); } // ポーズボタン : PAUSE { m_pLibrary->RegisterCustomizeType(PAUSE, sl::GAMEPAD, sl::XIGAMEPAD_START); m_pLibrary->RegisterCustomizeType(PAUSE, sl::KEYBOARD, sl::K_TAB); } } #ifdef _DEBUG /** @todo 2017/05/19現在 仮実装 */ void MainGame::CutomizeInputDebug(void) { // 上ボタン: UP { m_pLibrary->RegisterCustomizeType(UP, sl::KEYBOARD, sl::K_UP); } // 下のボタン : DOWN { m_pLibrary->RegisterCustomizeType(DOWN, sl::KEYBOARD, sl::K_DOWN); } // 右ボタン : RIGHT { m_pLibrary->RegisterCustomizeType(RIGHT, sl::KEYBOARD, sl::K_RIGHT); } // 左ボタン : LEFT { m_pLibrary->RegisterCustomizeType(LEFT, sl::KEYBOARD, sl::K_LEFT); } // 決定 : ENTER { m_pLibrary->RegisterCustomizeType(ENTER, sl::KEYBOARD, sl::K_A); m_pLibrary->RegisterCustomizeType(ENTER, sl::KEYBOARD, sl::K_RETURN); } // プレイヤーのモード切替 : MODE_CHANGE { m_pLibrary->RegisterCustomizeType(MODE_CHANGE, sl::KEYBOARD, sl::K_Z); } // プレイヤーのモード解除 : MODE_RELEASE { m_pLibrary->RegisterCustomizeType(MODE_CHANGE, sl::KEYBOARD, sl::K_Z); } // 空間入れ替え : SPACE_CHANGE { m_pLibrary->RegisterCustomizeType(SPACE_CHANGE, sl::KEYBOARD, sl::K_RETURN); } // アンカ-セット : ANCHOR_SET { m_pLibrary->RegisterCustomizeType(ANCHOR_SET, sl::KEYBOARD, sl::K_SPACE); } // アンカー回収 : ANCHOR_RETRIEVE { m_pLibrary->RegisterCustomizeType(ANCHOR_RETRIEVE, sl::KEYBOARD, sl::K_C); } // ダッシュ : DASH { m_pLibrary->RegisterCustomizeType(DASH, sl::KEYBOARD, sl::K_LSHIFT); m_pLibrary->RegisterCustomizeType(DASH, sl::KEYBOARD, sl::K_RSHIFT); } // ジャンプ : JUMP { m_pLibrary->RegisterCustomizeType(JUMP, sl::KEYBOARD, sl::K_UP); } // しゃがむ : SQUAT { m_pLibrary->RegisterCustomizeType(SQUAT, sl::KEYBOARD, sl::K_DOWN); } // 特殊アクション : SPECIAL_ACTION { m_pLibrary->RegisterCustomizeType(SPECIAL_ACTION, sl::KEYBOARD, sl::K_X); } // 時もどしの左ボタン : TIME_RETURN_L { m_pLibrary->RegisterCustomizeType(TIME_RETURN_L, sl::KEYBOARD, sl::K_B); } // 時もどしの右ボタン : TIME_RETURN_R { m_pLibrary->RegisterCustomizeType(TIME_RETURN_R, sl::KEYBOARD, sl::K_N); } // ポーズボタン : PAUSE { m_pLibrary->RegisterCustomizeType(PAUSE, sl::KEYBOARD, sl::K_P); } } #endif // _DEBUG } // namespace ar //==================================================================================================================================// // END OF FILE //==================================================================================================================================//
[ "holmes221nob@gmail.com" ]
holmes221nob@gmail.com
5924f22a4d4190dc81a2fce04f5b43f857b8c712
f06d75add72ec34f3a59bfcf85bb8249fda8f663
/robot_setup_tf/src/tf_broadcaster.cpp
8ab62015b1e6adc2c292481385331e905ebb62f7
[]
no_license
BenedictCheong/Mybom-Kinetic-Navigation
12e304f0e0517536b7d571cebc08820ca8627239
bc7664580701565b45306a4151e99428b85c73ae
refs/heads/master
2022-02-26T13:20:08.990005
2019-07-22T02:14:55
2019-07-22T02:14:55
198,123,348
0
0
null
null
null
null
UTF-8
C++
false
false
491
cpp
#include <ros/ros.h> #include <tf/transform_broadcaster.h> int main(int argc, char** argv){ ros::init(argc, argv, "robot_tf_publisher"); ros::NodeHandle n; ros::Rate r(10); tf::TransformBroadcaster broadcaster; while(n.ok()){ broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0, 0, 0, 1), tf::Vector3(0.1, 0.0, 0.2)), ros::Time::now(),"base_link", "camera_link")); r.sleep(); } }
[ "noreply@github.com" ]
noreply@github.com
0ef7c8efe007f8933161c38df16186f0333e5040
c87d64fce4b52ae89076dc8b00db3c61342747b6
/simulator/AlgorithmRegistrar.cpp
fa12f7e0023bd89591ceadd1298747f9f9cc357b
[]
no_license
liangxiao-xikunlun/Stowage_Algorithm_Simulator
e21d3ef9de48f7865fbb234b55f5bf6d3290a44b
9dde457e4cf9df95be10b0733822a5e02f363351
refs/heads/master
2023-03-18T12:26:48.497801
2020-10-11T12:14:56
2020-10-11T12:14:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,537
cpp
// // Created by Owner on 12-May-20. // #include "AlgorithmRegistrar.h" using AlgorithmFactory = AlgorithmRegistrar::AlgorithmFactory; void AlgorithmRegistrar::DlCloser::operator()(void *dlhandle) const noexcept { dlclose(dlhandle); } AlgorithmRegistrar::~AlgorithmRegistrar() { // Remove all factories - before closing all handles! algorithm_factories.clear(); dl_handles.clear(); } void AlgorithmRegistrar::register_algorithm_factory(AlgorithmFactory algorithm_factory) { algorithm_factories.push_back(algorithm_factory); } void AlgorithmRegistrar::add_algorithm_name(string name) { algorithm_names.push_back(name); } const vector<AlgorithmFactory>&AlgorithmRegistrar::get_algorithm_factories() const { return algorithm_factories; } const vector<string>& AlgorithmRegistrar::get_algorithm_names() const { return algorithm_names; } int AlgorithmRegistrar::get_num_algorithms() const { return (int)algorithm_names.size(); } const AlgorithmFactory & AlgorithmRegistrar::get_factory_by_idx(int idx) { return algorithm_factories[idx]; } const string &AlgorithmRegistrar::get_algorithm_name_by_idx(int idx) { return algorithm_names[idx]; } bool AlgorithmRegistrar::load_algorithm_from_file(const char *file_path, std::string& error) { #ifndef WIN_DEBUG // To check if algorithm was registered unsigned num_factories_before_register = algorithm_factories.size(); /* When debugging on Windows, SO loading will always fail and the * algorithms are loaded statically. */ #endif // Try to load given module DlHandler algo_handle(dlopen(file_path, RTLD_LAZY)); // Check if dlopen succeeded if (algo_handle == nullptr) { #ifdef WIN_DEBUG // In debug on Windows, add the algorithm anyway. add_algorithm_name(FileParser::extract_file_name_from_path(file_path)); #endif const char *dlopen_error = dlerror(); error = dlopen_error ? dlopen_error : ("Failed to open shared object " + FileParser::extract_file_name_from_path(file_path) + ".so"); return false; } #ifndef WIN_DEBUG // Check if algorithm was registered if (num_factories_before_register == algorithm_factories.size()) { error = string("File loaded but no algorithm registered: ") + FileParser::extract_file_name_from_path(file_path) + ".so"; return false; } #endif dl_handles[file_path] = std::move(algo_handle); add_algorithm_name(FileParser::extract_file_name_from_path(file_path)); return true; } AlgorithmRegistrar &AlgorithmRegistrar::get_instance() { static AlgorithmRegistrar instance; return instance; }
[ "ofek1210@gmail.com" ]
ofek1210@gmail.com
2995bfc3b155cf0734885a6797068db138b9154d
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_patch_hunk_2849.cpp
d5092cdef3207ad90a65d10efc8bb74916daff6f
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,399
cpp
return (unsigned char)*a - (unsigned char)*b; } static int split_maildir(const char *maildir, const char *dir, int nr_prec, int skip) { - char file[PATH_MAX]; - char name[PATH_MAX]; + char *file = NULL; + FILE *f = NULL; int ret = -1; int i; struct string_list list = STRING_LIST_INIT_DUP; list.cmp = maildir_filename_cmp; if (populate_maildir_list(&list, maildir) < 0) goto out; for (i = 0; i < list.nr; i++) { - FILE *f; - snprintf(file, sizeof(file), "%s/%s", maildir, list.items[i].string); + char *name; + + free(file); + file = xstrfmt("%s/%s", maildir, list.items[i].string); + f = fopen(file, "r"); if (!f) { error("cannot open mail %s (%s)", file, strerror(errno)); goto out; } if (strbuf_getwholeline(&buf, f, '\n')) { error("cannot read mail %s (%s)", file, strerror(errno)); goto out; } - sprintf(name, "%s/%0*d", dir, nr_prec, ++skip); + name = xstrfmt("%s/%0*d", dir, nr_prec, ++skip); split_one(f, name, 1); + free(name); fclose(f); + f = NULL; } ret = skip; out: + if (f) + fclose(f); + free(file); string_list_clear(&list, 1); return ret; } static int split_mbox(const char *file, const char *dir, int allow_bare, int nr_prec, int skip) { - char name[PATH_MAX]; int ret = -1; int peek; FILE *f = !strcmp(file, "-") ? stdin : fopen(file, "r"); int file_done = 0;
[ "993273596@qq.com" ]
993273596@qq.com
635e8c840c4730e3aa711f0c5f96d27a09c2405b
eab329dd608035ac69c7737b4a1f525efd51114b
/tests/RemoveObjectWhileIterating.cpp
7b92574e546c7a14f20046d655ca014efc112125
[]
no_license
lineCode/Flexium
a8c8c07de3015928b0df757487f3002bb3268bab
4e38d4a9f6b37d39eeca28e8d96d4b23f6197ba6
refs/heads/master
2021-05-30T03:30:33.109035
2015-03-29T00:33:38
2015-03-29T00:33:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
/* This shows that objects that are destroyed before they are iterated over are never iterated over. */ #include <Flexium/ConsoleMinimal.hpp> #include <Flexium/World.hpp> #include <Flexium/Object.hpp> using namespace flx; class ObjectOne : public Object { protected: std::string name; public: ObjectOne(std::string s): name(s) {}; virtual void sayName() { Console::Log << name << std::endl; } virtual ~ObjectOne() {}; }; class ObjectTwo : public ObjectOne { private: Object * target; public: ObjectTwo(std::string s, Object * o): ObjectOne(s), target(o) {}; virtual void sayName() { Console::Log << name << std::endl; // Do something sneaky! target -> destroy(); } virtual ~ObjectTwo() {}; }; int main() { World world; Object * target = new ObjectOne("Bob"); world.instanceAdd(new ObjectTwo("Bill", target)); world.instanceAdd(target); for (auto i : world.instanceGet<ObjectOne>()) { i -> sayName(); } }
[ "dxsmiley@hotmail.com" ]
dxsmiley@hotmail.com
f9d8b5c56be9c341caa9aff30d52e65ebf5f6148
b8499de1a793500b47f36e85828f997e3954e570
/v2_3/build/Android/Preview/app/src/main/jni/Alive.SettingsMenuItem.cpp
326f2e08ffa116aee1525819f06b1fba678e4d0f
[]
no_license
shrivaibhav/boysinbits
37ccb707340a14f31bd57ea92b7b7ddc4859e989
04bb707691587b253abaac064317715adb9a9fe5
refs/heads/master
2020-03-24T05:22:21.998732
2018-07-26T20:06:00
2018-07-26T20:06:00
142,485,250
0
0
null
2018-07-26T20:03:22
2018-07-26T19:30:12
C++
UTF-8
C++
false
false
15,473
cpp
// This file was generated based on build/Android/Preview/cache/ux15/Alive.SettingsMenuItem.g.uno. // WARNING: Changes might be lost if you edit this file directly. #include <_root.v2_accessor_Ali-a5c421c2.h> #include <_root.v2_FuseControls-71dcdce3.h> #include <Alive.ButtonText.h> #include <Alive.SettingsMenuItem.h> #include <Fuse.Controls.LayoutControl.h> #include <Fuse.Controls.TextControl.h> #include <Fuse.Elements.Alignment.h> #include <Fuse.Elements.Element.h> #include <Fuse.Layouts.Layout.h> #include <Fuse.Layouts.StackLayout.h> #include <Fuse.Reactive.BindingMode.h> #include <Fuse.Reactive.Constan-264ec80.h> #include <Fuse.Reactive.Constant.h> #include <Fuse.Reactive.DataBinding.h> #include <Fuse.Reactive.Expression.h> #include <Fuse.Reactive.IExpression.h> #include <Fuse.Reactive.Property.h> #include <Uno.Bool.h> #include <Uno.Float.h> #include <Uno.Float4.h> #include <Uno.Int.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.UX.Property.h> #include <Uno.UX.Property1-1.h> #include <Uno.UX.PropertyAccessor.h> #include <Uno.UX.PropertyObject.h> #include <Uno.UX.Selector.h> static uString* STRINGS[3]; static uType* TYPES[2]; namespace g{ namespace Alive{ // public partial sealed class SettingsMenuItem :4 // { // static SettingsMenuItem() :22 static void SettingsMenuItem__cctor_7_fn(uType* __type) { SettingsMenuItem::__selector01_ = ::g::Uno::UX::Selector__op_Implicit1(::STRINGS[0/*"Value"*/]); } static void SettingsMenuItem_build(uType* type) { ::STRINGS[0] = uString::Const("Value"); ::STRINGS[1] = uString::Const("Pages/SettingsPage.ux"); ::STRINGS[2] = uString::Const("Label"); ::TYPES[0] = ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL); ::TYPES[1] = ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL); type->SetDependencies( ::g::v2_accessor_Alive_SettingsMenuItem_Label_typeof()); type->SetInterfaces( ::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::Shape_type, interface0), ::g::Fuse::Scripting::IScriptObject_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface1), ::g::Fuse::IProperties_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface2), ::g::Fuse::INotifyUnrooted_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface3), ::g::Fuse::ISourceLocation_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface4), ::TYPES[0/*Uno.Collections.ICollection<Fuse.Binding>*/], offsetof(::g::Fuse::Controls::Shape_type, interface5), ::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::Shape_type, interface6), ::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::Shape_type, interface7), ::g::Uno::UX::IPropertyListener_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface8), ::g::Fuse::ITemplateSource_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface9), ::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Visual_typeof(), NULL), offsetof(::g::Fuse::Controls::Shape_type, interface10), ::TYPES[1/*Uno.Collections.ICollection<Fuse.Node>*/], offsetof(::g::Fuse::Controls::Shape_type, interface11), ::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::Shape_type, interface12), ::g::Fuse::Triggers::Actions::IShow_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface13), ::g::Fuse::Triggers::Actions::IHide_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface14), ::g::Fuse::Triggers::Actions::ICollapse_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface15), ::g::Fuse::IActualPlacement_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface16), ::g::Fuse::Animations::IResize_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface17), ::g::Fuse::Drawing::ISurfaceDrawable_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface18), ::g::Fuse::Drawing::IDrawObjectWatcherFeedback_typeof(), offsetof(::g::Fuse::Controls::Shape_type, interface19)); type->SetFields(124, ::g::Uno::String_typeof(), offsetof(SettingsMenuItem, _field_Label), 0, ::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::String_typeof(), NULL), offsetof(SettingsMenuItem, temp_Value_inst), 0, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&SettingsMenuItem::__selector01_, uFieldFlagsStatic); type->Reflection.SetFunctions(4, new uFunction("get_Label", NULL, (void*)SettingsMenuItem__get_Label_fn, 0, false, ::g::Uno::String_typeof(), 0), new uFunction("set_Label", NULL, (void*)SettingsMenuItem__set_Label_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::String_typeof()), new uFunction(".ctor", NULL, (void*)SettingsMenuItem__New6_fn, 0, true, type, 0), new uFunction("SetLabel", NULL, (void*)SettingsMenuItem__SetLabel_fn, 0, false, uVoid_typeof(), 2, ::g::Uno::String_typeof(), ::g::Uno::UX::IPropertyListener_typeof())); } ::g::Fuse::Controls::Shape_type* SettingsMenuItem_typeof() { static uSStrong< ::g::Fuse::Controls::Shape_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Alive::Card_typeof(); options.FieldCount = 127; options.InterfaceCount = 20; options.DependencyCount = 1; options.ObjectSize = sizeof(SettingsMenuItem); options.TypeSize = sizeof(::g::Fuse::Controls::Shape_type); type = (::g::Fuse::Controls::Shape_type*)uClassType::New("Alive.SettingsMenuItem", options); type->fp_build_ = SettingsMenuItem_build; type->fp_ctor_ = (void*)SettingsMenuItem__New6_fn; type->fp_cctor_ = SettingsMenuItem__cctor_7_fn; type->interface19.fp_Changed = (void(*)(uObject*, uObject*))::g::Fuse::Controls::Shape__FuseDrawingIDrawObjectWatcherFeedbackChanged_fn; type->interface19.fp_Prepare = (void(*)(uObject*, uObject*))::g::Fuse::Controls::Shape__FuseDrawingIDrawObjectWatcherFeedbackPrepare_fn; type->interface19.fp_Unprepare = (void(*)(uObject*, uObject*))::g::Fuse::Controls::Shape__FuseDrawingIDrawObjectWatcherFeedbackUnprepare_fn; type->interface18.fp_Draw = (void(*)(uObject*, ::g::Fuse::Drawing::Surface*))::g::Fuse::Controls::Shape__FuseDrawingISurfaceDrawableDraw_fn; type->interface18.fp_get_IsPrimary = (void(*)(uObject*, bool*))::g::Fuse::Controls::Shape__FuseDrawingISurfaceDrawableget_IsPrimary_fn; type->interface18.fp_get_ElementSize = (void(*)(uObject*, ::g::Uno::Float2*))::g::Fuse::Controls::Shape__FuseDrawingISurfaceDrawableget_ElementSize_fn; type->interface8.fp_OnPropertyChanged = (void(*)(uObject*, ::g::Uno::UX::PropertyObject*, ::g::Uno::UX::Selector*))::g::Fuse::Controls::Shape__OnPropertyChanged2_fn; type->interface13.fp_Show = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsIShowShow_fn; type->interface15.fp_Collapse = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsICollapseCollapse_fn; type->interface14.fp_Hide = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsIHideHide_fn; type->interface17.fp_SetSize = (void(*)(uObject*, ::g::Uno::Float2*))::g::Fuse::Elements::Element__FuseAnimationsIResizeSetSize_fn; type->interface16.fp_get_ActualSize = (void(*)(uObject*, ::g::Uno::Float3*))::g::Fuse::Elements::Element__FuseIActualPlacementget_ActualSize_fn; type->interface16.fp_get_ActualPosition = (void(*)(uObject*, ::g::Uno::Float3*))::g::Fuse::Elements::Element__FuseIActualPlacementget_ActualPosition_fn; type->interface16.fp_add_Placed = (void(*)(uObject*, uDelegate*))::g::Fuse::Elements::Element__add_Placed_fn; type->interface16.fp_remove_Placed = (void(*)(uObject*, uDelegate*))::g::Fuse::Elements::Element__remove_Placed_fn; type->interface10.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Visual__UnoCollectionsIEnumerableFuseVisualGetEnumerator_fn; type->interface11.fp_Clear = (void(*)(uObject*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeClear_fn; type->interface11.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeContains_fn; type->interface7.fp_RemoveAt = (void(*)(uObject*, int32_t*))::g::Fuse::Visual__UnoCollectionsIListFuseNodeRemoveAt_fn; type->interface12.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Visual__UnoCollectionsIEnumerableFuseNodeGetEnumerator_fn; type->interface11.fp_get_Count = (void(*)(uObject*, int32_t*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeget_Count_fn; type->interface7.fp_get_Item = (void(*)(uObject*, int32_t*, uTRef))::g::Fuse::Visual__UnoCollectionsIListFuseNodeget_Item_fn; type->interface7.fp_Insert = (void(*)(uObject*, int32_t*, void*))::g::Fuse::Visual__Insert1_fn; type->interface9.fp_FindTemplate = (void(*)(uObject*, uString*, ::g::Uno::UX::Template**))::g::Fuse::Visual__FindTemplate_fn; type->interface11.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Visual__Add1_fn; type->interface11.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__Remove1_fn; type->interface5.fp_Clear = (void(*)(uObject*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingClear_fn; type->interface5.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingContains_fn; type->interface0.fp_RemoveAt = (void(*)(uObject*, int32_t*))::g::Fuse::Node__UnoCollectionsIListFuseBindingRemoveAt_fn; type->interface6.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Node__UnoCollectionsIEnumerableFuseBindingGetEnumerator_fn; type->interface1.fp_SetScriptObject = (void(*)(uObject*, uObject*, ::g::Fuse::Scripting::Context*))::g::Fuse::Node__FuseScriptingIScriptObjectSetScriptObject_fn; type->interface5.fp_get_Count = (void(*)(uObject*, int32_t*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingget_Count_fn; type->interface0.fp_get_Item = (void(*)(uObject*, int32_t*, uTRef))::g::Fuse::Node__UnoCollectionsIListFuseBindingget_Item_fn; type->interface1.fp_get_ScriptObject = (void(*)(uObject*, uObject**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptObject_fn; type->interface1.fp_get_ScriptContext = (void(*)(uObject*, ::g::Fuse::Scripting::Context**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptContext_fn; type->interface4.fp_get_SourceNearest = (void(*)(uObject*, uObject**))::g::Fuse::Node__FuseISourceLocationget_SourceNearest_fn; type->interface3.fp_add_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedadd_Unrooted_fn; type->interface3.fp_remove_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedremove_Unrooted_fn; type->interface0.fp_Insert = (void(*)(uObject*, int32_t*, void*))::g::Fuse::Node__Insert_fn; type->interface2.fp_get_Properties = (void(*)(uObject*, ::g::Fuse::Properties**))::g::Fuse::Node__get_Properties_fn; type->interface4.fp_get_SourceLineNumber = (void(*)(uObject*, int32_t*))::g::Fuse::Node__get_SourceLineNumber_fn; type->interface4.fp_get_SourceFileName = (void(*)(uObject*, uString**))::g::Fuse::Node__get_SourceFileName_fn; type->interface5.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Node__Add_fn; type->interface5.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__Remove_fn; return type; } // public SettingsMenuItem() :26 void SettingsMenuItem__ctor_10_fn(SettingsMenuItem* __this) { __this->ctor_10(); } // private void InitializeUX() :30 void SettingsMenuItem__InitializeUX2_fn(SettingsMenuItem* __this) { __this->InitializeUX2(); } // public string get_Label() :10 void SettingsMenuItem__get_Label_fn(SettingsMenuItem* __this, uString** __retval) { *__retval = __this->Label(); } // public void set_Label(string value) :11 void SettingsMenuItem__set_Label_fn(SettingsMenuItem* __this, uString* value) { __this->Label(value); } // public SettingsMenuItem New() :26 void SettingsMenuItem__New6_fn(SettingsMenuItem** __retval) { *__retval = SettingsMenuItem::New6(); } // public void SetLabel(string value, Uno.UX.IPropertyListener origin) :13 void SettingsMenuItem__SetLabel_fn(SettingsMenuItem* __this, uString* value, uObject* origin) { __this->SetLabel(value, origin); } ::g::Uno::UX::Selector SettingsMenuItem::__selector01_; // public SettingsMenuItem() [instance] :26 void SettingsMenuItem::ctor_10() { uStackFrame __("Alive.SettingsMenuItem", ".ctor()"); ctor_9(); InitializeUX2(); } // private void InitializeUX() [instance] :30 void SettingsMenuItem::InitializeUX2() { uStackFrame __("Alive.SettingsMenuItem", "InitializeUX()"); ::g::Fuse::Reactive::Constant* temp1 = ::g::Fuse::Reactive::Constant::New1(this); ::g::Alive::ButtonText* temp = ::g::Alive::ButtonText::New4(); temp_Value_inst = ::g::v2_FuseControlsTextControl_Value_Property::New1(temp, SettingsMenuItem::__selector01_); ::g::Fuse::Reactive::Property* temp2 = ::g::Fuse::Reactive::Property::New1(temp1, ::g::v2_accessor_Alive_SettingsMenuItem_Label::Singleton()); ::g::Fuse::Layouts::StackLayout* temp3 = ::g::Fuse::Layouts::StackLayout::New2(); ::g::Fuse::Reactive::DataBinding* temp4 = ::g::Fuse::Reactive::DataBinding::New1(temp_Value_inst, (uObject*)temp2, 1); Padding(::g::Uno::Float4__New2(20.0f, 20.0f, 20.0f, 20.0f)); SourceLineNumber(2); SourceFileName(::STRINGS[1/*"Pages/Setti...*/]); temp3->SourceLineNumber(5); temp3->SourceFileName(::STRINGS[1/*"Pages/Setti...*/]); temp->Alignment(10); temp->Margin(::g::Uno::Float4__New2(0.0f, 15.0f, 0.0f, 15.0f)); temp->Opacity(0.5f); temp->SourceLineNumber(7); temp->SourceFileName(::STRINGS[1/*"Pages/Setti...*/]); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Bindings()), ::TYPES[0/*Uno.Collections.ICollection<Fuse.Binding>*/]), temp4); temp2->SourceLineNumber(7); temp2->SourceFileName(::STRINGS[1/*"Pages/Setti...*/]); temp1->SourceLineNumber(7); temp1->SourceFileName(::STRINGS[1/*"Pages/Setti...*/]); Layout(temp3); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(Children()), ::TYPES[1/*Uno.Collections.ICollection<Fuse.Node>*/]), temp); } // public string get_Label() [instance] :10 uString* SettingsMenuItem::Label() { return _field_Label; } // public void set_Label(string value) [instance] :11 void SettingsMenuItem::Label(uString* value) { uStackFrame __("Alive.SettingsMenuItem", "set_Label(string)"); SetLabel(value, NULL); } // public void SetLabel(string value, Uno.UX.IPropertyListener origin) [instance] :13 void SettingsMenuItem::SetLabel(uString* value, uObject* origin) { uStackFrame __("Alive.SettingsMenuItem", "SetLabel(string,Uno.UX.IPropertyListener)"); if (::g::Uno::String::op_Inequality(value, _field_Label)) { _field_Label = value; OnPropertyChanged1(::g::Uno::UX::Selector__op_Implicit1(::STRINGS[2/*"Label"*/]), origin); } } // public SettingsMenuItem New() [static] :26 SettingsMenuItem* SettingsMenuItem::New6() { SettingsMenuItem* obj1 = (SettingsMenuItem*)uNew(SettingsMenuItem_typeof()); obj1->ctor_10(); return obj1; } // } }} // ::g::Alive
[ "shubhamanandoist@gmail.com" ]
shubhamanandoist@gmail.com
e39de3c0eca59719faa72d5c6fd93c9788ceb863
17d0ab7e09b7f69258ca6219d5e3df84d64534a0
/Datastructures/Recursion.cpp
b6b6a309e9485b07fd5e4b0c7b21524e1a182044
[]
no_license
Bsebring/Portfolio
137e96c73ee937027b56d7b462834aed758256c9
a60e8b7c24379e541bff03c82d2ac1fb2e044ac6
refs/heads/master
2020-04-13T07:10:09.189592
2018-12-25T03:43:34
2018-12-25T03:43:34
163,042,557
0
0
null
null
null
null
UTF-8
C++
false
false
6,402
cpp
// Ben Sebring // CPSC 250 // 11:00 am class // 2/11/2017 // Email: bsebring@live.esu.edu // The following is a collection of recursive programs // that perform various operations on numbers, arrays, and strings #include <iostream> #include <string> using namespace std; //Function prototypes int computeSum(const int anArray[], int n); int sum(int start, int end); void writeBackward(string s); void writeBackward2(string s); void writeIntegers(int m, int n); int sumOfSquares(int n); void reverseDigits(int integer); void writeLine(char ch, int n); void writeBlock(char ch, int m, int n); const int SIZE = 8; int main() { // Creating the test array int anArray[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Creating the test string string s = "cat"; // Outputting labels and calling other functions cout << "1. computeSum(anArray, 5) returns: " << computeSum(anArray, 5) << endl << endl; cout << "2. sum(2, 5) returns: " << sum(2, 5) << endl << endl; cout << "3. a. writeBacward(s) returns : "; writeBackward(s); cout << endl << endl; cout << "3. b. writeBackward2(s) returns: "; writeBackward2(s); cout << endl << endl; cout << "4. writeIntegers(2, 5) returns: "; writeIntegers(2, 5); cout << endl << endl; cout << "5. sumOfSquares(5) returns: " << sumOfSquares(5) << endl << endl; cout << "6. reverseDigits(1234) returns: "; reverseDigits(1234); cout << endl << endl; cout << "7. a. writeLine('*', 5) returns :\n"; writeLine('*', 5); cout << endl << endl; cout << "7. b. writeBlock('*', 5, 3) returns: \n"; writeBlock('*', 5, 3); cout << endl << endl; system("pause"); return 0; } //Function Definitions /* int computeSum(const int anArray[], int n) computes the sum of the given number of integers in an array preconditions: the array has at least n integers parameters: const int anArray[] - an array of integers int n - the number of integers from the array to sum together postconditions: n/a return: integer number or anArray[n-1] + recursive call to the function */ int computeSum(const int anArray[], int n) { // Base case if (n == 1) return 1; else // Add the n-1 position to the return of the funtion with one less number to evaluate return anArray[n - 1] + computeSum(anArray, n - 1); } /* int sum(int start, int end) computes the sum of all integers from start to end preconditions: end >= start parameters: int start - the number to start adding with int end - the last number to be added postconditions: n/a return: integer number or end + recursive call to the function */ int sum(int start, int end) { // Base case if (start == end) return start; else // Add end to the function call and decrement the end return end + sum(start, end - 1); } /* void writeBackward(string s) writes a string in reverse order preconditions: n/a parameters: string s - the string to be written in reverse */ void writeBackward(string s) { // Initialize length to the length of string s int length = s.length(); // Base case if (length == 1) cout << s; else { // Print the last letter in string s cout << s.substr(length - 1, 1); // Call to function with one less letter writeBackward(s.substr(0, length - 1)); } } /* void writeBackward2(string s) A different aproach to writing a string in reverse order preconditions: n/a parameters: string s - the string to be written in reverse */ void writeBackward2(string s) { // Initializing length to the size of the string int length = s.size(); // Base case is length == 0 because then this function prints nothing if (length > 0) { // Call the function without the first character in string s writeBackward2(s.substr(length - (length - 1), length)); // Print the first character in string s cout << s.substr(0, 1); } } /* void writeIntegers(int m, int n) writes the integers m through n (inclusively) to the console sepparated by a comma and a space (, ). preconditions: m > 0 m < n parameters: int m - the first integer to print int n - the last integer to print */ void writeIntegers(int m, int n) { // Base case if (n == m) cout << n << ", "; else { // Call the function with n-1 writeIntegers(m, n - 1); cout << n << ", "; } } /* int sumOfSquares(int n) computes the sum of the squares from 1 through n (inclusively) preconditions: n > 0 parameters: int n - the last number to square and sum together postconditions: n/a return: integer number or (n*n) + recursive call to the function */ int sumOfSquares(int n) { // Base case if (n == 1) return 1; // Add (n*n) to the function call and decriment n else return n*n + sumOfSquares(n - 1); } /* void reverseDigits(int integer) Prints an integer to the console in reverse order preconditions: integer > 0 parameters: int integer - the number to be displayed in reverse order */ void reverseDigits(int integer) { // Base case because 1-9 is one character if (integer < 10) cout << integer; else { // Print the last character by utilizing modulo operator cout << integer % 10; // call function and drop last number by dividing by 10 reverseDigits(integer / 10); } } /* void writeLine(char ch, int n) Prints out a specific number of any character on one line preconditions: n/a parameters: int n - the number of character for the line char ch - the character to be printed n times */ void writeLine(char ch, int n) { // Base case if (n == 1) cout << ch << endl; else { cout << ch; // Call the function with one less star needed writeLine(ch, n - 1); } } /* void writeBlock(char ch, int m, int n) Prints out a block of a specific character, using the writeLine function preconditions: n/a parameters: int n - the number of characters for the line char ch - the character to be printed n times int m - he number of times to call writeLine */ void writeBlock(char ch, int m, int n) { // Base case // Call writeLine to print a single line if (m == 1) writeLine(ch, n); else { // Call writeBlock with one less row writeBlock(ch, m - 1, n); // Call writeLine to print a single line writeLine(ch, n); } }
[ "noreply@github.com" ]
noreply@github.com
8fa177e0f0e0790d5ff9e827fc4041c449f42980
4c1b914bf3a4f0a856c6f7b9b864db4dac4988c6
/test_lst_timer.cpp
3914b32fd4fd6762d42304230d14d2e5063a7302
[]
no_license
ajunlonglive/hplsp-1
ae451729a8328e4cd51e08621b6bcc8767e45981
7b48f16300e8e48b3e05d25bd0f3b094b17bb664
refs/heads/master
2023-03-16T06:13:06.598853
2015-07-20T08:21:29
2015-07-20T08:21:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,394
cpp
#include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<assert.h> #include<stdio.h> #include<signal.h> #include<unistd.h> #include<errno.h> #include<string.h> #include<fcntl.h> #include<stdlib.h> #include<sys/epoll.h> #include<pthread.h> #include"lst_timer.h" #define FD_LIMIT 65535 #define MAX_EVENT_NUMBER 1024 #define TIMESLOT 5 static int pipefd[2]; static sort_timer_lst timer_lst; static int epollfd = 0 ; int setnonblocking(int fd) { int old_option = fcntl(fd, F_GETFL); int new_option = old_option | O_NONBLOCK; fcntl(fd, F_SETFL, new_option); return old_option; } void addfd(int epollfd, int fd) { epoll_event event; event.data.fd = fd; event.events = EPOLLIN | EPOLLET; epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); setnonblocking(fd); } void sig_handler(int sig) { int save_errno = errno; int msg = sig; send(pipefd[1], (char*)&msg, 1, 0); errno = save_errno; } void addsig(int sig) { struct sigaction sa; memset(&sa, '\0', sizeof(sa)); sa.sa_handler = sig_handler ; sa.sa_flags |= SA_RESTART; sigfillset(&sa.sa_mask); assert(sigaction(sig, &sa, NULL) != -1); } void timer_handler() { timer_lst.tick(); alarm(TIMESLOT); } void cb_func(client_data *user_data) { epoll_ctl(epollfd, EPOLL_CTL_DEL, user_data->sockfd, 0); assert(user_data); close(user_data->sockfd); printf("close fd %d\n", user_data->sockfd); } int main(int argc, char* argv[]) { if(argc <= 2){ printf("usage: %s ip port \n", basename(argv[0])); return 1; } const char* ip = argv[1]; int port = atoi(argv[2]); int ret = 0 ; struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); inet_pton(AF_INET, ip, &address.sin_addr); int listenfd = socket(AF_INET, SOCK_STREAM, 0); assert(listenfd >= 0); ret = bind(listenfd, (struct sockaddr*)&address, sizeof(address)); assert(ret != -1); ret = listen(listenfd, 5); assert(ret != -1); epoll_event events[MAX_EVENT_NUMBER]; int epollfd = epoll_create(5); assert(epollfd != -1); addfd(epollfd, listenfd); ret = socketpair(PF_UNIX, SOCK_STREAM, 0, pipefd); assert(ret != -1); setnonblocking(pipefd[1]); addfd(epollfd, pipefd[0]); addsig(SIGALRM); addsig(SIGTERM); bool stop_server = false; client_data* users = new client_data[FD_LIMIT]; bool timeout = false; alarm(TIMESLOT); while(!stop_server){ int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1); if(number<0 && errno != EINTR){ printf("epoll failure\n"); break; } for(int i = 0 ; i < number ; ++i){ int sockfd = events[i].data.fd; if(sockfd == listenfd){ struct sockaddr_in client_address; socklen_t client_addrlength = sizeof(client_address); int connfd = accept(listenfd, (struct sockaddr*)&client_address,&client_addrlength); addfd(epollfd, connfd); util_timer *timer = new util_timer; timer->user_data = &users[connfd]; timer->cb_func = cb_func; time_t cur = time(NULL); timer->expire = cur + 3*TIMESLOT; users[connfd].timer = timer; timer_lst.add_timer(timer); } else if(sockfd == pipefd[0] && (events[i].events & EPOLLIN)){ int sig ; char signals[1024]; ret = recv(pipefd[0], signals, sizeof(signals), 0); if(ret == -1){ continue; }else if(ret == 0){ continue; }else{ for(int j = 0 ; j < ret ; ++j){ switch(signals[j]){ case SIGALRM: timeout = true; break; case SIGTERM: stop_server = true; } } } }else if(events[i].events & EPOLLIN){ memset(users[sockfd].buf, '\0', BUFFER_SIZE); ret = recv(sockfd, users[sockfd].buf, BUFFER_SIZE - 1, 0); printf("get %d bytes of client data %s from %d\n", ret, users[sockfd].buf, sockfd); util_timer *timer = users[sockfd].timer; if(ret < 0){ if(errno != EAGAIN){ cb_func(&users[sockfd]); if(timer) timer_lst.del_timer(timer); } }else if(ret ==0){ cb_func(&users[sockfd]); if(timer) timer_lst.del_timer(timer); }else{ if(timer){ time_t cur = time(NULL); timer->expire = cur + 3*TIMESLOT; printf("adjust timer once\n"); timer_lst.adjust_timer(timer); } } } } if(timeout){ timer_handler(); timeout = false; } } close(listenfd); close(pipefd[1]); close(pipefd[0]); delete [] users; return 0; }
[ "1140625494@qq.com" ]
1140625494@qq.com
35c681d0e5ac1b87b067cd9e87bdd3bc66f1d0e9
f0ddda4f94cdfe6f66832700819b94a8024fb1f5
/262/A.cpp
69b96ffcf8c4b106d4e0d37012f0918c645dd526
[]
no_license
leontalukdar/Codeforces
3d3232edf10d07b680519624c81988761bf6e27c
2c3294b1b71682a50279e1a1bef83f633aa96e92
refs/heads/master
2021-01-19T10:42:58.541045
2017-03-07T00:45:43
2017-03-07T00:45:43
82,209,524
0
0
null
null
null
null
UTF-8
C++
false
false
1,299
cpp
#include <iostream> #include <sstream> #include <math.h> #include <algorithm> #include <string> #include <map> #include <set> #include <vector> #include <stdlib.h> #include <stdio.h> #include <queue> #include <cstring> #include <ctype.h> using namespace std; typedef long long int ll; typedef pair<int,int> pii; #define pb push_back #define mp make_pair #define PI acos(-1.0) //Normal Gcd /*int gcd ( int a, int b ) { int c; while ( a != 0 ) { c = a; a = b%a; b = c; } return b; }*/ //Recursive Gcd /*int gcdr ( int a, int b ) { if ( a==0 ) return b; return gcdr ( b%a, a ); }*/ //moduler arithmetic /*ll bigmod(ll B,ll P,ll M) { if(P==0)return 1; if(P%2==0) { ll ret=bigmod(B,P/2,M); return ((ret%M)*(ret%M))%M; } else return ((B%M)*(bigmod(B,P-1,M)%M))%M; }*/ //int fx[]={0,0,1,-1}; //int fy[]={1,-1,0,0}; //int fx[]={0,0,1,1,1,-1,-1,-1}; //int fy[]={1,-1,0,1,-1,0,1,-1}; //int fx[]={1,1,-1,-1,2,-2,2,-2}; //int fy[]={2,-2,2,-2,1,1,-1,-1}; int main() { string s; int n,k,ncount=0; cin>>n>>k; for(int i=0;i<n;i++) { cin>>s; int count4=count(s.begin(),s.end(),'4'); int count7=count(s.begin(),s.end(),'7'); if(count4+count7<=k) ncount++; } cout<<ncount<<endl; return 0; }
[ "leontalukdar@gmail.com" ]
leontalukdar@gmail.com
e2e8754d7ee0160fb633111250e7994a317ac7b9
0062e752c226c62ad6f2d29af1b2e735cc764ee3
/matrixCHOLMOD.cc
a7b479d070effd539261df88839689949841ce29
[]
no_license
rgjha/EDT_scripts
20def0f227d227287745c402af923b0a3ac0274a
694dc38ad542176dd0100e22702cf90481f391aa
refs/heads/master
2021-04-06T11:06:52.382759
2021-02-06T02:36:37
2021-02-06T02:36:37
124,620,401
1
0
null
null
null
null
UTF-8
C++
false
false
6,950
cc
#include <iostream> #include <string> #include <iomanip> #include <sstream> #include <stdio.h> #include <time.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include "sparse.h" #include "cholmod.h" using namespace std; void matrix_sqr(ValArray<double> &M, ValArray<double> &Msqr, int N4ct); void conj_grad(ValArray<double> &M, ValArray<double> &phi, ValArray<double> &Mp, int N4ct, double minRes, int maxIt); int main(int argc, char *argv[]) { int N4max(8000); // Set double of the N4 volume int nConfig(1); int initConfig; initConfig = atoi(argv[1]); double m(0.125); // m for the identity matrix double Ng(1); int count(0); long dum=-2; string bufferTemp2, bufferTemp3, bufferTemp4, bufferTemp5; for(int n(initConfig); n<nConfig+initConfig; n++) { ostringstream config_num; config_num << initConfig; bufferTemp3 = argv[2]; bufferTemp4 = argv[3]; infile input2(bufferTemp3); infile input6(bufferTemp5); ValArray<int> SliceRead(N4max); ValArray<int> InvSliceRead(N4max); ValArray<int> N4inf(5*N4max); int N4ct(0); input2.find("N4inf:"); input2 >> N4ct; for(int i(0); i<N4ct; i++) { input2 >> SliceRead[i]; InvSliceRead[SliceRead[i]]=i; for(int j(0); j<5; j++) {input2 >> N4inf[5*SliceRead[i]+j];} } ValArray<double> val(6*N4ct); ValArray<int> row_ind(6*N4ct); ValArray<int> col_ptr(6*N4ct); int s(0); int s2(1); for(int i(0); i<N4ct; i++) { ValArray<int> stor(5); int s3(0); for(int k(0); k<5; k++) { if(InvSliceRead[N4inf[5*SliceRead[i]+k]]<i) { stor[s3]=InvSliceRead[N4inf[5*SliceRead[i]+k]]; s3++; } } for(int k(0); k<s3; k++) { for(int l(0); l<s3-1; l++) { if(stor[l]>stor[l+1]) { int temp = stor[l+1]; stor[l+1] = stor[l]; stor[l] = temp; } } } if(s3>0) { val[s] += -1; row_ind[s] = stor[0]; for(int k(1); k<s3; k++) { if(stor[k]==stor[k-1]) { val[s] += -1; } else { s++; val[s] += -1; row_ind[s] = stor[k]; } } s++; } val[s] = 5.0+m*m; row_ind[s] = i; s++; col_ptr[s2] = s; s2++; } // Initialize ValArray<double>::set_default_size(N4ct); ValArray<ValArray<double> > phi(Ng); ValArray<ValArray<double> > R(Ng); ValArray<ValArray<double> > Minvphi(Ng); ValArray<double> valR(6*N4ct); ValArray<int> rowR_ind(6*N4ct); ValArray<int> colR_ptr(6*N4ct); double *v; int *ri, *cp; double *vR; int *riR, *cpR; infile input4(bufferTemp4); int data[400]; // Assume that 400 would be maximum simplexes smeared ever for 4K i.e ~ 10% ! string line; while (getline(input4, line)){ input4 >> data[count]; count = count+1;} cout << "Number of simplices actually smeared is " << count << endl ; // NOTE : March 2018 differences were here !! for (int i(0) ; i < count-1 ; i++){ phi[0][data[i]] = 1 ; } int sR(0); for(int j(0); j<Ng; j++) { for(int i(0); i<N4ct; i++) { if(phi[j][i]!=0) { valR[sR]=phi[j][i]; rowR_ind[sR]=i; sR++; } } } colR_ptr[1]=sR; // CHLMOD STARTS HERE // cholmod_sparse *A; // A is laplacian // cholmod_factor *L; cholmod_sparse *B; cholmod_dense *Y1; cholmod_sparse *Y; cholmod_common Common, *cm; cm = &Common; cholmod_start (cm); cm->supernodal=0; A = cholmod_allocate_sparse(N4ct, N4ct, s, 1, 1, 1, 1, cm); cp = (int *) A->p; ri = (int *) A->i; v = (double*) A->x; // This is ROW< COL< VAL // for(int i(0); i<N4ct+1; i++) {cp[i] = col_ptr[i];} for(int i(0); i<s; i++) { ri[i] = row_ind[i]; v[i] = val[i]; } // B = cholmod_allocate_sparse(N4ct, 1, count, 1, 1, 0, 1, cm); // Any !=square matrix will have this zero hidden, stype : 0 // B = cholmod_allocate_sparse(N4ct, 1, sR, 1, 1, 0, 1, cm); cpR = (int *) B->p; riR = (int *) B->i; vR = (double*) B->x; for(int i(0); i<2; i++) {cpR[i] = colR_ptr[i];} for(int i(0); i<sR; i++) { riR[i] = rowR_ind[i]; vR[i] = valR[i]; } L=cholmod_analyze(A, cm); cholmod_factorize(A, L, cm); Y=cholmod_spsolve(0, L, B, cm); // First entry is - s type ! // Y1 = cholmod_sparse_to_dense(Y,cm); double *xfinal; int *cpfinal; xfinal = (double *) L->x; cpfinal = (int *) L->p; double determ(0); for(int i(0); i<N4ct; i++) { determ += log(xfinal[cpfinal[i]]); // Calculate log(det) of Box operator } double *yfinal; yfinal = (double *) Y->x; double ans(0); for(int i(0); i<N4ct; i++) {Minvphi[0][i]=yfinal[i];} for(int i(0); i<N4ct; i++) {ans+=phi[0][i]*Minvphi[0][i];} for(int i(0); i<N4ct; i++) {cout << setprecision(10) << Minvphi[0][i] << endl ;} cholmod_free_factor(&L, cm); cholmod_free_sparse(&A, cm); cholmod_free_sparse(&B, cm); cholmod_free_sparse(&Y, cm); cholmod_free_dense(&Y1, cm) ; cout << "logarithm of the Det is" << determ << endl; cholmod_finish (cm); cout << ans << endl; } return (0); } void matrix_sqr(ValArray<double> &M, ValArray<double> &Msqr, int N4ct) { for(int i(0); i<N4ct; i++) { for(int j(0); j<N4ct; j++) { for(int k(0); k<N4ct; k++) { Msqr[i*N4ct+j] += M[i*N4ct+k]*M[k*N4ct+j]; } } } } void conj_grad(ValArray<double> &M, ValArray<double> &phi, ValArray<double> &x, int N4ct, double minRes, int maxIt) { ValArray<double> r(N4ct); ValArray<double> p(N4ct); ValArray<double> Mx(N4ct); double rsold(0); double rsnew(0); double alpha(0); for(int i(0); i<N4ct; i++) { for(int j(0); j<N4ct; j++) { Mx[i]+=M[i*N4ct+j]*x[j]; } r[i] = phi[i] - Mx[i]; p[i] = r[i]; } for(int i(0); i<N4ct; i++) { rsold += r[i]*r[i]; } for(int l(0); l<maxIt; l++) { ValArray<double> Mp(N4ct); for(int i(0); i<N4ct; i++) { for(int j(0); j<N4ct; j++) { Mp[i]+=M[i*N4ct+j]*p[j]; } } double denom(0); for(int i(0); i<N4ct; i++) { denom += p[i]*Mp[i]; } alpha = rsold/(denom); for(int i(0); i<N4ct; i++) { x[i] = x[i] + alpha*p[i]; r[i] = r[i] - alpha*Mp[i]; } rsnew = 0; for(int i(0); i<N4ct; i++) { rsnew += r[i]*r[i]; } if(sqrt(rsnew)<minRes) { return; } else { for(int i(0); i<N4ct; i++) { p[i] = r[i] + rsnew/rsold*p[i]; } rsold = rsnew; } } cout << "CG did not converge in " << maxIt << " iterations" << endl; return; }
[ "rgjha1989@gmail.com" ]
rgjha1989@gmail.com
1960b000acaca58779810105f73b32736f22609a
fba6ee80ae03468ad5c6f29c07be4b7f88456e47
/test39-boost-thread.cpp
ba19061e5bdde2b49a489f95e8a681fddcc31f39
[]
no_license
shane0314/testcpp
397df85eaab2244debe000fd366c30037d83b60e
480f70913e6b3939cc4b60b1a543810890b3e317
refs/heads/master
2021-07-09T15:35:37.373116
2020-07-17T09:13:49
2020-07-17T09:13:49
163,728,721
0
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
/* g++ test39-boost-thread.cpp -o t39 -lboost_thread -pthread */ #include <iostream> #include <boost/thread.hpp> void task_1() { for (int i = 0; i < 5; i ++) std::cout << "task_1 " << i << std::endl; } void task_2(int j) { for (int i = 0; i < 5; i ++) std::cout << "task_2 " << i << std::endl; } int main() { //boost::thread 不需要类似start,begin函数启动! boost::thread* t1 = new boost::thread(&task_1); boost::thread* t2 = new boost::thread(boost::bind(&task_2, 888)); boost::this_thread::sleep( boost::posix_time::seconds( 1 ) ); std::cout << "---main---" << std::endl; t1->join(); t2->join(); return 0; }
[ "swang@shancetech.com" ]
swang@shancetech.com
8518b9c7473404103e2354faba39ff9c44d990be
97305d1d853b71005e8781fed99362dcc7335e5e
/base/files/memory_mapped_file_posix.cc
2a5a4158dc9e5de524b271f7cc6df417725391fa
[]
no_license
wanqin88/base
206c45330f8d3b8f591dd4f9ac7516d866c0a116
c9b15dae218e9b63309dc9746a2c22afd382e55e
refs/heads/master
2020-07-04T15:28:01.494748
2019-08-14T11:19:45
2019-08-14T11:19:45
202,324,568
0
0
null
null
null
null
UTF-8
C++
false
false
1,258
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/files/memory_mapped_file.h" #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include "base/logging.h" #include "base/posix/eintr_wrapper.h" namespace base { MemoryMappedFile::MemoryMappedFile() : file_(kInvalidPlatformFileValue), data_(NULL), length_(0) { } bool MemoryMappedFile::MapFileToMemoryInternal() { // ThreadRestrictions::AssertIOAllowed(); struct stat file_stat; if (fstat(file_, &file_stat) == kInvalidPlatformFileValue) { DPLOG(ERROR) << "fstat " << file_; return false; } length_ = file_stat.st_size; data_ = static_cast<uint8*>( mmap(NULL, length_, PROT_READ, MAP_SHARED, file_, 0)); if (data_ == MAP_FAILED) DPLOG(ERROR) << "mmap " << file_; return data_ != MAP_FAILED; } void MemoryMappedFile::CloseHandles() { // ThreadRestrictions::AssertIOAllowed(); if (data_ != NULL) munmap(data_, length_); if (file_ != kInvalidPlatformFileValue) ignore_result(HANDLE_EINTR(close(file_))); data_ = NULL; length_ = 0; file_ = kInvalidPlatformFileValue; } } // namespace base
[ "mycloudpeak@outlook.com" ]
mycloudpeak@outlook.com
eea373eca4deab524ae69dab299af1d1ad58890c
2979ffab1670cc0dcacb38abccf8a29cd50aa291
/server/log.cpp
96820cef7660503891f83c2f73cd714f0fd4704e
[]
no_license
slazav/eventdb
43b098197bc571b50b0e48d004b0d590fca64139
1eac5ff2969e086f7cfbe3daa164f73bd4f633ec
refs/heads/master
2021-01-17T08:53:18.186082
2016-11-07T23:21:48
2016-11-07T23:21:48
7,232,079
1
0
null
null
null
null
UTF-8
C++
false
false
621
cpp
#include <string> #include <fstream> #include <cstdio> /* snprintf */ using namespace std; /* string with current date and time */ string time_str(){ char tstr[25]; time_t lt; time (&lt); struct tm * t = localtime(&lt); snprintf(tstr, sizeof(tstr), "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); return string(tstr); } // add the message to the log file void log(const string & fname, const string & msg){ if (fname.length()==0) return; ofstream out(fname.c_str(), ios::app); out << time_str() << " " << msg << endl; }
[ "slazav@altlinux.org" ]
slazav@altlinux.org
2c08df35d489dace2767b27ab815d3f3beb5626a
0168c2e81b666112a8cabbad058b39b4f924ef8e
/ffmpeg/ffmpeg/src/simplest_ffmpeg_audio_player/simplest_ffmpeg_audio_player.cpp
01948ba5bfb81ed78901601ff0205bfea223e246
[ "MIT" ]
permissive
jisudong/LearnFFmpeg
e8f4e3a8e0b544108850a5ce4bc29a234cb02c93
2c0ff184308c038e7cd21b691df23b74d33f0dfc
refs/heads/master
2022-07-03T17:01:05.982793
2022-06-09T07:34:47
2022-06-09T07:34:47
206,207,967
1
1
MIT
2019-12-06T08:13:44
2019-09-04T01:53:45
C
UTF-8
C++
false
false
5,312
cpp
// // simplest_ffmpeg_audio_player.cpp // ffmpeg // // Created by apple on 2019/12/24. // Copyright © 2019 apple. All rights reserved. // #include "simplest_ffmpeg_audio_player.hpp" extern "C" { #include <SDL2/SDL.h> #include <libavformat/avformat.h> #include <libavcodec/avcodec.h> #include <libswresample/swresample.h> } #define MAX_AUDIO_FRAME_SIZE 192000 // 1 second of 48khz 32bit audio //Output PCM #define OUTPUT_PCM 0 //Use SDL #define USE_SDL 1 //Buffer: //|-----------|-------------| //chunk-------pos---len-----| static Uint8 *audio_chunk; static Uint32 audio_len; static Uint8 *audio_pos; void audio_callback(void *udata, Uint8 *stream, int len) { SDL_memset(stream, 0, len); if (audio_len == 0) { return; } len = len > audio_len ? audio_len : len; SDL_MixAudio(stream, audio_pos, len, SDL_MIX_MAXVOLUME); audio_pos += len; audio_len -= len; } int audio_player() { AVFormatContext *pFormatCtx = NULL; AVCodecContext *pCodecCtx = NULL; AVCodec *pCodec = NULL; AVFrame *pFrame = NULL; AVPacket *pkt; SwrContext *audio_convert_ctx = NULL; SDL_AudioSpec wanted_spec, spec; int audioStream = -1; int got_frame = 0; int index = 0; int64_t in_channel_layout; uint8_t *out_buffer; char url[] = "Titanic.mkv"; #if OUTPUT_PCM FILE *pFile = NULL; #endif av_register_all(); avformat_network_init(); pFormatCtx = avformat_alloc_context(); if (avformat_open_input(&pFormatCtx, url, NULL, NULL) != 0) { return -1; } if (avformat_find_stream_info(pFormatCtx, NULL) < 0) { return -1; } av_dump_format(pFormatCtx, 0, url, 0); for (int i = 0; i < pFormatCtx->nb_streams; i++) { if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { audioStream = i; break; } } if (audioStream == -1) { return -1; } pCodecCtx = pFormatCtx->streams[audioStream]->codec; pCodec = avcodec_find_decoder(pCodecCtx->codec_id); if (pCodec == NULL) { return -1; } if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) { return -1; } #if OUTPUT_PCM pFile = fopen("output.pcm", "wb"); #endif pkt = (AVPacket *)malloc(sizeof(AVPacket)); av_init_packet(pkt); uint64_t out_channel_layout = AV_CH_LAYOUT_STEREO; int out_nb_samples = pCodecCtx->frame_size; AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16; int out_sample_rate = 44100; int out_channels = av_get_channel_layout_nb_channels(out_channel_layout); int out_buffer_size = av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, out_sample_fmt, 1); out_buffer = (uint8_t *)av_malloc(MAX_AUDIO_FRAME_SIZE * 2); pFrame = av_frame_alloc(); #if USE_SDL if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_TIMER)) { return -1; } wanted_spec.freq = out_sample_rate; wanted_spec.format = AUDIO_S16SYS; wanted_spec.channels = out_channels; wanted_spec.silence = 0; wanted_spec.samples = out_nb_samples; wanted_spec.callback = audio_callback; wanted_spec.userdata = NULL; if (SDL_OpenAudio(&wanted_spec, &spec) < 0) { return -1; } #endif in_channel_layout = av_get_default_channel_layout(pCodecCtx->channels); audio_convert_ctx = swr_alloc(); if (audio_convert_ctx) { swr_alloc_set_opts(audio_convert_ctx, out_channel_layout, out_sample_fmt, out_sample_rate, in_channel_layout, pCodecCtx->sample_fmt, pCodecCtx->sample_rate, 0, NULL); } swr_init(audio_convert_ctx); SDL_PauseAudio(0); while (av_read_frame(pFormatCtx, pkt) >= 0) { if (pkt->stream_index == audioStream) { avcodec_decode_audio4(pCodecCtx, pFrame, &got_frame, pkt); if (got_frame) { swr_convert(audio_convert_ctx, &out_buffer, MAX_AUDIO_FRAME_SIZE, (const uint8_t **)pFrame->data, pFrame->nb_samples); printf("index:%5d\t pts:%lld\t packet size:%d\n", index, pkt->pts,pkt->size); #if OUTPUT_PCM fwrite(out_buffer, 1, out_buffer_size, pFile); #endif index++; } #if USE_SDL while (audio_len > 0) { SDL_Delay(1); } audio_chunk = (Uint8 *)out_buffer; audio_len = out_buffer_size; audio_pos = audio_chunk; #endif } av_free_packet(pkt); } swr_free(&audio_convert_ctx); #if USE_SDL SDL_CloseAudio(); SDL_Quit(); #endif #if OUTPUT_PCM fclose(pFile); #endif av_free(out_buffer); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); return 0; }
[ "coderjee@163.com" ]
coderjee@163.com
ed559d19acca53be121c551962f7406b559d09d2
20f69b8a86c1e44cc1c34e62e5e9b851feb43811
/Error.cpp
f63678db6335f3b4ca35db1a4d8c521438054b74
[]
no_license
ShylyukDavid/labs
134dea404c4da861a211aeb52eab9b1b51266008
2ba772c5554f14aa2a480403fd6a9eccc1e16373
refs/heads/master
2020-04-16T16:22:36.831829
2019-01-14T21:00:52
2019-01-14T21:00:52
165,734,149
0
0
null
null
null
null
UTF-8
C++
false
false
690
cpp
/*********************************************************************** * Module: Error.cpp * Author: is7222 * Modified: Thursday, January 10, 2019 10:28:13 AM * Purpose: Implementation of the class Error ***********************************************************************/ #include "Error.h" Error::Error(int i) :type(i){ } void Error::SearchError() { switch (type){ case 1: LowPoints(); break; } } void Error::LowPoints(void) { printf("\n\nPoints are less than 60. Student can`t study more"); } void Error::LowFinancing(void) { // TODO : implement } void Error::LowAttractedPeople(void) { // TODO : implement }
[ "noreply@github.com" ]
noreply@github.com
53b0d631e2c4438307c34b98a43a9138bd45bf86
170d69d53485c247f691030e2b06e26ce624e7e9
/Documentos/alambres_03.cpp
c11da32fce1ff80d6c3352ac8b5f42643278d100
[]
no_license
pelanmar1/GPC
8f09c277d39d3a9f926633121d46f644cd4236c9
ffafd46dff3078867039aba0b45b215da9bfdc0a
refs/heads/master
2021-08-20T09:21:40.219106
2017-11-28T19:12:57
2017-11-28T19:12:57
102,777,597
0
0
null
null
null
null
UTF-8
C++
false
false
10,778
cpp
//======================================================================== // Simple GLFW example // Copyright (c) Camilla Berglund <elmindreda@elmindreda.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // //======================================================================== //! [code] #include <GLFW/glfw3.h> #include <linmath.h> #include <stdlib.h> #include <stdio.h> static void error_callback(int error, const char* description) { fputs(description, stderr); } // Variables Globales float GLOBAL_Tz = 0.f; float GLOBAL_Fov = 35.0f; float GLOBAL_Rc = 2.0f; static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { //if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) if(action == GLFW_REPEAT || action == GLFW_PRESS) switch (key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, GL_TRUE); break; case GLFW_KEY_0: GLOBAL_Fov += 1.f; break; case GLFW_KEY_1: GLOBAL_Fov -= 1.f; break; case GLFW_KEY_UP: GLOBAL_Rc -= 0.025f; break; case GLFW_KEY_DOWN: GLOBAL_Rc += 0.025f; break; } } GLfloat f_esfera(float x) { //return 0.25f; return (GLfloat)sqrt(0.0625f - (x - 0.5f) * (x - 0.5f)); } GLfloat f_cilindro(float x) { return (GLfloat) 0.05f; } GLfloat f_cono(float x) { return (GLfloat)(0.5f * (x - 0.25f)); } void inyectaSolidoDeRevolucion(GLfloat f(float x), GLfloat color[]) { GLenum modo = GL_LINE_LOOP; float x, fx, y, z, deltaX, x0 = 0.25f, x1 = 0.75f; float t, deltaT; float *p_ant, *p, *p_temp; int k, j, m = 25, n = 10; deltaX = (x1 - x0) / n; deltaT = 6.2832f / m; p_ant = (float*)malloc(3 * (m + 1) * sizeof(float)); p = (float*)malloc(3 * (m + 1) * sizeof(float)); if (!p_ant || !p) { printf("Fracasó por falta de memoria al inyectar un Sólido de Revolución...\n"); exit(1); } for (k = 0; k <= n; k++) { x = x0 + k * deltaX; fx = f(x); glBegin(modo); glColor3f(color[0], color[1], color[2]); for (j = 0; j <= m; j++) { t = j * deltaT; y = fx * cosf(t); z = fx * sinf(t); p[3 * j] = x; p[3 * j + 1] = y; p[3 * j + 2] = z; glVertex3f(x, y, z); } glEnd(); if (k > 0) { glBegin(modo); for (j = 0; j < m; j++) { glVertex3f(p[3 * j + 0], p[3 * j + 1], p[3 * j + 2]); glVertex3f(p_ant[3 * j + 0], p_ant[3 * j + 1], p_ant[3 * j + 2]); } glEnd(); } // paso la rodaja actual a la rodaja anterior sin perder los lugares. p_temp = p; p = p_ant; p_ant = p_temp; } // libero la memoria free(p); free(p_ant); } void inyectaPoliedro() { GLenum modo = GL_LINE_LOOP; /* // CARA I (FRONT) glBegin(modo); glColor3f(1.f, 0.f, 0.f); glVertex3f(0.5f, 0.5f, 0.5f); glVertex3f(-0.5f, 0.5f, 0.5f); glVertex3f(-0.5f, -0.5f, 0.5f); glVertex3f(0.5f, -0.5f, 0.5f); //glVertex3f(0.5f, 0.5f, 0.5f); glEnd(); // CARA II (REAR) glBegin(modo); glColor3f(0.f, 1.f, 0.f); glVertex3f(0.5f, 0.5f, -0.5f); //glColor3f(0.f, 1.f, 0.f); glVertex3f(-0.5f, 0.5f, -0.5f); //glColor3f(0.f, 1.f, 0.f); glVertex3f(-0.5f, -0.5f, -0.5f); //glColor3f(0.f, 1.f, 0.f); glVertex3f(0.5f, -0.5f, -0.5f); //glColor3f(0.f, 1.f, 0.f); //glVertex3f(0.5f, 0.5f, -0.5f); glEnd(); */ // CARA III (TOP) glBegin(modo); glColor3f(1.f, 1.f, 1.f); glVertex3f(0.5f, 0.5f, 0.5f); glVertex3f(0.5f, 0.5f, -0.5f); glVertex3f(-0.5f, 0.5f, -0.5f); glVertex3f(-0.5f, 0.5f, 0.5f); glEnd(); // CARA IV (BOTTOM) glBegin(modo); glColor3f(0.f, 1.f, 0.f); glVertex3f(0.5f, -0.5f, 0.5f); glVertex3f(0.5f, -0.5f, -0.5f); glVertex3f(-0.5f, -0.5f, -0.5f); glVertex3f(-0.5f, -0.5f, 0.5f); glEnd(); /* // CARA V (LEFT) glBegin(modo); glColor3f(0.f, 1.f, 1.f); glVertex3f(0.5f, 0.5f, 0.5f); //glColor3f(0.f, 1.f, 1.f); glVertex3f(0.5f, -0.5f, 0.5f); //glColor3f(0.f, 1.f, 1.f); glVertex3f(0.5f, -0.5f, -0.5f); //glColor3f(0.f, 1.f, 1.f); glVertex3f(0.5f, 0.5f, -0.5f); //glColor3f(0.f, 1.f, 1.f); //glVertex3f(0.5f, 0.5f, 0.5f); glEnd(); // CARA VI (RIGHT) glBegin(modo); glColor3f(1.f, 1.f, 1.f); glVertex3f(-0.5f, 0.5f, 0.5f); //glColor3f(1.f, 1.f, 1.f); glVertex3f(-0.5f, -0.5f, 0.5f); //glColor3f(1.f, 1.f, 1.f); glVertex3f(-0.5f, -0.5f, -0.5f); //glColor3f(1.f, 1.f, 1.f); glVertex3f(-0.5f, 0.5f, -0.5f); //glColor3f(1.f, 1.f, 1.f); //glVertex3f(-0.5f, 0.5f, 0.5f); glEnd(); */ // FIN DEL POLIEDRO } void inyectaOtroPoliedro() { const GLfloat model_diffuse[4] = { 1.0f, 0.8f, 0.8f, 1.0f }; const GLfloat model_specular[4] = { 0.6f, 0.6f, 0.6f, 1.0f }; const GLfloat model_shininess = 20.0f; // Set model material (used for perspective view, lighting enabled) GLenum modo = GL_TRIANGLE_FAN; glBegin(modo); glMaterialfv(GL_FRONT, GL_DIFFUSE, model_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, model_specular); glMaterialf(GL_FRONT, GL_SHININESS, model_shininess); glColor3f(1.f, 1.f, 1.f); glNormal3f(0.f, 0.f, 1.f); glVertex3f(0.5f, 0.0f, 0.5f); glColor3f(1.f, 0.f, 0.f); glNormal3f(0.f, 0.f, 1.f); glVertex3f(0.2f, 0.3f, 0.0f); glColor3f(0.f, 1.f, 0.f); glNormal3f(0.f, 0.f, 1.f); glVertex3f(0.2f, -0.3f, 0.0f); glColor3f(0.f, 0.f, 1.f); glNormal3f(0.f, 0.f, 1.f); glVertex3f(0.8f, -0.3f, 0.0f); glColor3f(1.f, 1.f, 0.f); glNormal3f(0.f, 0.f, 1.f); glVertex3f(0.8f, 0.3f, 0.0f); glEnd(); } int main(void) { GLFWwindow* window; mat4x4 Rid, Rx, Ry, Rz, Rtot; mat4x4 Sxyz, Tx, Txloc, Rzloc; const GLfloat light_position[4] = { -0.1f, 0.0f, 0.5f, 1.0f }; const GLfloat light_diffuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; const GLfloat light_specular[4] = { 1.0f, 0.5f, 0.5f, 1.0f }; const GLfloat light_ambient[4] = { 0.2f, 0.2f, 0.3f, 1.0f }; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetKeyCallback(window, key_callback); float alfa_z = 0.f; float fk = 0.1f; while (!glfwWindowShouldClose(window)) { float ratio; float tiempo_t; float radX, radY, radZ; int width, height; float Rc, x_eye,y_eye,z_eye,T,theta; float blanco[] = { 1.f, 1.f, 1.f }; float rojo[] = { 1.f, 0.f, 0.f }; float verde[] = { 0.f, 1.f, 0.f }; float azul[] = { 0.f, 0.f, 1.f }; tiempo_t = (float)glfwGetTime(); radX = tiempo_t * 10.0f * 3.14159f / 180.f; radY = tiempo_t * 20.0f * 3.14159f / 180.f; radZ = tiempo_t * 30.0f * 3.14159f / 180.f; glfwGetFramebufferSize(window, &width, &height); ratio = width / (float)height; glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); // ==================================================== glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Enable face culling (faster rendering) glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CCW); vec3 eye; //= { 0.0f,0.0f,0.125f}; vec3 target = {0.0f,0.0f,-2.5f}; vec3 up = {0.0f,1.0f,0.0f}; Rc = 2.0f; T = 10.0F; // en "segundos" theta = 6.2832 / T * tiempo_t; x_eye = GLOBAL_Rc * sinf(theta); y_eye = sinf(0.5f * tiempo_t); z_eye = GLOBAL_Rc * cosf(theta) - 2.5f; eye[0] = x_eye; eye[1] = y_eye; eye[2] = z_eye; glMatrixMode(GL_PROJECTION); glLoadIdentity(); //glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f); mat4x4 Rview,Rat,Rp; mat4x4_look_at(Rat, eye, target, up); mat4x4_perspective(Rp, (float)(GLOBAL_Fov*3.1416 / 180.0), 800.0f/600.0f, 0.2f, 100.0f); mat4x4_mul(Rview, Rp, Rat); glMultMatrixf(Rview); // Configure and enable light source 1 glLightfv(GL_LIGHT1, GL_POSITION, light_position); glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular); glEnable(GL_LIGHT1); glEnable(GL_LIGHTING); // ==================================================== glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //glRotatef( tiempo_t * 50.f, 1.f, 0.f, 0.f); mat4x4_identity(Rid); mat4x4_rotate_X(Rx, Rid, radX); mat4x4_rotate_Y(Ry, Rid, radY); alfa_z += fk * GLOBAL_Tz * 3.14159f / 180.f; mat4x4_rotate_Z(Rz, Rid, alfa_z); //mat4x4_mul(Rtot, Ry, Rx); //mat4x4_mul(Rtot, Rz, Rtot); //mat4x4_mul(Rtot, Tx, Ry ); //mat4x4_mul(Rtot, Sxyz, Rtot); mat4x4_rotate_Z(Rzloc, Rid, 4.f*radZ); mat4x4_translate(Txloc, -0.5f, 0.f, 0.f); mat4x4_scale_aniso(Sxyz, Rid, 0.25, 0.25, 0.25); mat4x4_translate(Tx, 0.75f, 0.f, 0.f); mat4x4_mul(Rtot, Txloc, Rid); mat4x4_mul(Rtot, Sxyz, Rtot); //mat4x4_mul(Rtot, Rzloc, Rtot); mat4x4_mul(Rtot, Ry, Rtot); mat4x4_mul(Rtot, Tx, Rtot); mat4x4_mul(Rtot, Rz, Rtot); glMultMatrixf(Txloc); mat4x4 Tzv; mat4x4_translate(Tzv, 0.f, 0.f, -2.5f); glMultMatrixf(Tzv); //glMultMatrixf(Rtot); /* glMultMatrixf(Rz); glMultMatrixf(Tx); glMultMatrixf(Sxyz); glMultMatrixf(Rzloc); glMultMatrixf(Ry); glMultMatrixf(Rx); glMultMatrixf(Txloc); */ /* glBegin(GL_POLYGON); glColor3f(1.f, 0.f, 0.f); glVertex3f(0.5f, 0.5f, 0.5f); glColor3f(0.f, 1.0f, 0.f); glVertex3f(-0.5f, 0.5f, 0.5f); glColor3f(0.f, 0.f, 1.f); glVertex3f(-0.5f, -0.5f, 0.5f); glColor3f(1.f, 1.f, 1.f); glVertex3f(0.5f, -0.5f, 0.5f); //glColor3f(1.f, 0.f, 0.f); //glVertex3f(0.5f, 0.5f, 0.5f); glEnd(); glBegin(GL_POLYGON); glColor3f(1.f, 0.f, 0.f); glVertex3f(0.5f, 0.5f, -0.5f); glColor3f(0.f, 1.0f, 0.f); glVertex3f(-0.5f, 0.5f, -0.5f); glColor3f(0.f, 0.f, 1.f); glVertex3f(-0.5f, -0.5f, -0.5f); glColor3f(1.f, 1.f, 1.f); glVertex3f(0.5f, -0.5f, -0.5f); //glColor3f(1.f, 0.f, 0.f); //glVertex3f(0.5f, 0.5f, -0.5f); glEnd(); */ //inyectaPoliedro(); inyectaOtroPoliedro(); //inyectaSolidoDeRevolucion(&f_cilindro, blanco); //inyectaSolidoDeRevolucion(&f_cono, verde); //inyectaSolidoDeRevolucion(&f_esfera, rojo); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } //! [code]
[ "sdist@itam.mx" ]
sdist@itam.mx
3a5b9ae2177065c504860eca2003697c1747bc72
aab7eafab5efae62cb06c3a2b6c26fe08eea0137
/prepare_misidvariations/FUMSB_simultaneous_NewTCK_misidvariation/src/addingcrossfeedbranch.cpp
dbb81e901a6f1eed4be58a2f722220a87948b815
[]
no_license
Sally27/B23MuNu_backup
397737f58722d40e2a1007649d508834c1acf501
bad208492559f5820ed8c1899320136406b78037
refs/heads/master
2020-04-09T18:12:43.308589
2018-12-09T14:16:25
2018-12-09T14:16:25
160,504,958
0
1
null
null
null
null
UTF-8
C++
false
false
102,499
cpp
#include<iostream> #include<algorithm> #include "TH1F.h" #include "TH2F.h" #include "TCanvas.h" #include "TFile.h" #include "TTree.h" #include "TLorentzVector.h" #include "TVector3.h" #include "TBranch.h" #include "TRandom.h" #include "TString.h" #include <string> #include <iostream> #include<sstream> #include<string> #include<vector> #include<fstream> #include "TH3F.h" #include <numeric> #include "TGraph.h" #include <sstream> #include <iostream> #include "TMath.h" #include <vector> #include <string> #include "TLegend.h" #include "TStyle.h" #include "TTreeFormula.h" #include "TPad.h" #include "TLine.h" #include "TRandom3.h" using namespace std; vector<double> binx(); vector<double> biny(); vector<double> binz(); vector<double> jackpion(); vector<double> jackkaon(); vector<double> jackproton(); //string cleanNameString(string str) //{ // size_t st(0); // // string toreplace(" */#.,[]{}()+-=:&"); // for(int i(0); i<toreplace.size(); ++i) // { // while(st != string::npos) // { // st = str.find(toreplace[i]); // if(st!=string::npos) str = str.replace(st, 1, "_"); // } // st = 0; // } // // return str; //} string cleanNameString(string str) { size_t st(0); string toreplace(" */#.,[]{}()+-=:"); for(int i(0); i<toreplace.size(); ++i) { while(st != string::npos) { st = str.find(toreplace[i]); if(st!=string::npos) str = str.replace(st, 1, "_"); } st = 0; } return str; } double s2d(string str) { double ret; istringstream is(str); is >> ret; return ret; } string bool_cast(const bool b) { ostringstream ss; ss << boolalpha << b; return ss.str(); } string d2s(double d) { string ret; ostringstream os; os<<d; return os.str(); } string f2s(float d) { string ret; ostringstream os; os<<d; return os.str(); } string i2s(int i) { string ret; ostringstream os; os<<i; return os.str(); } vector<float> crossmisid(string filename, string cuts, int p, int eta, string polarity, string stripping) { TFile s(filename.c_str()); TH2F *hname =(TH2F*)s.Get(cuts.c_str()); vector<float> effi; Double_t myaverage(0); Int_t z(0); TCanvas canv("plot",("crossmisid"+filename).c_str(),600,600); hname->Draw(); canv.Print("crossmisid.pdf"); for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { // for (int k=1; k<(ntracks+1); k++) { effi.push_back(hname->GetBinContent(i,j)); cout<<"K to pi misid: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << endl; cout<<"This is z:" << z <<endl; myaverage+=effi.at(z); z++; // } } } TCanvas *c1 = new TCanvas("c1","c1",600,600); hname->Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); c1->SaveAs(("PID_HeatMap_Type2_"+polarity+"_"+stripping+"_"+cleanNameString(cuts)+".pdf").c_str()); delete c1; TFile *F1 = new TFile("append.root","UPDATE"); hname->Write("", TObject::kOverwrite); F1->Close(); return(effi); } float avcrossmisid(string filename, string cuts, int p, int eta) { TFile s(filename.c_str()); TH2F *hname =(TH2F*)s.Get(cuts.c_str()); vector<float> effi; Double_t myaverage(0); Int_t z(0); TCanvas canv("plot",("crossmisid"+filename).c_str(),600,600); hname->Draw(); canv.Print("crossmisid.pdf"); for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { // for (int k=1; k<(ntracks+1); k++) { effi.push_back(hname->GetBinContent(i,j)); cout<<"K to pi misid: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; myaverage+=effi.at(z); z++; // } } } float aveff; aveff=(myaverage/72); //TFile *F1 = new TFile("append.root","UPDATE"); //hname->Write("", TObject::kOverwrite); //F1->Close(); return(aveff); } vector<float> jackefficiency(string filename, string cuts, int p, int eta, string species) { TFile s(filename.c_str()); TH2F *hname =(TH2F*)s.Get(cuts.c_str()); vector<float> effi; Double_t myaverage(0); Int_t z(0); vector<double> pionmisidinside; cout<<"THIS IS MY SPECIES "<<species<<endl; if (species=="pion"){ pionmisidinside = jackpion(); } else if (species=="kaon"){ pionmisidinside = jackkaon(); } else if (species=="proton"){ pionmisidinside = jackproton(); } vector<double> pionmisid; pionmisid=pionmisidinside; for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { // for (int k=1; k<(ntracks+1); k++) { effi.push_back(hname->GetBinContent(i,j)*float(pionmisid.at(i))); cout<<filename<<cuts<<"ID rate: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << endl; cout<<"This is z:" << z <<endl; myaverage+=effi.at(z); // if (effi[z]<0) // { // cout<<"Alarm!!!!: efficiency: "<< effi[z] <<endl; // effi[z]=0.0001; // cout<<"Changed efficiency: "<< effi[z] << endl; // } z++; // } } } TFile *F1 = new TFile("append.root","UPDATE"); hname->Write("", TObject::kOverwrite); F1->Close(); return(effi); } void createPIDvariation(string filename, string cuts, int p, int eta, string polarity, string stripping, int toy) { TRandom3 *gRandom = new TRandom3(); for (int ntoy(0); ntoy<toy; ntoy++) { TFile* s = new TFile((filename).c_str(),"READ"); if(!s){cerr<<"no file found"<<endl;return;} TH2F *hname =(TH2F*)s->Get(cuts.c_str()); if(!hname){cerr<<"no hist found"<<endl;return;} vector<float> effi; Int_t z(0); cout<<"Creating Histogram "<<ntoy<<endl; TFile *F1 = new TFile(("../generatedtuples/"+stripping+"_"+cleanNameString(cuts)+"_"+i2s(ntoy)+".root").c_str(),"RECREATE"); TH2D* newPIDhist =(TH2D*)hname->Clone(); newPIDhist->SetName((cleanNameString(cuts)+"_new").c_str()); for (int i(1); i<(p+1); i++) { double newvalue(0); newvalue=gRandom->Gaus(hname->GetBinContent(i,1),hname->GetBinError(i,1)); //because only one bin of eta for (int j(1); j<(eta+1); j++) { //because only one bin of eta newPIDhist->SetBinContent(i,j,newvalue); cout<<filename<<cuts<<"ID rate: " << hname->GetBinContent(i,j)<<" with error "<<hname->GetBinError(i,j)<< " in a bin i , j , k:" << i << " " << j << endl; cout<<"Filling with "<<newvalue<<endl; } } newPIDhist->Write("", TObject::kOverwrite); F1->Close(); delete(F1); s->Close(); delete(s); } } void plotPIDvariation(string filename, string cuts, int p, int eta, string polarity, string stripping, int toy) { for (int i(1); i<(p+1); i++) { for (int j(1); j<(eta+1); j++) { TH1F *hist = new TH1F(("Distribution_Bin_Momentum_"+i2s(i)+"_Eta"+i2s(j)).c_str(),"Distribution",100,0.0,0.01); for (int ntoy(0); ntoy<toy; ntoy++) { TFile* s = new TFile(("../generatedtuples/"+stripping+"_"+cleanNameString(cuts)+"_"+i2s(ntoy)+".root").c_str(),"READ"); if(!s){cerr<<"no file found"<<endl;return;} TH2F *hname =(TH2F*)s->Get((cleanNameString(cuts)+"_new").c_str()); if(!hname){cerr<<"no hist found"<<endl;return;} vector<float> effi; Int_t z(0); float value(0); value=hname->GetBinContent(i,j); cout<<"Value is "<<value<<endl; hist->Fill(value); s->Close(); delete(s); } // hist->Draw(); TCanvas *c1 =new TCanvas("c1","random",5,5,800,600); hist->Draw(); c1->Update(); TFile* ori = new TFile((filename).c_str(),"READ"); if(!ori){cerr<<"no file found"<<endl;return;} TH2F *hnameori =(TH2F*)ori->Get(cuts.c_str()); if(!hnameori){cerr<<"no hist found"<<endl;return;} TLine *l = new TLine(double(hnameori->GetBinContent(i,j)),c1->GetUymin(),double(hnameori->GetBinContent(i,j)),c1->GetUymax()); l->SetLineColor(kRed); l->SetLineWidth(4); l->Draw(); c1->Update(); TLine *l2 = new TLine(double(hnameori->GetBinContent(i,j))-double(hnameori->GetBinError(i,j)),0.0,double(hnameori->GetBinContent(i,j))+double(hnameori->GetBinError(i,j)),0.0); l2->SetLineColor(kRed); l2->SetLineWidth(4); l2->Draw(); c1->SaveAs(("../generatedplots/"+stripping+"_"+cleanNameString(cuts)+"_RandomDistribution_Bin_Momentum_"+i2s(i)+"_Eta"+i2s(j)+".pdf").c_str()); delete ori; delete l; delete l2; delete hist; delete c1; } } } vector<float> efficiency(string filename, string cuts, int p, int eta, string polarity, string stripping) { TFile s(filename.c_str()); TH2F *hname =(TH2F*)s.Get(cuts.c_str()); vector<float> effi; Double_t myaverage(0); Int_t z(0); for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { effi.push_back(hname->GetBinContent(i,j)); cout<<filename<<cuts<<"ID rate: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << endl; cout<<"This is z:" << z <<endl; myaverage+=effi.at(z); z++; } } TCanvas *c1 = new TCanvas("c1","c1",600,600); hname->Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); c1->SaveAs(("PID_HeatMap_Type2_"+stripping+"_"+polarity+"_"+cleanNameString(cuts)+".pdf").c_str()); TFile *F1 = new TFile("append.root","UPDATE"); hname->Write("", TObject::kOverwrite); F1->Close(); delete c1; delete F1; return(effi); } double averageefficiency(string filename, string cuts, int p, int eta) { TFile s(filename.c_str()); TH2F *hname =(TH2F*)s.Get(cuts.c_str()); vector<float> effi; Double_t myaverage(0); Int_t z(0); for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { // for (int k=1; k<(ntracks+1); k++) { effi.push_back(hname->GetBinContent(i,j)); cout<<filename<<cuts<<"ID rate: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; myaverage+=effi.at(z); z++; // } } } Double_t average; average = (myaverage/double(p*eta)); cout<<"Average efficiency of sample: "<<filename<<" with cut "<< cuts << "is: " <<average<<endl; return(average); } vector<float> misefficiency(string filename, string cuts, int p, int eta) { TFile s(filename.c_str()); TH3F *hname =(TH3F*)s.Get(cuts.c_str()); vector<float> effi; Double_t myaverage(0); Int_t z(0); for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { // for (int k=1; k<(ntracks+1); k++) { effi.push_back(hname->GetBinContent(i,j)); cout<<filename<<cuts<<"Mis-ID rate: " << effi.at(z) << " in a bin i , j " << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; myaverage+=effi.at(z); // if (effi[z]<0) // { // cout<<"Alarm!!!!: efficiency: "<< effi[z] <<endl; // effi[z]=0.0001; // cout<<"Changed efficiency: "<< effi[z] << endl; // } z++; // } } } return(effi); } void cutTree(string nametree, string decaytreename, string namecuttree, string cuts) { TFile f(nametree.c_str()); TTree* t = (TTree*)f.Get(decaytreename.c_str()); TFile f2(namecuttree.c_str(), "RECREATE"); TTree* t2 = t->CloneTree(0); TTreeFormula ttf("ttf", cuts.c_str(), t); cout<<"Cutting tree "<<nametree<<endl; cout<<"Cut applied: "<<cuts<<endl; for(int i(0); i<t->GetEntries(); ++i) { // if(i % (t->GetEntries()/10) == 0) cout<<100*i/(t->GetEntries())<<" \% processed"<<endl; t->GetEntry(i); if(ttf.EvalInstance()) t2->Fill(); } double effofcut; effofcut = double(t2->GetEntries())/double(t->GetEntries()); cout<<"Efficiency of cut"<< cuts << " wrt " << nametree << " is: " << effofcut << endl; t2->Write("",TObject::kOverwrite); f2.Close(); f.Close(); } void addmultiplicationofbranches(string filename, string decaytree, string branch1, string branch2, string varname) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t branch11, branch22; t->SetBranchAddress((branch1).c_str(), &branch11); t->SetBranchAddress((branch2).c_str(), &branch22); TFile *g = new TFile((filename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t variable; newtree->Branch(varname.c_str(),&variable,"variable/D"); for(int i=0; i<t->GetEntries(); ++i) { t->GetEntry(i); variable=branch11*branch22; newtree->Fill(); } g->Write("",TObject::kOverwrite); g->Close(); f->Close(); } void addrealweight(string filename, string decaytree, string variable, string weight, string varname, string species) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t branchvariable, branchweight; t->SetBranchAddress((variable).c_str(), &branchvariable); t->SetBranchAddress((weight).c_str(), &branchweight); TFile *g = new TFile("ht.root","UPDATE"); TTree *newtree = new TTree("newtree","test"); TH1D *CorrMreweigh = new TH1D(("CorrMreweigh"+species).c_str(),("CorrMreweigh"+species).c_str(),100,0,10000); newtree->Branch(("CorrMreweigh"+species).c_str(),"TH1D",&CorrMreweigh,2560000,0); for(int i=0; i<t->GetEntries(); ++i) { t->GetEntry(i); CorrMreweigh->Fill(branchvariable,branchweight); cout<<"Branch Variable: "<<branchvariable<<" and Branch Weight: "<<branchweight<<endl; newtree->Fill(); } cout<<"Integral for the species : " << species << " is " << CorrMreweigh->Integral()<<endl; newtree->Print(); g->Write("",TObject::kOverwrite); g->Close(); f->Close(); } void addproductbranches(string filename, string decaytree, string branch1, string branch2, string varname) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t branch11, branch22; t->SetBranchAddress((branch1).c_str(), &branch11); t->SetBranchAddress((branch2).c_str(), &branch22); TFile *g = new TFile((filename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t variable; newtree->Branch(varname.c_str(),&variable,"variable/D"); for(int i=0; i<t->GetEntries(); ++i) { t->GetEntry(i); variable=branch11*branch22; newtree->Fill(); } g->Write("",TObject::kOverwrite); g->Close(); f->Close(); } void addratiofbranches(string filename, string decaytree, string branch1, string branch2, string varname) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t branch11, branch22; t->SetBranchAddress((branch1).c_str(), &branch11); t->SetBranchAddress((branch2).c_str(), &branch22); TFile *g = new TFile((filename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t variable; newtree->Branch(varname.c_str(),&variable,"variable/D"); for(int i=0; i<t->GetEntries(); ++i) { t->GetEntry(i); variable=branch11/branch22; newtree->Fill(); } g->Write("",TObject::kOverwrite); g->Close(); f->Close(); } void addnormalbranchweight(string filename, string decaytree, string branch1, string varname) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t branch11; t->SetBranchAddress((branch1).c_str(), &branch11); TFile *g = new TFile((filename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); vector<double> myunnormalized; Double_t variable; double h(0); double largestprob; double scalefac; newtree->Branch(varname.c_str(),&variable,"variable/D"); for(int i=0; i<t->GetEntries(); ++i) { t->GetEntry(i); cout<<"Branch 11:"<<branch11<<endl; myunnormalized.push_back(branch11); h+=branch11; } largestprob=*std::max_element(myunnormalized.begin(),myunnormalized.end()); std::cout << "The largest element in the probability is: " << *std::max_element(myunnormalized.begin(),myunnormalized.end()) << endl; scalefac=1.0/largestprob; std::cout << "Scale factor: " << scalefac <<endl; vector<double> mynormalized; for(int i=0; i<t->GetEntries(); ++i) { t->GetEntry(i); variable=branch11*scalefac; mynormalized.push_back(variable); cout<<"pretty: "<<variable<< " branch11: "<<branch11<<" scalefac: "<<scalefac<<endl; newtree->Fill(); } double largestweight; largestweight=*std::max_element(mynormalized.begin(),mynormalized.end()); std::cout << "The largest weight is: " << largestweight << endl; g->Write("",TObject::kOverwrite); g->Close(); f->Close(); } vector<float> newbinmydata(string filename, string decaytree, string species) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); TCanvas *canv=new TCanvas("plotmy3d","plotmy3d",600,600); Double_t mu3_P, mu3_ETA, Bplus_Corrected_Mass; // Int_t nTracks; t->SetBranchAddress("mu3_P", &mu3_P); t->SetBranchAddress("mu3_ETA", &mu3_ETA); // t->SetBranchAddress("nTracks", &nTracks); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); int p=18; // int eta=4; // int ntracks=4; vector<double> binningx = binx(); vector<double> binningy = biny(); // vector<double> binningz = binz(); Double_t* xedges = &binningx[0]; Double_t* yedges = &binningy[0]; // Double_t* zedges = &binningz[0]; for(int i=0; i<p; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } const Int_t XBINS = 18; const Int_t YBINS = 4; // const Int_t ZBINS = 4; TH2* h3 = new TH2F(("bindata"+species).c_str(), ("bindata"+species).c_str(), XBINS, xedges, YBINS, yedges); for(int b(0); b < t->GetEntries(); ++b) { t->GetEntry(b); h3->Fill(mu3_P,mu3_ETA); } h3->Draw(); canv->Print(("bin"+species+".pdf").c_str()); TAxis* xAxis = h3->GetXaxis(); // TAxis* yAxis = h3->GetYaxis(); // TAxis* zAxis = h3->GetZaxis(); cout<< "Binx 1: "<<endl; cout<< "lower edge: "<<xAxis->GetBinLowEdge(1)<<endl; cout<< "high edge: "<<xAxis->GetBinUpEdge(1)<<endl; int z(0); int acc(0); vector<float> numofmykaons; vector<int> numofkaons; for (int i=1; i<XBINS+1; i++) { for (int j=1; j<YBINS+1; j++) { // for (int k=1; k<ZBINS+1; k++) { numofkaons.push_back(h3->GetBinContent(i,j)); acc+=numofkaons.at(z); numofmykaons.push_back(numofkaons.at(z)); cout<< numofkaons.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< numofmykaons.at(z)<< endl; z++; // } } } int numberofthrownevents(0); for(int n=0; n<t->GetEntries(); ++n) { t->GetEntry(n); cout<<"Bplus_Corrected_Mass"<<Bplus_Corrected_Mass<<endl; cout<<"mu3_P:"<<mu3_P<<endl; // int resultx; // int resulty; // int resultz; if (mu3_P<binningx.at(0) || mu3_P>binningx.at(18) || mu3_ETA<binningy.at(0) || mu3_ETA>binningy.at(4)) { cout<< "Need to thow away this"<<endl; cout<< "Num of thrown away events: "<<numberofthrownevents++<<endl; cout<< "Borders:"<< binningx.at(0) <<" "<<binningx.at(18)<< " "<<binningy.at(0)<< " "<<binningy.at(4) << endl; } } TFile *F1 = new TFile("append.root","UPDATE"); h3->Write("", TObject::kOverwrite); F1->Close(); delete F1; f->Close(); delete canv; cout<<"Accumulate numofmykaons : "<<acc<<endl; cout<<"numberofthrownevents : "<<numberofthrownevents<<endl; return numofmykaons; } void addweighttotreeJACK(string filename, string decaytree, string species, string name, string newfilename) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t mu3_P; t->SetBranchAddress("mu3_P", &mu3_P); // t->SetBranchAddress("mu3_ETA", &mu3_ETA); // t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); TFile *g = new TFile((newfilename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t weight; newtree->Branch(name.c_str(),&weight,"weight/D"); int p=18; // int eta=4; vector<double> binningx = binx(); // vector<double> binningy = biny(); // Double_t* xedges = &binningx[0]; // Double_t* yedges = &binningy[0]; for(int i=0; i<p; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } //Jack momentum weights// //Pion Misid //Kaon Misid //Proton Misid vector<double> pionmisidinside; cout<<"THIS IS MY SPECIES "<<species<<endl; if (species=="pion"){ pionmisidinside = jackpion(); } else if (species=="kaon"){ pionmisidinside = jackkaon(); } else if (species=="proton"){ pionmisidinside = jackproton(); } vector<double> pionmisid; pionmisid=pionmisidinside; int numberofthrownevents(0); for(int n=0; n<t->GetEntries(); ++n) { t->GetEntry(n); int resultx(20); if (mu3_P<binningx.at(0) || mu3_P>binningx.at(18)) { cout<< "Need to thow away this"<<endl; cout<< "Num of thrown away events: "<<numberofthrownevents++<<endl; cout<< "Borders:"<< binningx.at(0) <<" "<<binningx.at(18)<< " "<<endl; weight= 3.0; } else { for (int i=0; i<(p); i++) { if ((mu3_P>binningx.at(i)) && (mu3_P<binningx.at(i+1))) { weight=pionmisid.at(i); cout<<species<<" misid JACK: "<< weight<<endl; } } } //end of else cout<<"mu3_P: "<<mu3_P<<endl; cout<<"Weight:" <<weight<<endl; newtree->Fill(); } //end of tree get entries cout<<"Number of events:" << t->GetEntries()<< endl; cout<<"Final numberofthrownevent: "<< numberofthrownevents<<endl; g->Write("",TObject::kOverwrite); g->Close(); f->Close(); return; } void plotheatmapPID(string filename, string decaytree, string weightfile, string wfilecuts, string name, string polarity, string stripping) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t mu3_P, mu3_ETA, Bplus_Corrected_Mass; t->SetBranchAddress("mu3_P", &mu3_P); t->SetBranchAddress("mu3_ETA", &mu3_ETA); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); int p=18; int eta=4; vector<double> binningx = binx(); vector<double> binningy = biny(); // Double_t* xedges = &binningx[0]; // Double_t* yedges = &binningy[0]; for(int i=0; i<p; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } cout<<"Weight file: "<<weightfile<<"Weight cuts:"<< wfilecuts<<endl; TFile* s = new TFile(weightfile.c_str()); TH2F *hname =(TH2F*)s->Get(wfilecuts.c_str()); vector<float> effi; Int_t z(0); for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { effi.push_back(hname->GetBinContent(i,j)); cout<<weightfile<<wfilecuts<<"ID rate: " << effi[z] << " in a bin i , j:" << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; z++; } } TCanvas *c1 = new TCanvas("c1","c1",600,600); hname->Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); c1->SaveAs(("PID_HeatMap_"+polarity+"_"+stripping+"_"+cleanNameString(wfilecuts)+".pdf").c_str()); f->Close(); s->Close(); delete c1; delete s; delete f; return; } void addweighttotree(string filename, string decaytree, string weightfile, string wfilecuts, string name, string newfilename) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t mu3_P, mu3_ETA, Bplus_Corrected_Mass; t->SetBranchAddress("mu3_P", &mu3_P); t->SetBranchAddress("mu3_ETA", &mu3_ETA); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); TFile *g = new TFile((newfilename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t weight; newtree->Branch(name.c_str(),&weight,"weight/D"); int p=18; int eta=4; vector<double> binningx = binx(); vector<double> binningy = biny(); // Double_t* xedges = &binningx[0]; // Double_t* yedges = &binningy[0]; for(int i=0; i<p; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } cout<<"Weight file: "<<weightfile<<"Weight cuts:"<< wfilecuts<<endl; TFile* s = new TFile(weightfile.c_str()); TH2F *hname =(TH2F*)s->Get(wfilecuts.c_str()); vector<float> effi; Int_t z(0); for (int i=1; i<(p+1); i++) { for (int j=1; j<(eta+1); j++) { effi.push_back(hname->GetBinContent(i,j)); cout<<weightfile<<wfilecuts<<"ID rate: " << effi[z] << " in a bin i , j:" << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; z++; } } int numberofthrownevents(0); for(int n=0; n<t->GetEntries(); ++n) { t->GetEntry(n); int resultx(20); int resulty(20); if (mu3_P<binningx.at(0) || mu3_P>binningx.at(18) || mu3_ETA<binningy.at(0) || mu3_ETA>binningy.at(4)) { cout<< "Need to thow away this"<<endl; cout<< "Num of thrown away events: "<<numberofthrownevents++<<endl; cout<< "Borders:"<< binningx.at(0) <<" "<<binningx.at(18)<< " "<<binningy.at(0)<< " "<<binningy.at(4) << " "<<endl; weight=3.0; } else { for (int i=0; i<(p); i++) { if ((mu3_P>binningx.at(i)) && (mu3_P<binningx.at(i+1))) { resultx=i+1; cout<<"resultx: "<< resultx<<endl; } } for (int j=0; j<(eta); j++) { if ((mu3_ETA>binningy.at(j)) && (mu3_ETA<binningy.at(j+1))) { resulty=j+1; cout<<"resulty: "<< resulty<<endl; } } weight=hname->GetBinContent(resultx,resulty); } //end of else cout<<"mu3_P: "<<mu3_P<<endl; cout<<"mu3_ETA: "<<mu3_ETA<<endl; cout<<"Weight:" <<weight<<endl; newtree->Fill(); } //end of tree get entries cout<<"Number of events:" << t->GetEntries()<< endl; cout<<"Final numberofthrownevent: "<< numberofthrownevents<<endl; g->Write("",TObject::kOverwrite); g->Close(); f->Close(); s->Close(); return; } void addweighttotreespecial(string filename, string decaytree, vector<float> weights, string name) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t mu3_P, mu3_ETA, Bplus_Corrected_Mass; //Int_t nTracks; t->SetBranchAddress("mu3_P", &mu3_P); t->SetBranchAddress("mu3_ETA", &mu3_ETA); //t->SetBranchAddress("nTracks", &nTracks); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); TFile *g = new TFile((filename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t weight; newtree->Branch(name.c_str(),&weight,"weight/D"); int p=18; int eta=4; //int ntracks=4; vector<double> binningx = binx(); vector<double> binningy = biny(); //vector<double> binningz = binz(); //Double_t* xedges = &binningx[0]; //Double_t* yedges = &binningy[0]; //Double_t* zedges = &binningz[0]; for(int i=0; i<p; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } vector<float> myweights; myweights=weights; float vectortoidentify[18][4]; Int_t z(0); for (int i=0; i<(p); i++) { for (int j=0; j<(eta); j++) { // for (int k=0; k<(ntracks); k++) { vectortoidentify[i][j]=myweights[z]; cout<<"Give final weight for event"<<endl; cout<<vectortoidentify[i][j]<< " in a bin i , j , k:" << i << " " << j << " "<< endl; // cout<<"This is z:" << z <<endl; // myaverage+=effi[z]; z++; // } } } //int numberofthrownevents(0); for(int n=0; n<t->GetEntries(); ++n) { t->GetEntry(n); cout<<"Bplus_Corrected_Mass"<<Bplus_Corrected_Mass<<endl; cout<<"mu3_P:"<<mu3_P<<endl; cout<<"mu3_ETA:"<<mu3_ETA<<endl; //cout<<"nTracks:"<<nTracks<<endl; int resultx(20); int resulty(20); //int resultz; //int numberofthrownevents; for (int i=0; i<(p); i++) { if ((mu3_P>binningx.at(i)) && (mu3_P<binningx.at(i+1))) { resultx=i; cout<<"resultx: "<< resultx<<endl; } } for (int j=0; j<(eta); j++) { if ((mu3_ETA>binningy.at(j)) && (mu3_ETA<binningy.at(j+1))) { resulty=j; cout<<"resulty: "<< resulty<<endl; } } weight=vectortoidentify[resultx][resulty]; cout<<"mu3_P: "<<mu3_P<<endl; cout<<"mu3_ETA: "<<mu3_ETA<<endl; //cout<<"nTracks: "<<nTracks<<endl; cout<<"Weight:" <<weight<<endl; newtree->Fill(); } //end of tree get entries cout<<"Number of events:" << t->GetEntries()<< endl; //cout<<"Final numberofthrownevent: "<< numberofthrownevents<<endl; g->Write("",TObject::kOverwrite); g->Close(); f->Close(); //s->Close(); return; } vector<float> binmydatacorrm(string filename, string decaytree, string species, Double_t lowcorrm, Double_t highcorrm){ //TFile *F1 = new TFile("append.root","UPDATE"); TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); TCanvas *canv=new TCanvas("plotmy3d","plotmy3d",600,600); Double_t mu3_P, mu3_ETA, Bplus_Corrected_Mass; Int_t nTracks; t->SetBranchAddress("mu3_P", &mu3_P); t->SetBranchAddress("mu3_ETA", &mu3_ETA); t->SetBranchAddress("nTracks", &nTracks); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); const int count = 253393; Double_t maxParr [count] = {}; Double_t maxEtaarr [count] = {}; Double_t maxnTracksarr [count] = {}; int out0(0); int out1(0); int out2(0); int out3(0); int out4(0); int out5(0); int out6(0); int out7(0); int out8(0); int out9(0); int out10(0); int out11(0); int out12(0); int out13(0); int out14(0); for(int b(0); b < t->GetEntries(); ++b) { t->GetEntry(b); if ((Bplus_Corrected_Mass > lowcorrm) && (Bplus_Corrected_Mass < highcorrm)) { // t->GetEntry(b); maxParr[b] = mu3_P; maxEtaarr[b] = mu3_ETA; maxnTracksarr[b] = nTracks; if (mu3_P<3000.0) { out0++; if (mu3_ETA<1.5) { out5++; if (nTracks>=500.0) { out9++; } } if (mu3_ETA>=5.0) { out6++; if (nTracks>=500.0) { out10++; } } if (nTracks>=500.0) { out13++; } } if (mu3_P>=100000.0) { out1++; if (mu3_ETA<1.5) { out7++; if (nTracks>=500.0) { out11++; } } if (mu3_ETA>=5.0) { out8++; if (nTracks>=500.0) { out12++; } } if (nTracks>=500.0) { out14++; } } if (mu3_ETA<1.5) { out2++; } if (mu3_ETA>=5.0) { out3++; } if (nTracks>=500.0) { out4++; } } } std::cout << "The smallest element in P is " << *std::min_element(maxParr,maxParr+count) << '\n'; std::cout << "The largest element in P is " << *std::max_element(maxParr,maxParr+count) << '\n'; std::cout << "The smallest element in eta is " << *std::min_element(maxEtaarr,maxEtaarr+count) << '\n'; std::cout << "The largest element in eta is " << *std::max_element(maxEtaarr,maxEtaarr+count) << '\n'; std::cout << "The smallest element in nTracks is " << *std::min_element(maxnTracksarr,maxnTracksarr+count) << '\n'; std::cout << "The largest element in nTracks is " << *std::max_element(maxnTracksarr,maxnTracksarr+count) << '\n'; cout<<"This is number of events with mu3_P < 3000.0: "<<out0<<endl; cout<<"This is number of evetns with mu3_P >= 100000.0: "<<out1<<endl; cout<<"This is number of events with mu3_ETA < 1.5 "<<out2<<endl; cout<<"This is number of events with mu3_ETA >= 5.0: "<<out3<<endl; cout<<"This is number of events with mu3_nTracks >= 500: "<<out4<<endl; cout<<"This is number of events with mu3_P<3000.0 and mu3_ETA < 1.5: "<<out5<<endl; cout<<"This is number of events with mu3_P<3000.0 and mu3_ETA >= 5.0: "<<out6<<endl; cout<<"This is number of events with mu3_P>=10000.0 and mu3_ETA < 1.5: "<<out7<<endl; cout<<"This is number of events with mu3_P>=10000.0 and mu3_ETA >= 5.0: "<<out8<<endl; cout<<"This is number of events with mu3_P<3000.0 and mu3_ETA < 1.5 and ntracks >=500: "<<out9<<endl; cout<<"This is number of events with mu3_P<3000.0 and mu3_ETA >= 5.0 and ntracks >= 500: "<<out10<<endl; cout<<"This is number of events with mu3_P>=10000.0 and mu3_ETA < 1.5 and ntracks >= 500: "<<out11<<endl; cout<<"This is number of events with mu3_P>=10000.0 and mu3_ETA >= 5.0 and ntracks >= 500: "<<out12<<endl; cout<<"This is number of events with mu3_P<3000.0 and ntracks >= 500: "<<out13<<endl; cout<<"This is number of events with mu3_P>=10000.0 and ntracks >= 500: "<<out14<<endl; Double_t nTracksArr[5] = {0.0}; Double_t EtaArr[5] = {0.0}; Double_t PArr[19] = {0.0}; EtaArr[0]=1.5; PArr[0]=3000.0; PArr[1]=9300.0; PArr[2]=15600.0; PArr[3]=19000.0; nTracksArr[0]=0.0; nTracksArr[1]=50.0; nTracksArr[2]=200.0; nTracksArr[3]=300.0; nTracksArr[4]=500.0; const int p = 18; const int eta = 4; const int ntracks = 4; for(int j(1); j<(eta+1); ++j) { EtaArr[j] = EtaArr[j-1] + 0.875; cout<<"Eta: "<<EtaArr[j]<<endl; } for(int j(4); j<(p+1); ++j) { PArr[j] = PArr[j-1] + 5400.0; } cout<<"P binning: "; for(int j(0); j<(p+1); ++j) { cout<<" "<<PArr[j]<<","; } cout<<"."<<endl; cout<<"Eta binning: "; for(int j(0); j<(eta+1); ++j) { cout<<" "<<EtaArr[j]<<","; } cout<<"."<<endl; cout<<"nTracks Binning: "; for(int j(0); j<(ntracks+1); ++j) { cout<<" "<<nTracksArr[j]<<","; } cout<<"."<<endl; const Int_t XBINS = 18; const Int_t YBINS = 4; const Int_t ZBINS = 4; //Double_t xedges[XBINS+1] = PArr; //Double_t yedges[YBINS+1] = EtaArr; //Double_t zedges[ZBINS+1] = nTracksArr; TH3* h3 = new TH3F(("bindatacor"+species).c_str(), ("bindatacor"+species).c_str(), XBINS, PArr, YBINS, EtaArr, ZBINS, nTracksArr); for(int b(0); b < t->GetEntries(); ++b) { t->GetEntry(b); if ((Bplus_Corrected_Mass > lowcorrm) && (Bplus_Corrected_Mass < highcorrm)) { cout<<"Corrected Mass:"<<Bplus_Corrected_Mass<<endl; //cout<<mu3_P<<","<<mu3_ETA<<","<<nTracks; h3->Fill(mu3_P,mu3_ETA,float(nTracks)); } } h3->Draw(); canv->Print(("bindatacor"+species+".pdf").c_str()); TAxis* xAxis = h3->GetXaxis(); //TAxis* yAxis = h3->GetYaxis(); //TAxis* zAxis = h3->GetZaxis(); cout<< "Binx 1: "<<endl; cout<< "lower edge: "<<xAxis->GetBinLowEdge(1)<<endl; cout<< "high edge: "<<xAxis->GetBinUpEdge(1)<<endl; int z(0); int acc(0); vector<float> numofmykaons; Int_t numofkaons[288]; for (int i=1; i<XBINS+1; i++) { for (int j=1; j<YBINS+1; j++) { for (int k=1; k<ZBINS+1; k++) { numofkaons[z] = h3->GetBinContent(i,j,k); acc+=numofkaons[z]; numofmykaons.push_back(numofkaons[z]); cout<< numofkaons[z] << " in a bin i , j , k:" << i << " " << j << " "<< k << " "<< numofmykaons.at(z)<< endl; z++; } } } //f->Close(); TFile *F1 = new TFile("append.root","UPDATE"); h3->Write("", TObject::kOverwrite); F1->Close(); delete F1; f->Close(); delete canv; cout<<"Accumulate:"<<acc<<endl; return numofmykaons; } vector<float> newmyfavkin(vector<float> numberofparticles , vector<float> ideff, string species){ vector<double> binningx = binx(); vector<double> binningy = biny(); // vector<double> binningz = binz(); Double_t* xedges = &binningx[0]; Double_t* yedges = &binningy[0]; // Double_t* zedges = &binningz[0]; const Int_t XBINS = 18; const Int_t YBINS = 4; // const Int_t ZBINS = 4; for(int i=0; i<18; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } TCanvas *canv=new TCanvas("plotmy3d","plotmy3d",600,600); TH2* h3 = new TH2F(("kindistr"+species).c_str(), ("kindistr"+species).c_str(), XBINS, xedges, YBINS, yedges); float myfav; int z(0); vector<float> kindistribution; for (int i=1; i<XBINS+1; i++) { for (int j=1; j<YBINS+1; j++) { // for (int k=1; k<ZBINS+1; k++) { myfav=numberofparticles.at(z)/ideff.at(z); kindistribution.push_back(myfav); h3->SetBinContent(i,j, myfav); cout<<"Kin distribution"<<kindistribution.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< endl; cout<<"number of particles: "<<numberofparticles.at(z)<<endl; cout<<"id efficiency: "<<ideff.at(z)<<endl; z++; // } } } float check; for (int i=1; i<XBINS+1; i++) { for (int j=1; j<YBINS+1; j++) { // for (int k=1; k<ZBINS+1; k++) { check = h3->GetBinContent(i,j); cout<<"Check: "<<check<<endl; // } } } h3->Draw(); canv->Print(("kindistr"+species+".pdf").c_str()); cout<<"madeit"<<endl; TFile *F1 = new TFile("append.root","UPDATE"); h3->Write("", TObject::kOverwrite); F1->Close(); delete F1; delete h3; delete canv; //f->Close(); return kindistribution; } vector<float> myfavkin(vector<float> numberofparticles , vector<float> ideff, string species){ Double_t nTracksArr[5] = {0.0}; Double_t EtaArr[5] = {0.0}; Double_t PArr[19] = {0.0}; EtaArr[0]=1.5; PArr[0]=3000.0; PArr[1]=9300.0; PArr[2]=15600.0; PArr[3]=19000.0; nTracksArr[0]=0.0; nTracksArr[1]=50.0; nTracksArr[2]=200.0; nTracksArr[3]=300.0; nTracksArr[4]=500.0; const int p = 18; const int eta = 4; const int ntracks = 4; for(int j(1); j<(eta+1); ++j) { EtaArr[j] = EtaArr[j-1] + 0.875; cout<<"Eta: "<<EtaArr[j]<<endl; } for(int j(4); j<(p+1); ++j) { PArr[j] = PArr[j-1] + 5400.0; } cout<<"P binning: "; for(int j(0); j<(p+1); ++j) { cout<<" "<<PArr[j]<<","; } cout<<"."<<endl; cout<<"Eta binning: "; for(int j(0); j<(eta+1); ++j) { cout<<" "<<EtaArr[j]<<","; } cout<<"."<<endl; cout<<"nTracks Binning: "; for(int j(0); j<(ntracks+1); ++j) { cout<<" "<<nTracksArr[j]<<","; } cout<<"."<<endl; const Int_t XBINS = 18; const Int_t YBINS = 4; const Int_t ZBINS = 4; //Double_t xedges[XBINS+1] = PArr; //Double_t yedges[YBINS+1] = EtaArr; //Double_t zedges[ZBINS+1] = nTracksArr; TCanvas *canv=new TCanvas("plotmy3d","plotmy3d",600,600); TH3* h3 = new TH3F(("kindistr"+species).c_str(), ("kindistr"+species).c_str(), XBINS, PArr, YBINS, EtaArr, ZBINS, nTracksArr); float myfav; int z(0); vector<float> kindistribution; for (int i=1; i<XBINS+1; i++) { for (int j=1; j<YBINS+1; j++) { for (int k=1; k<ZBINS+1; k++) { myfav=numberofparticles.at(z)/ideff.at(z); // if (myfav>10000) // { // myfav=; // } kindistribution.push_back(myfav); h3->SetBinContent(i,j,k, myfav); cout<<"Kin distribution"<<kindistribution.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< k << " "<< endl; cout<<"number of particles: "<<numberofparticles.at(z)<<endl; cout<<"id efficiency: "<<ideff.at(z)<<endl; z++; } } } float check; for (int i=1; i<XBINS+1; i++) { for (int j=1; j<YBINS+1; j++) { for (int k=1; k<ZBINS+1; k++) { check = h3->GetBinContent(i,j,k); cout<<"Check: "<<check<<endl; } } } h3->Draw(); canv->Print(("kindistr"+species+".pdf").c_str()); cout<<"madeit"<<endl; TFile *F1 = new TFile("append.root","UPDATE"); h3->Write("", TObject::kOverwrite); F1->Close(); delete F1; delete h3; delete canv; //f->Close(); return kindistribution; } vector<double> jackpion(){ vector<double> PArr; PArr.push_back(1.08); PArr.push_back(1.19); PArr.push_back(1.87); PArr.push_back(1.87); const int p = 18; for(int j(4); j<(p); ++j) { PArr.push_back(1.87); } PArr.push_back(3.35); cout<<"Jack pion weight: "; for(int j(0); j<(p+1); ++j) { cout<<" "<<PArr.at(j)<<","; } cout<<"."<<endl; return PArr; } vector<double> jackkaon(){ vector<double> PArr; PArr.push_back(1.04); PArr.push_back(1.36); PArr.push_back(1.59); PArr.push_back(1.59); const int p = 18; for(int j(4); j<(p); ++j) { PArr.push_back(1.59); } PArr.push_back(2.15); cout<<"Jack pion weight: "; for(int j(0); j<(p+1); ++j) { cout<<" "<<PArr.at(j)<<","; } cout<<"."<<endl; return PArr; } vector<double> jackproton(){ vector<double> PArr; PArr.push_back(1.0); PArr.push_back(1.0); PArr.push_back(1.0); PArr.push_back(1.0); const int p = 18; for(int j(4); j<(p); ++j) { PArr.push_back(1.0); } PArr.push_back(1.0); cout<<"Jack pion weight: "; for(int j(0); j<(p+1); ++j) { cout<<" "<<PArr.at(j)<<","; } cout<<"."<<endl; return PArr; } vector<double> binmuonx(){ vector<double> PArr; PArr.push_back(3000.0); PArr.push_back(6000.0); PArr.push_back(8000.0); PArr.push_back(10000.0); PArr.push_back(12000.0); PArr.push_back(14500.0); PArr.push_back(17500.0); PArr.push_back(21500.0); PArr.push_back(27000.0); PArr.push_back(32000.0); PArr.push_back(40000.0); PArr.push_back(60000.0); PArr.push_back(70000.0); PArr.push_back(100000.0); //const int p = 13; return PArr; } vector<double> binx(){ vector<double> PArr; PArr.push_back(3000.0); PArr.push_back(9300.0); PArr.push_back(15600.0); PArr.push_back(19000.0); const int p = 18; for(int j(4); j<(p+1); ++j) { PArr.push_back(PArr.at(j-1) + 5400.0); } cout<<"P binning: "; for(int j(0); j<(p+1); ++j) { cout<<" "<<PArr.at(j)<<","; } cout<<"."<<endl; return PArr; } vector<double> biny(){ vector<double> EtaArr; const int eta=4; EtaArr.push_back(1.5); for(int j(1); j<(eta+1); ++j) { EtaArr.push_back(EtaArr[j-1] + 0.875); } cout<<"ETA binning: "; for(int j(0); j<(eta+1); ++j) { cout<<" "<<EtaArr.at(j)<<","; } cout<<"."<<endl; return EtaArr; } vector<double> binz(){ vector<double> nTracksArr; const int ntracks=4; nTracksArr.push_back(0.0); nTracksArr.push_back(50.0); nTracksArr.push_back(200.0); nTracksArr.push_back(300.0); nTracksArr.push_back(500.0); cout<<"ntracks binning: "; for(int j(0); j<(ntracks+1); ++j) { cout<<" "<<nTracksArr.at(j)<<","; } cout<<"."<<endl; return nTracksArr; } vector<float> newkindistrpion(vector<float> pionbinmydata , vector<float> myktopimisid, vector<float> truekinematicaldistributionkaon, vector<float> pionideff, vector<float> misidpiontomuon) { const Int_t XBINS = 18; const Int_t YBINS = 4; const Int_t ZBINS = 4; vector<float> newkinematicaldispion; int c(0); for (int i=0; i<XBINS; i++) { for (int j=0; j<YBINS; j++) { for (int k=0; k<ZBINS; k++) { newkinematicaldispion.push_back((pionbinmydata.at(c)-(myktopimisid.at(c)*truekinematicaldistributionkaon.at(c)))/pionideff.at(c)); cout<<"NewKinematicalpion : "<<newkinematicaldispion.at(c)<< endl; c++; } } } return(newkinematicaldispion); } vector<float> newkindistrkaon(vector<float> kaonbinmydata , vector<float> mypitokmisid, vector<float> truekinematicaldistributionpion, vector<float> kaonideff, vector<float> misidkaontomuon) { const Int_t XBINS = 18; const Int_t YBINS = 4; //const Int_t ZBINS = 4; vector<float> newkinematicaldiskaon; //---------CHECK-------// cout<<"Size of kaonbinmydata: "<< kaonbinmydata.size()<<endl; cout<<"Size of mypitokmisid: "<< mypitokmisid.size()<<endl; cout<<"Size of truekinematicaldistributionpion: "<< truekinematicaldistributionpion.size()<<endl; cout<<"Size of kaonideff: "<< kaonideff.size()<<endl; cout<<"Size of misidkaontomuon: "<<misidkaontomuon.size(); int c(0); for (int i=0; i<XBINS; i++) { for (int j=0; j<YBINS; j++) { // for (int k=0; k<ZBINS; k++) { newkinematicaldiskaon.push_back((kaonbinmydata.at(c)-(mypitokmisid.at(c)*truekinematicaldistributionpion.at(c)))/kaonideff.at(c)); cout<<"NewKinematicalpion : "<<newkinematicaldiskaon.at(c)<< endl; c++; // } } } return(newkinematicaldiskaon); } float numofpionafteriteration(vector<float> pionbinmydata , vector<float> myktopimisid, vector<float> truekinematicaldistributionkaon, vector<float> pionideff, vector<float> misidpiontomuon, int number, string species, string misidcuts, string polarity, string stripping) { vector<double> binningx = binx(); vector<double> binningy = biny(); // vector<double> binningz = binz(); Double_t* xedges = &binningx[0]; Double_t* yedges = &binningy[0]; // Double_t* zedges = &binningz[0]; const Int_t XBINS = 18; const Int_t YBINS = 4; // const Int_t ZBINS = 4; TH2* myhisto = new TH2F("pion", "pion", XBINS, xedges, YBINS, yedges); //const Int_t ZBINS = 4; vector<float> newkinematicaldispion; //vector<float> newkinematicaldiskaon; vector<float> jop1; //vector<float> jop2; int c(0); for (int i=0; i<XBINS; i++) { for (int j=0; j<YBINS; j++) { // for (int k=0; k<ZBINS; k++) { newkinematicaldispion.push_back((pionbinmydata.at(c)-(myktopimisid.at(c)*truekinematicaldistributionkaon.at(c)))/pionideff.at(c)); cout<<"NewKinematicalpion : "<<newkinematicaldispion.at(c)<< endl; jop1.push_back(newkinematicaldispion.at(c)*misidpiontomuon.at(c)); // newkinematicaldiskaon.push_back((kaonbinmydata.at(c)-(mypitokmisid.at(c)*truekinematicaldistributionpion.at(c)))/kaonideff.at(c)); // cout<<"NewKinematicalkaon : "<<newkinematicaldiskaon.at(c)<< endl; // jop2.push_back(newkinematicaldiskaon.at(c)*misidkaontomuon.at(c)); myhisto->SetBinContent(i+1,j+1,jop1.at(c)); c++; // } } } TCanvas *c4 = new TCanvas("c4","c4",600,600); myhisto->Draw("TEXT89COLZ"); myhisto->SetTitle(("NumOfMisid_after_"+i2s(number)+"_iteration_pion_numberofpart_"+d2s(std::accumulate(jop1.begin(),jop1.end(),0.0))).c_str()); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(90); c4->SaveAs(("NumberOfMisidafter_"+i2s(number)+"_iteration_HeatMap_pion_"+species+"_"+polarity+"_"+stripping+"_"+misidcuts+".pdf").c_str()); delete c4; delete myhisto; // cout<<"num of mis kaons 1st correction:"<<std::accumulate(jop2.begin(),jop2.end(),0.0)<<endl; cout<<"num of mis pions correction:"<<std::accumulate(jop1.begin(),jop1.end(),0.0)<<endl; return(std::accumulate(jop1.begin(),jop1.end(),0.0)); } float numofkaonafteriteration(vector<float> kaonbinmydata , vector<float> mypitokmisid, vector<float> truekinematicaldistributionpion, vector<float> kaonideff, vector<float> misidkaontomuon, int number, string species, string misidcuts, string polarity, string stripping) { vector<double> binningx = binx(); vector<double> binningy = biny(); // vector<double> binningz = binz(); Double_t* xedges = &binningx[0]; Double_t* yedges = &binningy[0]; // Double_t* zedges = &binningz[0]; const Int_t XBINS = 18; const Int_t YBINS = 4; // const Int_t ZBINS = 4; TH2* myhisto = new TH2F("kaon", "kaon", XBINS, xedges, YBINS, yedges); //const Int_t ZBINS = 4; //vector<float> newkinematicaldispion; vector<float> newkinematicaldiskaon; //vector<float> jop1; vector<float> jop2; int c(0); for (int i=0; i<XBINS; i++) { for (int j=0; j<YBINS; j++) { // for (int k=0; k<ZBINS; k++) { // newkinematicaldispion.push_back((pionbinmydata.at(c)-(myktopimisid.at(c)*truekinematicaldistributionkaon.at(c)))/pionideff.at(c)); // cout<<"NewKinematicalpion : "<<newkinematicaldispion.at(c)<< endl; // jop1.push_back(newkinematicaldispion.at(c)*misidpiontomuon.at(c)); newkinematicaldiskaon.push_back((kaonbinmydata.at(c)-(mypitokmisid.at(c)*truekinematicaldistributionpion.at(c)))/kaonideff.at(c)); cout<<"NewKinematicalkaon : "<<newkinematicaldiskaon.at(c)<< endl; // myhisto->SetBinContent(i+1,j+1,newkinematicaldiskaon.at(c)); jop2.push_back(newkinematicaldiskaon.at(c)*misidkaontomuon.at(c)); myhisto->SetBinContent(i+1,j+1,jop2.at(c)); c++; // } } } TCanvas *c4 = new TCanvas("c4","c4",600,600); myhisto->Draw("TEXT89COLZ"); myhisto->SetTitle(("NumOfMisid_after_"+i2s(number)+"_iteration_kaon_numberofpart_"+d2s(std::accumulate(jop2.begin(),jop2.end(),0.0))).c_str()); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(90); c4->SaveAs(("NumberOfMisidafter_"+i2s(number)+"_iteration_HeatMap_kaon_"+species+"_"+polarity+"_"+stripping+"_"+misidcuts+".pdf").c_str()); delete c4; delete myhisto; cout<<"num of mis kaons correction:"<<std::accumulate(jop2.begin(),jop2.end(),0.0)<<endl; // cout<<"num of mis pions 1st correction:"<<std::accumulate(jop1.begin(),jop1.end(),0.0)<<endl; return(std::accumulate(jop2.begin(),jop2.end(),0.0)); } float numofparafteriteration(int number,vector<float> pionbinmydata , vector<float> myktopimisid, vector<float> truekinematicaldistributionkaon, vector<float> pionideff, vector<float> misidpiontomuon, vector<float> kaonbinmydata , vector<float> mypitokmisid, vector<float> truekinematicaldistributionpion, vector<float> kaonideff, vector<float> misidkaontomuon) { const Int_t XBINS = 18; const Int_t YBINS = 4; //const Int_t ZBINS = 4; vector<float> newkinematicaldispion; vector<float> newkinematicaldiskaon; vector<float> jop1; vector<float> jop2; int c(0); for (int i=0; i<XBINS; i++) { for (int j=0; j<YBINS; j++) { // for (int k=0; k<ZBINS; k++) { newkinematicaldispion.push_back((pionbinmydata.at(c)-(myktopimisid.at(c)*truekinematicaldistributionkaon.at(c)))/pionideff.at(c)); cout<<"NewKinematicalpion : "<<newkinematicaldispion.at(c)<< endl; jop1.push_back(newkinematicaldispion.at(c)*misidpiontomuon.at(c)); newkinematicaldiskaon.push_back((kaonbinmydata.at(c)-(mypitokmisid.at(c)*truekinematicaldistributionpion.at(c)))/kaonideff.at(c)); cout<<"NewKinematicalkaon : "<<newkinematicaldiskaon.at(c)<< endl; jop2.push_back(newkinematicaldiskaon.at(c)*misidkaontomuon.at(c)); c++; // } } } cout<<"num of mis kaons "<<number<<"st correction:"<<std::accumulate(jop2.begin(),jop2.end(),0.0)<<endl; cout<<"num of mis pions "<<number<<"st correction:"<<std::accumulate(jop1.begin(),jop1.end(),0.0)<<endl; return((std::accumulate(jop2.begin(),jop2.end(),0.0))+(std::accumulate(jop1.begin(),jop1.end(),0.0))); } float totmisidproton(string filename, string species, string misidPIDcalib, string misidcuts, string idPIDcalib, string idcuts, string tags, string stripping, string polarity) { string decaytree ="DecayTree"; ///------------ ADD Weights ------------/// TFile f1((filename).c_str()); TTree* t1 = (TTree*)f1.Get(decaytree.c_str()); if(t1 && t1->GetEntries()!=0) { addweighttotree(filename, decaytree, idPIDcalib, idcuts, "idPIDcalib", ("modified"+stripping+polarity+filename).c_str()); plotheatmapPID(filename, decaytree, idPIDcalib, idcuts, "idPIDcalib", polarity, stripping); addweighttotreeJACK(("modified"+stripping+polarity+filename).c_str(), decaytree, species, "jackweight", ("modifiedjack"+stripping+polarity+filename).c_str()); addweighttotree(("modifiedjack"+stripping+polarity+filename).c_str(), decaytree, misidPIDcalib, misidcuts, "misidPIDcalibold", ("modified"+tags+stripping+polarity+filename).c_str()); plotheatmapPID(("modifiedjack"+stripping+polarity+filename).c_str(), decaytree, misidPIDcalib, misidcuts, "misidPIDcalibold",polarity, stripping); ///------------Cut the stupid entries------/// cutTree(("modified"+tags+stripping+polarity+filename).c_str(), decaytree, ("modifiedandcut"+tags+stripping+polarity+filename).c_str(), "(idPIDcalib != 3.0 && misidPIDcalibold != 3.0)"); //----Include Jack's weight--------// addproductbranches(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, "misidPIDcalibold", "jackweight", "misidPIDcalib"); ///----------- Calculate the probability of misid ----/// addratiofbranches(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, "misidPIDcalib", "idPIDcalib", "misidoverid"); int p=18; int eta=4; vector<float> protonbinmydata; protonbinmydata=newbinmydata(filename, decaytree, species); vector<float> protonideff; protonideff = efficiency(idPIDcalib,idcuts, p, eta, polarity, stripping); vector<float> misidprotontomuon; misidprotontomuon = efficiency(misidPIDcalib, misidcuts, p, eta, polarity, stripping);// species2); vector<float> truekinematicaldistributionproton; truekinematicaldistributionproton=newmyfavkin(protonbinmydata , protonideff, species); TFile s("append.root"); TH2F *numproton =(TH2F*)s.Get(("bindata"+species).c_str()); TCanvas *c3 = new TCanvas("c3","c3",600,600); numproton->Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(); c3->SaveAs(("NumberOfParticles_HeatMap_"+species+"_"+polarity+"_"+stripping+"_"+cleanNameString(misidcuts)+".pdf").c_str()); delete c3; cout<<"Hola"<<endl; //--MIS ID EFFICIENCIES FROM TH2F--// TH2F *misproton =(TH2F*)s.Get(misidcuts.c_str()); float o = misproton->Integral(); cout<<"misproton:"<<o<<endl; //--FIRST TRUE KINEMATICAL DISTRIBUTIONS--// TH2F *kinproton =(TH2F*)s.Get(("kindistr"+species).c_str()); //--------FIRST TRUE KINEMATICAL DISTRIBUTIONS* MISIDEFFICIENCY--------// TH2F firstproton=((*misproton)*(*kinproton)); TCanvas *c1 = new TCanvas("c1","c1",600,600); firstproton.Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(); c1->SaveAs(("MisidNumberAfter_zeroth_iteration_HeatMap_"+species+"_"+polarity+"_"+stripping+"_"+cleanNameString(misidcuts)+".pdf").c_str()); delete c1; ///---------- Reweigh Corrected Mass ------// addrealweight(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, "Bplus_Corrected_Mass", "misidoverid", "ReweightedCorrM", species); TFile f2(("modifiedandcut"+tags+stripping+polarity+filename).c_str()); TTree* t2 = (TTree*)f2.Get(decaytree.c_str()); // TFile f1(("modifiedandcut"+tags+stripping+polarity+filename2).c_str()); // // TTree* t1 = (TTree*)f1.Get(decaytree2.c_str()); // if(t2 && t2->GetEntries()!=0) { cout<<"I will do this"<<endl; ///---------- Add it normalized ----------/// addnormalbranchweight(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, "misidoverid", "normalizedmisidoverid"); } } return(3.1); } float totmisidnobinofcorrmimp(string filename, string filename2, string species, string species2 ,string misidPIDcalib, string misidcuts, string misidPIDcalib2, string misidcuts2, string idPIDcalib, string idcuts, string idPIDcalib2, string idcuts2, string ktopimisidfilename, string ktopimisidcuts, string pitokmisidfilename, string pitokmisidcuts, string tags, string stripping, string polarity) { //string filename="B23MuNuFakeSameSignMuonSmallDataSample_mu3isNotMuon_mu3inMuonAcc_Jpsi_cut_mu1nShared_mu2nShared_qmincut_KaonPID_PUNZIoptBDT.root"; string decaytree ="DecayTree"; //string misidPIDcalib ="/vols/lhcb/ss4314/week26oct/vetojpsismallsamplenshared/PIDnshared/KisMuonNSharedzeroDLLmumorethanzeroDLLmuminusKmorethanzero/PerfHists_K_Strip20_MagDown_P_ETA_nTracks.root"; //string misidcuts ="K_(IsMuon==1.0) && (DLLmu > 0.0) && ((DLLmu - DLLK) > 0.0) && (nShared==0)_All"; //string idPIDcalib ="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/idkaon/PerfHists_K_Strip20_MagDown_P_ETA.root"; //string idcuts ="K_IsMuon==0.0 && DLLK > 0.0 && ((DLLp - DLLK) < 5.0)_All"; //string filename2="B23MuNuFakeSameSignMuonSmallDataSample_mu3isNotMuon_mu3inMuonAcc_Jpsi_cut_mu1nShared_mu2nShared_qmincut_PionPID_PUNZIoptBDT.root"; string decaytree2 ="DecayTree"; //string misidPIDcalib2 ="/vols/lhcb/ss4314/week26oct/vetojpsismallsamplenshared/PIDnshared/PisMuonNSharedzeroDLLmumorethanzeroDLLmuminusKmorethanzero/PerfHists_Pi_Strip20_MagDown_P_ETA_nTracks.root"; //string misidcuts2 ="Pi_(IsMuon==1.0) && (DLLmu > 0.0) && ((DLLmu - DLLK) > 0.0) && (nShared==0)_All"; //string idPIDcalib2 ="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/idpion/PerfHists_Pi_Strip20_MagDown_P_ETA.root"; //string idcuts2 ="Pi_IsMuon==0.0 && DLLK < 0.0 && DLLp < 5.0_All";ck //string species = "kaon"; //string species2 = "pion"; ///------------ ADD Weights ------------/// cout<<"Satrting to calculate corssfeed"<<endl; addweighttotree(filename, decaytree, idPIDcalib, idcuts, "idPIDcalib", ("modified"+stripping+polarity+filename).c_str()); plotheatmapPID(filename, decaytree, idPIDcalib, idcuts, "idPIDcalib",polarity, stripping); addweighttotree(("modified"+stripping+polarity+filename).c_str(), decaytree, misidPIDcalib, misidcuts, "misidPIDcalib", ("modified"+tags+stripping+polarity+filename).c_str()); plotheatmapPID(("modified"+stripping+polarity+filename).c_str(), decaytree, misidPIDcalib, misidcuts, "misidPIDcalib",polarity, stripping); addweighttotree(filename2, decaytree2, idPIDcalib2, idcuts2, "idPIDcalib", ("modified"+stripping+polarity+filename2).c_str()); plotheatmapPID(filename2, decaytree2, idPIDcalib2, idcuts2, "idPIDcalib",polarity, stripping); addweighttotree(("modified"+stripping+polarity+filename2).c_str(), decaytree2, misidPIDcalib2, misidcuts2, "misidPIDcalib", ("modified"+tags+stripping+polarity+filename2).c_str()); plotheatmapPID(("modified"+stripping+polarity+filename2).c_str(), decaytree2, misidPIDcalib2, misidcuts2, "misidPIDcalib",polarity, stripping); //addweighttotree(filename, decaytree); ///------------Cut the stupid entries------/// cutTree(("modified"+tags+stripping+polarity+filename).c_str(), decaytree, ("modifiedandcut"+tags+stripping+polarity+filename).c_str(), "(idPIDcalib != 3.0 && misidPIDcalib != 3.0)"); cutTree(("modified"+tags+stripping+polarity+filename2).c_str(), decaytree, ("modifiedandcut"+tags+stripping+polarity+filename2).c_str(), "(idPIDcalib != 3.0 && misidPIDcalib != 3.0)"); ///----------- Calculate the probability of misid ----/// addratiofbranches(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, "misidPIDcalib", "idPIDcalib", "misidoverid"); addratiofbranches(("modifiedandcut"+tags+stripping+polarity+filename2).c_str(), decaytree2, "misidPIDcalib", "idPIDcalib", "misidoverid"); cout<<"Hola"<<endl; ///---------- Reweigh Corrected Mass ------// addrealweight(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, "Bplus_Corrected_Mass", "misidoverid", "ReweightedCorrM", species); addrealweight(("modifiedandcut"+tags+stripping+polarity+filename2).c_str(), decaytree, "Bplus_Corrected_Mass", "misidoverid", "ReweightedCorrM", species2); TFile f2(("modifiedandcut"+tags+stripping+polarity+filename).c_str()); TTree* t2 = (TTree*)f2.Get(decaytree.c_str()); TFile f1(("modifiedandcut"+tags+stripping+polarity+filename2).c_str()); TTree* t1 = (TTree*)f1.Get(decaytree.c_str()); if(t2 && t2->GetEntries()!=0 && t1 && t1->GetEntries()!=0) { cout<<"I will do this"<<endl; ///---------- Add it normalized ----------/// addnormalbranchweight(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, "misidoverid", "normalizedmisidoverid"); addnormalbranchweight(("modifiedandcut"+tags+stripping+polarity+filename2).c_str(), decaytree2, "misidoverid", "normalizedmisidoverid"); } ///-------------BINNING SCHEME---------/// int p=18; int eta=4; //int ntracks=4; vector<double> binningx = binx(); vector<double> binningy = biny(); //vector<double> binningz = binz(); //Double_t* xedges = &binningx[0]; //Double_t* yedges = &binningy[0]; //Double_t* zedges = &binningz[0]; //Double_t yedges[eta+1] = binningy; //Double_t zedges[ntracks+1] = binningz; ///-------------BIN THE DATA-----------/// vector<float> kaonbinmydata; kaonbinmydata=newbinmydata(filename, decaytree, species); vector<float> pionbinmydata; pionbinmydata=newbinmydata(filename2, decaytree2, species2); ///------------BIN DATA IN CORRECTED MASS---/// //vector<float> kaonbinmydatacorrm; //kaonbinmydata=binmydatacorrm(filename, decaytree, species, 2500, 10000); //vector<float> pionbinmydatacorrm; //pionbinmydata=binmydatacorrm(filename2, decaytree2, species2, 2500, 10000); ///------------ ID EFFICIENCIES------------------// vector<float> kaonideff; kaonideff = efficiency(idPIDcalib,idcuts, p, eta, polarity, stripping); vector<float> pionideff; pionideff = efficiency(idPIDcalib2,idcuts2, p, eta, polarity, stripping); ///------------ MIS-ID EFFICIENCIES-------------// vector<float> misidpiontomuon; misidpiontomuon = efficiency(misidPIDcalib2, misidcuts2, p, eta, polarity, stripping);// species2); vector<float> misidkaontomuon; misidkaontomuon = efficiency(misidPIDcalib, misidcuts, p, eta, polarity, stripping);// species); ///------------ Cross-feed Efficiencies---------// vector<float> myktopimisid; // string ktopimisidfilename="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/crossfeedkaon/PerfHists_K_Strip20_MagDown_P_ETA.root"; // string ktopimisidcuts="K_IsMuon==0.0 && DLLK < 0.0 && DLLp < 5.0_All"; myktopimisid = crossmisid(ktopimisidfilename,ktopimisidcuts, p, eta, polarity, stripping); vector<float> mypitokmisid; // string pitokmisidfilename="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/crossfeedpion/PerfHists_Pi_Strip20_MagDown_P_ETA.root"; // string pitokmisidcuts="Pi_IsMuon==0.0 && DLLK > 0.0 && ((DLLp - DLLK) < 5.0)_All"; mypitokmisid = crossmisid(pitokmisidfilename,pitokmisidcuts, p, eta, polarity, stripping); ///-------FIRST TRUE KINEMATICAL DISTRIBUTION----------// vector<float> truekinematicaldistributionkaon; truekinematicaldistributionkaon=newmyfavkin(kaonbinmydata , kaonideff, species); vector<float> truekinematicaldistributionpion; truekinematicaldistributionpion=newmyfavkin(pionbinmydata , pionideff, species2); ///----------- AVERAGE CROSS FEED EFF-----------// cout<<"Average K to pi misid rate:"<< avcrossmisid(ktopimisidfilename,ktopimisidcuts, p,eta)<<endl; cout<<"Average pi to K misid rate:"<< avcrossmisid(pitokmisidfilename,pitokmisidcuts, p,eta)<<endl; float checkthepion(0); float checkthekaon(0); for(int j(0); j<72; j++){ checkthepion+=(myktopimisid.at(j)*truekinematicaldistributionkaon.at(j)); checkthekaon+=(mypitokmisid.at(j)*truekinematicaldistributionpion.at(j)); } cout<<"checkthepion: "<< checkthepion <<endl; cout<<"checkthekaon: "<< checkthekaon <<endl; ///----TOTAL MIS ID RATE at 0th iteration-----// //--OPEN THE ROOT FILE WITH ALL INFO--// TFile s("append.root"); //--MIS ID EFFICIENCIES FROM TH2F--// TH2F *miskaon =(TH2F*)s.Get(misidcuts.c_str()); TH2F *mispion =(TH2F*)s.Get(misidcuts2.c_str()); //--Checking the bin boundaries--// TAxis* xAxis = miskaon->GetXaxis(); TAxis* yAxis = miskaon->GetYaxis(); //TAxis* zAxis = miskaon->GetZaxis(); for(int j(0); j<(p+1); ++j) { cout<< "Binx: "<<j<<" : "<<endl; cout<< "lower edge: "<<xAxis->GetBinLowEdge(j)<<endl; cout<< "high edge: "<<xAxis->GetBinUpEdge(j)<<endl; } for(int j(0); j<(eta+1); ++j) { cout<< "Biny: "<<j<<" : "<<endl; cout<< "lower edge: "<<yAxis->GetBinLowEdge(j)<<endl; cout<< "high edge: "<<yAxis->GetBinUpEdge(j)<<endl; } //for(int j(0); j<(ntracks+1); ++j) //{ //cout<< "Binz: "<<j<<" : "<<endl; //cout<< "lower edge: "<<zAxis->GetBinLowEdge(j)<<endl; //cout<< "high edge: "<<zAxis->GetBinUpEdge(j)<<endl; //} float o = miskaon->Integral(); float x = mispion->Integral(); cout<<"miskaon:"<<o<<endl; cout<<"mispion:"<<x<<endl; //--BIN MY DATA FROM TH3F--// TH2F *numkaon =(TH2F*)s.Get(("bindata"+species).c_str()); TH2F *numpion =(TH2F*)s.Get(("bindata"+species2).c_str()); TCanvas *c3 = new TCanvas("c3","c3",600,600); numkaon->Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(); c3->SaveAs(("NumberOfParticles_HeatMap_"+species+"_"+polarity+"_"+stripping+"_"+cleanNameString(misidcuts)+".pdf").c_str()); delete c3; TCanvas *c4 = new TCanvas("c4","c4",600,600); numpion->Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(90); c4->SaveAs(("NumberOfParticles_HeatMap_"+species+"_"+polarity+"_"+stripping+"_"+cleanNameString(misidcuts2)+".pdf").c_str()); delete c4; float d = numkaon->Integral(); float e = numpion->Integral(); cout<<"numkaon:"<<d<<endl; cout<<"numpion:"<<e<<endl; //--FIRST TRUE KINEMATICAL DISTRIBUTIONS--// TH2F *kinkaon =(TH2F*)s.Get(("kindistr"+species).c_str()); TH2F *kinpion =(TH2F*)s.Get(("kindistr"+species2).c_str()); //const Int_t XBINS = 18; //const Int_t YBINS = 4; //const Int_t ZBINS = 4; //TH3F* firstkaon = new TH3F(("first"+species).c_str(), ("first"+species).c_str(), XBINS, xedges, YBINS, yedges, ZBINS, zedges); //TH3F* firstpion = new TH3F(("first"+species2).c_str(), ("first"+species2).c_str(), XBINS, xedges, YBINS, yedges, ZBINS, zedges); // ---CHECKING THE NUMBER OF BINS----// cout<<miskaon->GetNbinsX()<<endl; cout<<miskaon->GetNbinsY()<<endl; //cout<<miskaon->GetNbinsZ()<<endl; //--------FIRST TRUE KINEMATICAL DISTRIBUTIONS* MISIDEFFICIENCY--------// TH2F firstkaon=((*miskaon)*(*kinkaon)); TCanvas *c1 = new TCanvas("c1","c1",600,600); firstkaon.Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(); c1->SaveAs(("MisidNumberAfter_zeroth_iteration_HeatMap_"+species+"_"+polarity+"_"+stripping+"_"+cleanNameString(misidcuts)+".pdf").c_str()); delete c1; TH2F firstpion =((*mispion)*(*kinpion)); TCanvas *c2 = new TCanvas("c2","c2",600,600); firstpion.Draw("TEXT89COLZ"); gPad->SetRightMargin(0.15); gStyle->SetOptStat(0); // gStyle->SetTextAngle(90); c2->SaveAs(("MisidNumberAfter_zeroth_iteration_HeatMap_"+species2+"_"+polarity+"_"+stripping+"_"+cleanNameString(misidcuts2)+".pdf").c_str()); delete c2; //----------------------------------CREATE VECTORS FOR KAON PION AND TOTAL MISID-----------// vector<float> kaonvector; vector<float> pionvector; vector<float> overallvector; float la = firstkaon.Integral(); float le = firstpion.Integral(); cout<<"num of mis kaons 0th it:"<<la<<endl; cout<<"num of mis pions 0th it:"<<le<<endl; cout<<"At 0th iteration: "<<la+le<<endl; kaonvector.push_back(la); pionvector.push_back(le); overallvector.push_back(la+le); //----------------------END OF 0th iteration------EVERYTHING OK------------// //---------------------STARTOF First Iteration-----------------------------------// int number=1; vector<float> firstiterationkaon; firstiterationkaon=newkindistrkaon(kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon); vector<float> firstiterationpion; firstiterationpion=newkindistrkaon(pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon); cout<<"numofkaonafteriteration:"<< number << "is: " <<numofkaonafteriteration(kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon, number, species, misidcuts, polarity, stripping)<<endl; cout<<"numofpionafteriteration:"<< number << "is: " << numofpionafteriteration(pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon, number, species2, misidcuts2, polarity, stripping)<<endl; kaonvector.push_back(numofkaonafteriteration(kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon,number,species, misidcuts, polarity, stripping)); pionvector.push_back(numofpionafteriteration(pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon,number,species2, misidcuts2, polarity, stripping)); float numofparticlesyeah(0); numofparticlesyeah=numofparafteriteration(number, pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon, kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon); cout<<"after it"<< number << " num of part:"<< numofparticlesyeah<<endl; overallvector.push_back(numofparticlesyeah); //--------------------END OF THE FIRST ITERATION--------------------------------------// //--------------------START OF THE SECOND ITERATION-----------------------------------// int number2=2; vector<float> seconditerationkaon; seconditerationkaon=newkindistrkaon(kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon); vector<float> seconditerationpion; seconditerationpion=newkindistrkaon(pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon); cout<<"numofkaonafteriteration: "<< number << "is: " << numofkaonafteriteration(kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon, number2, species, misidcuts, polarity, stripping)<<endl; cout<<"numofpionafteriteration: "<< number << "is: " << numofpionafteriteration(pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon, number2, species2, misidcuts2, polarity, stripping)<<endl; kaonvector.push_back(numofkaonafteriteration(kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon,number2, species, misidcuts, polarity, stripping)); pionvector.push_back(numofpionafteriteration(pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon,number2, species2, misidcuts2, polarity, stripping)); float numofparticlesyeah2(0); numofparticlesyeah2=numofparafteriteration(number2, pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon, kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon); cout<<"after it:"<<number2 <<" num of part: "<< numofparticlesyeah2<<endl; overallvector.push_back(numofparticlesyeah2); int z(0); cout<<"STATISTICS"<<endl; cout<<"Z+2: " << overallvector.at(z+2) << endl; cout<<"Filename: "<<("modifiedandcut"+tags+stripping+polarity+filename).c_str()<<endl; vector<float> iterationkaon; vector<float> iterationpion; float numofpit; //---------------------------------------------------------Loop-----UNTIL CONVERGENCE--------------------------------------------------------------// while (abs(overallvector.at(z+2)-overallvector.at(z+1))>(0.001*(overallvector.at(z+1)))) { cout<<"STATISTICS: REMEMBER ITERATION = CORRECTION +1 "<<endl; cout<<"total misid at " <<z+2<<" iteration: "<< (overallvector.at(z+2)) << endl; cout<<"total misid at " <<z+1<< " iteration: "<< (overallvector.at(z+1)) << endl; cout<<"Change between iteration: "<<z+2<<" and "<< z+1 << " is : "<< abs(overallvector.at(z+2)-overallvector.at(z+1))<<endl; cout<<"0.001* total misid at "<< z+1 <<" iteration is: "<<(0.001*(overallvector.at(z+1)))<<endl; iterationkaon=newkindistrkaon(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon); iterationpion=newkindistrkaon(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon); cout<<"numofkaonafteriteration:"<< numofkaonafteriteration(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon, z+3, species, misidcuts, polarity, stripping)<<endl; cout<<"numofpionafteriteration:"<< numofpionafteriteration(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon, z+3, species2, misidcuts2, polarity, stripping)<<endl; kaonvector.push_back(numofkaonafteriteration(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon,z+3, species, misidcuts, polarity, stripping)); pionvector.push_back(numofpionafteriteration(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon,z+3, species2, misidcuts2, polarity, stripping)); numofpit=numofparafteriteration(z+3, pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon, kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon); cout<<"WHILE loop after it number of particles:"<< numofpit <<endl; overallvector.push_back(numofpit); seconditerationpion.clear(); seconditerationkaon.clear(); for (int i=0; i<iterationkaon.size(); i++) { seconditerationkaon.push_back(iterationkaon.at(i)); seconditerationpion.push_back(iterationpion.at(i)); } iterationkaon.clear(); iterationpion.clear(); z++; vector<float> finalkaonit; vector<float> finalpionit; vector<float> weightfinalkaon; vector<float> weightfinalpion; if(abs(overallvector.at(z+2)-overallvector.at(z+1))<(0.001*(overallvector.at(z+1)))) { cout<<"IT will end now"<<endl; cout<<"ITERATION: "<< z+1 <<endl; finalkaonit=newkindistrkaon(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon); finalpionit=newkindistrkaon(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon); for(int l=0; l<finalkaonit.size(); l++) { weightfinalkaon.push_back((finalkaonit.at(l)*misidkaontomuon.at(l))/kaonbinmydata.at(l)); weightfinalpion.push_back((finalpionit.at(l)*misidpiontomuon.at(l))/pionbinmydata.at(l)); cout<<"FINAL KAON WEIGHT: "<<finalkaonit.at(l)<<endl; cout<<"FINAL PION WEIGHT: "<<finalpionit.at(l)<<endl; cout<<"FINAL NUM KAON WEIGHT: "<<weightfinalkaon.at(l)<<endl; cout<<"FINAL NUM PION WEIGHT: "<<weightfinalpion.at(l)<<endl; // addweighttotreespecial(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, weightfinalkaon, "crossfeedweight", "try.root"); } addweighttotreespecial(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, weightfinalkaon, "crossfeedweight"); addweighttotreespecial(("modifiedandcut"+tags+stripping+polarity+filename2).c_str(), decaytree, weightfinalpion, "crossfeedweight"); } //return(overallvector.push_back(numofpit)); } //----------------------------RETURNS THE FINAL MISID---------------------------------------------------------------// cout<<"THE FINAL AMOUNT OF MIS ID: "<<overallvector.back()<<endl; return(overallvector.back()); } float totmisidnobinofcorrm(string filename, string filename2, string species, string species2 ,string misidPIDcalib, string misidcuts, string misidPIDcalib2, string misidcuts2, string tags) { //string filename="B23MuNuFakeSameSignMuonSmallDataSample_mu3isNotMuon_mu3inMuonAcc_Jpsi_cut_mu1nShared_mu2nShared_qmincut_KaonPID_PUNZIoptBDT.root"; string decaytree ="DecayTree"; //string misidPIDcalib ="/vols/lhcb/ss4314/week26oct/vetojpsismallsamplenshared/PIDnshared/KisMuonNSharedzeroDLLmumorethanzeroDLLmuminusKmorethanzero/PerfHists_K_Strip20_MagDown_P_ETA_nTracks.root"; //string misidcuts ="K_(IsMuon==1.0) && (DLLmu > 0.0) && ((DLLmu - DLLK) > 0.0) && (nShared==0)_All"; string idPIDcalib ="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/idkaon/PerfHists_K_Strip20_MagDown_P_ETA.root"; string idcuts ="K_IsMuon==0.0 && DLLK > 0.0 && ((DLLp - DLLK) < 5.0)_All"; //string filename2="B23MuNuFakeSameSignMuonSmallDataSample_mu3isNotMuon_mu3inMuonAcc_Jpsi_cut_mu1nShared_mu2nShared_qmincut_PionPID_PUNZIoptBDT.root"; string decaytree2 ="DecayTree"; //string misidPIDcalib2 ="/vols/lhcb/ss4314/week26oct/vetojpsismallsamplenshared/PIDnshared/PisMuonNSharedzeroDLLmumorethanzeroDLLmuminusKmorethanzero/PerfHists_Pi_Strip20_MagDown_P_ETA_nTracks.root"; //string misidcuts2 ="Pi_(IsMuon==1.0) && (DLLmu > 0.0) && ((DLLmu - DLLK) > 0.0) && (nShared==0)_All"; string idPIDcalib2 ="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/idpion/PerfHists_Pi_Strip20_MagDown_P_ETA.root"; string idcuts2 ="Pi_IsMuon==0.0 && DLLK < 0.0 && DLLp < 5.0_All"; //string species = "kaon"; //string species2 = "pion"; ///------------ ADD Weights ------------/// addweighttotree(filename, decaytree, idPIDcalib, idcuts, "idPIDcalib", ("modified"+filename).c_str()); addweighttotree(("modified"+filename).c_str(), decaytree, misidPIDcalib, misidcuts, "misidPIDcalib", ("modified"+tags+filename).c_str()); addweighttotree(filename2, decaytree2, idPIDcalib2, idcuts2, "idPIDcalib", ("modified"+filename2).c_str()); addweighttotree(("modified"+filename2).c_str(), decaytree2, misidPIDcalib2, misidcuts2, "misidPIDcalib", ("modified"+tags+filename2).c_str()); //addweighttotree(filename, decaytree); ///------------Cut the stupid entries------/// cutTree(("modified"+tags+filename).c_str(), decaytree, ("modifiedandcut"+tags+filename).c_str(), "(idPIDcalib != 3.0 && misidPIDcalib != 3.0)"); cutTree(("modified"+tags+filename2).c_str(), decaytree, ("modifiedandcut"+tags+filename2).c_str(), "(idPIDcalib != 3.0 && misidPIDcalib != 3.0)"); ///----------- Calculate the probability of misid ----/// addratiofbranches(("modifiedandcut"+tags+filename).c_str(), decaytree, "misidPIDcalib", "idPIDcalib", "misidoverid"); addratiofbranches(("modifiedandcut"+tags+filename2).c_str(), decaytree2, "misidPIDcalib", "idPIDcalib", "misidoverid"); cout<<"Hola"<<endl; // exit; ///---------- Reweigh Corrected Mass ------// addrealweight(("modifiedandcut"+tags+filename).c_str(), decaytree, "Bplus_Corrected_Mass", "misidoverid", "ReweightedCorrM", species); addrealweight(("modifiedandcut"+tags+filename2).c_str(), decaytree, "Bplus_Corrected_Mass", "misidoverid", "ReweightedCorrM", species2); ///---------- Add it normalized ----------/// addnormalbranchweight(("modifiedandcut"+tags+filename).c_str(), decaytree, "misidoverid", "normalizedmisidoverid"); addnormalbranchweight(("modifiedandcut"+tags+filename2).c_str(), decaytree2, "misidoverid", "normalizedmisidoverid"); ///-------------BINNING SCHEME---------/// int p=18; int eta=4; //int ntracks=4; vector<double> binningx = binx(); vector<double> binningy = biny(); //vector<double> binningz = binz(); //Double_t* xedges = &binningx[0]; //Double_t* yedges = &binningy[0]; //Double_t* zedges = &binningz[0]; //Double_t yedges[eta+1] = binningy; //Double_t zedges[ntracks+1] = binningz; ///-------------BIN THE DATA-----------/// vector<float> kaonbinmydata; kaonbinmydata=newbinmydata(filename, decaytree, species); vector<float> pionbinmydata; pionbinmydata=newbinmydata(filename2, decaytree2, species2); ///------------BIN DATA IN CORRECTED MASS---/// //vector<float> kaonbinmydatacorrm; //kaonbinmydata=binmydatacorrm(filename, decaytree, species, 2500, 10000); //vector<float> pionbinmydatacorrm; //pionbinmydata=binmydatacorrm(filename2, decaytree2, species2, 2500, 10000); string polarity="balh"; string stripping="blah2"; ///------------ ID EFFICIENCIES------------------// vector<float> kaonideff; kaonideff = efficiency(idPIDcalib,idcuts, p, eta, polarity, stripping); vector<float> pionideff; pionideff = efficiency(idPIDcalib2,idcuts2, p, eta, polarity, stripping); ///------------ MIS-ID EFFICIENCIES-------------// vector<float> misidpiontomuon; misidpiontomuon = efficiency(misidPIDcalib2, misidcuts2, p, eta, polarity, stripping); vector<float> misidkaontomuon; misidkaontomuon = efficiency(misidPIDcalib, misidcuts, p, eta, polarity, stripping); ///------------ Cross-feed Efficiencies---------// vector<float> myktopimisid; string ktopimisidfilename="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/crossfeedkaon/PerfHists_K_Strip20_MagDown_P_ETA.root"; string ktopimisidcuts="K_IsMuon==0.0 && DLLK < 0.0 && DLLp < 5.0_All"; myktopimisid = crossmisid(ktopimisidfilename,ktopimisidcuts, p, eta, polarity, stripping); vector<float> mypitokmisid; string pitokmisidfilename="/vols/lhcb/ss4314/tightPIDinvestigation/nontrackcalculation/crossfeedpion/PerfHists_Pi_Strip20_MagDown_P_ETA.root"; string pitokmisidcuts="Pi_IsMuon==0.0 && DLLK > 0.0 && ((DLLp - DLLK) < 5.0)_All"; mypitokmisid = crossmisid(pitokmisidfilename,pitokmisidcuts, p, eta, polarity, stripping); ///-------FIRST TRUE KINEMATICAL DISTRIBUTION----------// vector<float> truekinematicaldistributionkaon; truekinematicaldistributionkaon=newmyfavkin(kaonbinmydata , kaonideff, species); vector<float> truekinematicaldistributionpion; truekinematicaldistributionpion=newmyfavkin(pionbinmydata , pionideff, species2); ///----------- AVERAGE CROSS FEED EFF-----------// cout<<"Average K to pi misid rate:"<< avcrossmisid(ktopimisidfilename,ktopimisidcuts, p,eta)<<endl; cout<<"Average pi to K misid rate:"<< avcrossmisid(pitokmisidfilename,pitokmisidcuts, p,eta)<<endl; float checkthepion(0); float checkthekaon(0); for(int j(0); j<72; j++){ checkthepion+=(myktopimisid.at(j)*truekinematicaldistributionkaon.at(j)); checkthekaon+=(mypitokmisid.at(j)*truekinematicaldistributionpion.at(j)); } cout<<"checkthepion: "<< checkthepion <<endl; cout<<"checkthekaon: "<< checkthekaon <<endl; ///----TOTAL MIS ID RATE at 0th iteration-----// //--OPEN THE ROOT FILE WITH ALL INFO--// TFile s("append.root"); //--MIS ID EFFICIENCIES FROM TH2F--// TH2F *miskaon =(TH2F*)s.Get(misidcuts.c_str()); TH2F *mispion =(TH2F*)s.Get(misidcuts2.c_str()); //--Checking the bin boundaries--// TAxis* xAxis = miskaon->GetXaxis(); TAxis* yAxis = miskaon->GetYaxis(); //TAxis* zAxis = miskaon->GetZaxis(); for(int j(0); j<(p+1); ++j) { cout<< "Binx: "<<j<<" : "<<endl; cout<< "lower edge: "<<xAxis->GetBinLowEdge(j)<<endl; cout<< "high edge: "<<xAxis->GetBinUpEdge(j)<<endl; } for(int j(0); j<(eta+1); ++j) { cout<< "Biny: "<<j<<" : "<<endl; cout<< "lower edge: "<<yAxis->GetBinLowEdge(j)<<endl; cout<< "high edge: "<<yAxis->GetBinUpEdge(j)<<endl; } //for(int j(0); j<(ntracks+1); ++j) //{ //cout<< "Binz: "<<j<<" : "<<endl; //cout<< "lower edge: "<<zAxis->GetBinLowEdge(j)<<endl; //cout<< "high edge: "<<zAxis->GetBinUpEdge(j)<<endl; //} float o = miskaon->Integral(); float x = mispion->Integral(); cout<<"miskaon:"<<o<<endl; cout<<"mispion:"<<x<<endl; //--BIN MY DATA FROM TH3F--// TH2F *numkaon =(TH2F*)s.Get(("bindata"+species).c_str()); TH2F *numpion =(TH2F*)s.Get(("bindata"+species2).c_str()); float d = numkaon->Integral(); float e = numpion->Integral(); cout<<"numkaon:"<<d<<endl; cout<<"numpion:"<<e<<endl; //--FIRST TRUE KINEMATICAL DISTRIBUTIONS--// TH2F *kinkaon =(TH2F*)s.Get(("kindistr"+species).c_str()); TH2F *kinpion =(TH2F*)s.Get(("kindistr"+species2).c_str()); //const Int_t XBINS = 18; //const Int_t YBINS = 4; //const Int_t ZBINS = 4; //TH3F* firstkaon = new TH3F(("first"+species).c_str(), ("first"+species).c_str(), XBINS, xedges, YBINS, yedges, ZBINS, zedges); //TH3F* firstpion = new TH3F(("first"+species2).c_str(), ("first"+species2).c_str(), XBINS, xedges, YBINS, yedges, ZBINS, zedges); // ---CHECKING THE NUMBER OF BINS----// cout<<miskaon->GetNbinsX()<<endl; cout<<miskaon->GetNbinsY()<<endl; //cout<<miskaon->GetNbinsZ()<<endl; //--------FIRST TRUE KINEMATICAL DISTRIBUTIONS* MISIDEFFICIENCY--------// TH2F firstkaon=((*miskaon)*(*kinkaon)); TH2F firstpion =((*mispion)*(*kinpion)); //----------------------------------CREATE VECTORS FOR KAON PION AND TOTAL MISID-----------// vector<float> kaonvector; vector<float> pionvector; vector<float> overallvector; float la = firstkaon.Integral(); float le = firstpion.Integral(); cout<<"num of mis kaons 0th it:"<<la<<endl; cout<<"num of mis pions 0th it:"<<le<<endl; cout<<"At 0th iteration: "<<la+le<<endl; kaonvector.push_back(la); pionvector.push_back(le); overallvector.push_back(la+le); //----------------------END OF 0th iteration------EVERYTHING OK------------// //---------------------STARTOF First Iteration-----------------------------------// int number=1; vector<float> firstiterationkaon; firstiterationkaon=newkindistrkaon(kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon); vector<float> firstiterationpion; firstiterationpion=newkindistrkaon(pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon); // string polarity="blah"; // string stripping="blah2"; cout<<"numofkaonafteriteration:"<< number << "is: " <<numofkaonafteriteration(kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon,number,species, misidcuts, polarity, stripping)<<endl; cout<<"numofpionafteriteration:"<< number << "is: " << numofpionafteriteration(pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon,number,species2, misidcuts2, polarity, stripping)<<endl; kaonvector.push_back(numofkaonafteriteration(kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon,number, species, misidcuts, polarity, stripping)); pionvector.push_back(numofpionafteriteration(pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon,number, species2, misidcuts2, polarity, stripping)); float numofparticlesyeah(0); numofparticlesyeah=numofparafteriteration(number, pionbinmydata , myktopimisid, truekinematicaldistributionkaon, pionideff, misidpiontomuon, kaonbinmydata , mypitokmisid, truekinematicaldistributionpion, kaonideff, misidkaontomuon); cout<<"after it"<< number << " num of part:"<< numofparticlesyeah<<endl; overallvector.push_back(numofparticlesyeah); //--------------------END OF THE FIRST ITERATION--------------------------------------// //--------------------START OF THE SECOND ITERATION-----------------------------------// int number2=2; vector<float> seconditerationkaon; seconditerationkaon=newkindistrkaon(kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon); vector<float> seconditerationpion; seconditerationpion=newkindistrkaon(pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon); cout<<"numofkaonafteriteration: "<< number2 << "is: " << numofkaonafteriteration(kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon,number2, species, misidcuts, polarity, stripping)<<endl; cout<<"numofpionafteriteration: "<< number2 << "is: " << numofpionafteriteration(pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon,number2, species2, misidcuts2, polarity, stripping)<<endl; kaonvector.push_back(numofkaonafteriteration(kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon,number2, species, misidcuts, polarity, stripping)); pionvector.push_back(numofpionafteriteration(pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon,number2, species2, misidcuts2, polarity, stripping)); float numofparticlesyeah2(0); numofparticlesyeah2=numofparafteriteration(number2, pionbinmydata , myktopimisid, firstiterationkaon, pionideff, misidpiontomuon, kaonbinmydata , mypitokmisid, firstiterationpion, kaonideff, misidkaontomuon); cout<<"after it:"<<number2 <<" num of part: "<< numofparticlesyeah2<<endl; overallvector.push_back(numofparticlesyeah2); int z(0); cout<<"STATISTICS"<<endl; cout<<"Z+2: " << overallvector.at(z+2) << endl; vector<float> iterationkaon; vector<float> iterationpion; float numofpit; //---------------------------------------------------------Loop-----UNTIL CONVERGENCE--------------------------------------------------------------// while (abs(overallvector.at(z+2)-overallvector.at(z+1))>(0.001*(overallvector.at(z+1)))) { cout<<"STATISTICS: REMEMBER ITERATION = CORRECTION +1 "<<endl; cout<<"total misid at " <<z+2<<" iteration: "<< (overallvector.at(z+2)) << endl; cout<<"total misid at " <<z+1<< " iteration: "<< (overallvector.at(z+1)) << endl; cout<<"Change between iteration: "<<z+2<<" and "<< z+1 << " is : "<< abs(overallvector.at(z+2)-overallvector.at(z+1))<<endl; cout<<"0.001* total misid at "<< z+1 <<" iteration is: "<<(0.001*(overallvector.at(z+1)))<<endl; iterationkaon=newkindistrkaon(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon); iterationpion=newkindistrkaon(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon); cout<<"numofkaonafteriteration:"<< numofkaonafteriteration(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon,z+3, species, misidcuts, polarity, stripping)<<endl; cout<<"numofpionafteriteration:"<< numofpionafteriteration(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon,z+3, species2, misidcuts2, polarity, stripping)<<endl; kaonvector.push_back(numofkaonafteriteration(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon,z+3,species, misidcuts, polarity, stripping)); pionvector.push_back(numofpionafteriteration(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon,z+3,species2, misidcuts2, polarity, stripping)); numofpit=numofparafteriteration(z+3, pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon, kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon); cout<<"WHILE loop after it number of particles:"<< numofpit <<endl; overallvector.push_back(numofpit); seconditerationpion.clear(); seconditerationkaon.clear(); for (int i=0; i<iterationkaon.size(); i++) { seconditerationkaon.push_back(iterationkaon.at(i)); seconditerationpion.push_back(iterationpion.at(i)); } iterationkaon.clear(); iterationpion.clear(); z++; vector<float> finalkaonit; vector<float> finalpionit; vector<float> weightfinalkaon; vector<float> weightfinalpion; if(abs(overallvector.at(z+2)-overallvector.at(z+1))<(0.001*(overallvector.at(z+1)))) { cout<<"IT will end now"<<endl; cout<<"ITERATION: "<< z+1 <<endl; finalkaonit=newkindistrkaon(kaonbinmydata , mypitokmisid, seconditerationpion, kaonideff, misidkaontomuon); finalpionit=newkindistrkaon(pionbinmydata , myktopimisid, seconditerationkaon, pionideff, misidpiontomuon); for(int l=0; l<finalkaonit.size(); l++) { weightfinalkaon.push_back((finalkaonit.at(l)*misidkaontomuon.at(l))/kaonbinmydata.at(l)); weightfinalpion.push_back((finalpionit.at(l)*misidpiontomuon.at(l))/pionbinmydata.at(l)); cout<<"FINAL KAON WEIGHT: "<<finalkaonit.at(l)<<endl; cout<<"FINAL PION WEIGHT: "<<finalpionit.at(l)<<endl; cout<<"FINAL NUM KAON WEIGHT: "<<weightfinalkaon.at(l)<<endl; cout<<"FINAL NUM PION WEIGHT: "<<weightfinalpion.at(l)<<endl; // addweighttotreespecial(("modifiedandcut"+tags+stripping+polarity+filename).c_str(), decaytree, weightfinalkaon, "crossfeedweight", "try.root"); } addweighttotreespecial(("modifiedandcut"+tags+filename).c_str(), decaytree, weightfinalkaon, "crossfeedweight"); addweighttotreespecial(("modifiedandcut"+tags+filename2).c_str(), decaytree, weightfinalpion, "crossfeedweight"); } //return(overallvector.push_back(numofpit)); } //----------------------------RETURNS THE FINAL MISID---------------------------------------------------------------// cout<<"THE FINAL AMOUNT OF MIS ID: "<<overallvector.back()<<endl; return(overallvector.back()); } double calaveffofasamplemu3(string filename, string decaytree, string weightfile, string wfilecuts, string name, string newfilename) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t mu3_P, mu3_ETA, Bplus_Corrected_Mass; // Int_t nTracks; t->SetBranchAddress("mu3_P", &mu3_P); t->SetBranchAddress("mu3_ETA", &mu3_ETA); // t->SetBranchAddress("nTracks", &nTracks); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); TFile *g = new TFile((newfilename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t weight; newtree->Branch(name.c_str(),&weight,"weight/D"); vector<double> binningx = binmuonx(); vector<double> binningy = biny(); // vector<double> binningz = binz(); int sizeofp = binningx.size(); int sizeofeta = binningy.size(); // int sizeofntracks = binningz.size(); cout<<"sizeofp: "<<sizeofp; cout<<"sizeofeta: "<<sizeofeta; // cout<<"sizeofntracks: "<<sizeofntracks; int count(0); //Double_t* xedges = &binningx[0]; // Double_t* yedges = &binningy[0]; // Double_t* zedges = &binningz[0]; double accumulate(0); cout<<"Bin those muons, this is different to pion and kaon"<<endl; for(int i=0; i<sizeofp-1; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } TFile* s = new TFile(weightfile.c_str()); TH2F *hname =(TH2F*)s->Get(wfilecuts.c_str()); vector<float> effi; Int_t z(0); for (int i=1; i<(sizeofp); i++) { for (int j=1; j<(sizeofeta); j++) { // for (int k=1; k<(sizeofntracks); k++) { effi.push_back(hname->GetBinContent(i,j)); cout<<"Using: "<<weightfile<<" with cuts: "<< wfilecuts<<" the ID rate: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; z++; // } } } int numberofthrownevents(0); for(int n=0; n < t->GetEntries(); ++n) { t->GetEntry(n); cout<<"Entry number: "<<n<<" Bplus_Corrected_Mass: "<< Bplus_Corrected_Mass << " mu3_P: " << mu3_P << " mu3_ETA: "<< mu3_ETA <<endl; int resultx(20); int resulty(20); //int resultz; //int numberofthrownevents; if (mu3_P<binningx.at(0) || mu3_P>binningx.at(sizeofp-1) || mu3_ETA<binningy.at(0) || mu3_ETA>binningy.at(sizeofeta-1) ) { cout<< "Need to thow away this"<<endl; cout<< "Num of thrown away events: "<<numberofthrownevents++<<endl; cout<< "Borders:"<< binningx.at(0) <<" "<<binningx.at(13)<< " "<<binningy.at(0)<< " "<<binningy.at(4) << " "<<endl; //break; weight=-1.0; } else { for (int i=0; i<(sizeofp-1); i++) { if ((mu3_P>binningx.at(i)) && (mu3_P<binningx.at(i+1))) { resultx=i+1; cout<<"resultxbin: "<< resultx<<endl; } } for (int j=0; j<(sizeofeta-1); j++) { if ((mu3_ETA>binningy.at(j)) && (mu3_ETA<binningy.at(j+1))) { resulty=j+1; cout<<"resultybin: "<< resulty<<endl; } } // for (int k=0; k<(sizeofntracks-1); k++) { // if ((nTracks>binningz.at(k)) && (nTracks<binningz.at(k+1))) // { // resultz=k+1; // cout<<"resultzbin: "<< resultz<<endl; /// } // } //end of for count++; weight=hname->GetBinContent(resultx,resulty); accumulate+=weight; } //end of else cout<<" Weight for this event: " <<weight<<endl; newtree->Fill(); } //end of tree get entries double averageeff; averageeff=accumulate/double((t->GetEntries())-numberofthrownevents); cout<<"Number of events:" << t->GetEntries()<< endl; cout<<"Final numberofthrownevent: "<< numberofthrownevents<<endl; cout<<"Average efficiency: "<< averageeff << " check: " <<accumulate/double(count)<<endl; g->Write("",TObject::kOverwrite); g->Close(); f->Close(); s->Close(); return(averageeff); } double calaveffofasamplemu2(string filename, string decaytree, string weightfile, string wfilecuts, string name, string newfilename) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t mu2_P, mu2_ETA, Bplus_Corrected_Mass; // Int_t nTracks; t->SetBranchAddress("mu2_P", &mu2_P); t->SetBranchAddress("mu2_ETA", &mu2_ETA); // t->SetBranchAddress("nTracks", &nTracks); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); TFile *g = new TFile((newfilename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t weight; newtree->Branch(name.c_str(),&weight,"weight/D"); vector<double> binningx = binmuonx(); vector<double> binningy = biny(); // vector<double> binningz = binz(); int sizeofp = binningx.size(); int sizeofeta = binningy.size(); // int sizeofntracks = binningz.size(); cout<<"sizeofp: "<<sizeofp; cout<<"sizeofeta: "<<sizeofeta; // cout<<"sizeofntracks: "<<sizeofntracks; int count(0); //Double_t* xedges = &binningx[0]; // Double_t* yedges = &binningy[0]; // Double_t* zedges = &binningz[0]; double accumulate(0); cout<<"Bin those muons, this is different to pion and kaon"<<endl; for(int i=0; i<sizeofp-1; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } TFile* s = new TFile(weightfile.c_str()); TH2F *hname =(TH2F*)s->Get(wfilecuts.c_str()); vector<float> effi; Int_t z(0); for (int i=1; i<(sizeofp); i++) { for (int j=1; j<(sizeofeta); j++) { // for (int k=1; k<(sizeofntracks); k++) { effi.push_back(hname->GetBinContent(i,j)); cout<<"Using: "<<weightfile<<" with cuts: "<< wfilecuts<<" the ID rate: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; z++; // } } } int numberofthrownevents(0); for(int n=0; n < t->GetEntries(); ++n) { t->GetEntry(n); cout<<"Entry number: "<<n<<" Bplus_Corrected_Mass: "<< Bplus_Corrected_Mass << " mu2_P: " << mu2_P << " mu2_ETA: "<< mu2_ETA <<endl; int resultx(20); int resulty(20); //int resultz; //int numberofthrownevents; if (mu2_P<binningx.at(0) || mu2_P>binningx.at(sizeofp-1) || mu2_ETA<binningy.at(0) || mu2_ETA>binningy.at(sizeofeta-1) ) { cout<< "Need to thow away this"<<endl; cout<< "Num of thrown away events: "<<numberofthrownevents++<<endl; cout<< "Borders:"<< binningx.at(0) <<" "<<binningx.at(13)<< " "<<binningy.at(0)<< " "<<binningy.at(4) << " "<<endl; //break; weight=-1.0; } else { for (int i=0; i<(sizeofp-1); i++) { if ((mu2_P>binningx.at(i)) && (mu2_P<binningx.at(i+1))) { resultx=i+1; cout<<"resultxbin: "<< resultx<<endl; } } for (int j=0; j<(sizeofeta-1); j++) { if ((mu2_ETA>binningy.at(j)) && (mu2_ETA<binningy.at(j+1))) { resulty=j+1; cout<<"resultybin: "<< resulty<<endl; } } // for (int k=0; k<(sizeofntracks-1); k++) { // if ((nTracks>binningz.at(k)) && (nTracks<binningz.at(k+1))) // { // resultz=k+1; // cout<<"resultzbin: "<< resultz<<endl; /// } // } //end of for count++; weight=hname->GetBinContent(resultx,resulty); accumulate+=weight; } //end of else cout<<" Weight for this event: " <<weight<<endl; newtree->Fill(); } //end of tree get entries double averageeff; averageeff=accumulate/double((t->GetEntries())-numberofthrownevents); cout<<"Number of events:" << t->GetEntries()<< endl; cout<<"Final numberofthrownevent: "<< numberofthrownevents<<endl; cout<<"Average efficiency: "<< averageeff << " check: " <<accumulate/double(count)<<endl; g->Write("",TObject::kOverwrite); g->Close(); f->Close(); s->Close(); return(averageeff); } double calaveffofasamplemu1(string filename, string decaytree, string weightfile, string wfilecuts, string name, string newfilename) { TFile* f = new TFile(filename.c_str()); TTree* t = (TTree*)f->Get(decaytree.c_str()); Double_t mu1_P, mu1_ETA, Bplus_Corrected_Mass; // Int_t nTracks; t->SetBranchAddress("mu1_P", &mu1_P); t->SetBranchAddress("mu1_ETA", &mu1_ETA); // t->SetBranchAddress("nTracks", &nTracks); t->SetBranchAddress("Bplus_Corrected_Mass", &Bplus_Corrected_Mass); TFile *g = new TFile((newfilename).c_str(), "RECREATE"); TTree *newtree = t->CloneTree(0); Double_t weight; newtree->Branch(name.c_str(),&weight,"weight/D"); vector<double> binningx = binmuonx(); vector<double> binningy = biny(); // vector<double> binningz = binz(); int sizeofp = binningx.size(); int sizeofeta = binningy.size(); // int sizeofntracks = binningz.size(); cout<<"sizeofp: "<<sizeofp; cout<<"sizeofeta: "<<sizeofeta; // cout<<"sizeofntracks: "<<sizeofntracks; int count(0); //Double_t* xedges = &binningx[0]; // Double_t* yedges = &binningy[0]; // Double_t* zedges = &binningz[0]; double accumulate(0); cout<<"Bin those muons, this is different to pion and kaon"<<endl; for(int i=0; i<sizeofp-1; ++i){ cout<< binningx.at(i)<< "Binning" << i << "th therm"<<endl; } TFile* s = new TFile(weightfile.c_str()); TH2F *hname =(TH2F*)s->Get(wfilecuts.c_str()); vector<float> effi; Int_t z(0); for (int i=1; i<(sizeofp); i++) { for (int j=1; j<(sizeofeta); j++) { // for (int k=1; k<(sizeofntracks); k++) { effi.push_back(hname->GetBinContent(i,j)); cout<<"Using: "<<weightfile<<" with cuts: "<< wfilecuts<<" the ID rate: " << effi.at(z) << " in a bin i , j , k:" << i << " " << j << " "<< endl; cout<<"This is z:" << z <<endl; z++; // } } } int numberofthrownevents(0); for(int n=0; n < t->GetEntries(); ++n) { t->GetEntry(n); cout<<"Entry number: "<<n<<" Bplus_Corrected_Mass: "<< Bplus_Corrected_Mass << " mu1_P: " << mu1_P << " mu1_ETA: "<< mu1_ETA <<endl; int resultx(20); int resulty(20); //int resultz; //int numberofthrownevents; if (mu1_P<binningx.at(0) || mu1_P>binningx.at(sizeofp-1) || mu1_ETA<binningy.at(0) || mu1_ETA>binningy.at(sizeofeta-1) ) { cout<< "Need to thow away this"<<endl; cout<< "Num of thrown away events: "<<numberofthrownevents++<<endl; cout<< "Borders:"<< binningx.at(0) <<" "<<binningx.at(13)<< " "<<binningy.at(0)<< " "<<binningy.at(4) << " "<<endl; //break; weight=-1.0; } else { for (int i=0; i<(sizeofp-1); i++) { if ((mu1_P>binningx.at(i)) && (mu1_P<binningx.at(i+1))) { resultx=i+1; cout<<"resultxbin: "<< resultx<<endl; } } for (int j=0; j<(sizeofeta-1); j++) { if ((mu1_ETA>binningy.at(j)) && (mu1_ETA<binningy.at(j+1))) { resulty=j+1; cout<<"resultybin: "<< resulty<<endl; } } // for (int k=0; k<(sizeofntracks-1); k++) { // if ((nTracks>binningz.at(k)) && (nTracks<binningz.at(k+1))) // { // resultz=k+1; // cout<<"resultzbin: "<< resultz<<endl; /// } // } //end of for count++; weight=hname->GetBinContent(resultx,resulty); accumulate+=weight; } //end of else cout<<" Weight for this event: " <<weight<<endl; newtree->Fill(); } //end of tree get entries double averageeff; averageeff=accumulate/double((t->GetEntries())-numberofthrownevents); cout<<"Number of events:" << t->GetEntries()<< endl; cout<<"Final numberofthrownevent: "<< numberofthrownevents<<endl; cout<<"Average efficiency: "<< averageeff << " check: " <<accumulate/double(count)<<endl; g->Write("",TObject::kOverwrite); g->Close(); f->Close(); s->Close(); return(averageeff); }
[ "ss4314@ss4314-laptop.hep.ph.ic.ac.uk" ]
ss4314@ss4314-laptop.hep.ph.ic.ac.uk
782836d0151a4377577ca05ea9bfeac03923098a
1b01f4d3f40051fe237ef4a4b38e7669b6386d16
/layerstack.h
07e3fa75a3d65ecc2ac5591e2fc03bd5288f4dac
[]
no_license
zzdever/PMIG
b3122341049ee8bcbf6144552ceb3e9620c4e64c
343721ecb60e2b93f97f215a9acfa07bc1c24395
refs/heads/master
2021-01-13T01:45:10.765031
2014-10-26T12:25:10
2014-10-26T12:25:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
249
h
#ifndef LAYERSTACK_H #define LAYERSTACK_H #include <QStack> struct Layer{ bool isVisible; }; //class QStack<int>; class LayerStack:public QStack<int> { public: LayerStack(); //setVisible(int layerNum); }; #endif // LAYERSTACK_H
[ "zzdever@gmail.com" ]
zzdever@gmail.com
dada613ab8325603ef4953c06e763ff5b0222a6b
701cbe8daca4714623bb7014f833dccf9de498a8
/src/use-cases/utils/LogWriter.h
d785b4505879251f83f6e5892477d6cf7c647d90
[ "Apache-2.0" ]
permissive
staywizu/DFI-public
cea1a98c1b58140688d9260848646af62c848073
46abf43c9b6fb9720e053b28b192f8ee2de8630b
refs/heads/main
2023-07-20T11:25:34.880550
2021-09-01T09:36:22
2021-09-01T09:36:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,540
h
#pragma once #include <string> #include <functional> #include <iostream> #include <fstream> #include <sstream> #include <sys/stat.h> #include <sstream> #include <cctype> #include <locale> #include <algorithm> using namespace std; class Filehelper { public: // trim from start (in place) static void ltrim(std::string &s) { s.erase( s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } static string getFileName(const string &s) { char sep = '/'; size_t i = s.rfind(sep, s.length()); if (i != string::npos) { return (s.substr(i + 1, s.length() - i)); } return (""); } static bool fileExists(const std::string &file) { struct stat buffer; return (stat(file.c_str(), &buffer) == 0); } static bool isDirectory(string dir) { struct stat sb; if (stat(dir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) { return true; } return false; } static string splitLine(int keyPos, string line) { string value = ""; int index = 0; std::stringstream lineStream(line); while (std::getline(lineStream, value, '|')) { if (keyPos == index) { return value; } ++index; } return value; } static int countLineNumbers(string inFile) { ifstream file(inFile); string line = ""; int index = 0; while (file.good()) { getline(file, line); ++index; } //counts last line file.close(); return index - 1; } }; class LogWriter { public: static void log(std::string filename, size_t size, size_t iter, size_t time_us, size_t servers, size_t threads, std::string strategy, double straggling_prob = 0, size_t sleep_us = 0) { if (!Filehelper::fileExists(filename)) { std::ofstream log(filename, std::ios_base::app | std::ios_base::out); log << "Size,Iter,BW,Time,servers,threads,strategy,stragglingProb,sleepUs\n"; log.flush(); } std::ofstream log(filename, std::ios_base::app | std::ios_base::out); double time_ms = time_us / 1000; double time_s = time_ms / 1000; double total_size_mb = 1.0 * size * iter / 1024 / 1024; double bw = total_size_mb / time_s; log << size << "," << iter << "," << bw << "," << time_s << "," << servers << "," << threads << "," << strategy << "," << straggling_prob << "," << sleep_us << "\n"; } static void latency_point(double latency) { latencies.push_back(latency); } static void latency_log(std::string filename, size_t size, size_t iter, size_t servers, size_t threads, std::string strategy) { if (!Filehelper::fileExists(filename)) { std::ofstream log(filename, std::ios_base::app | std::ios_base::out); log << "Size,Iter,servers,threads,strategy,latAvg,lat95,lat99,latMin,latMax\n"; log.flush(); } std::ofstream log(filename, std::ios_base::app | std::ios_base::out); std::sort(latencies.begin(), latencies.end()); double avg_lat = 0; for (double rtt : latencies) { avg_lat += rtt; } avg_lat = avg_lat / latencies.size(); log << size << "," << iter << "," << "," << servers << "," << threads << "," << strategy << "," << avg_lat << "," << latencies[latencies.size()/2] << "," << latencies[95*latencies.size()/100] << "," << latencies[90*latencies.size()/100] << "," << latencies[0] << "," << latencies[latencies.size()-1] << "\n"; } private: static std::vector<double> latencies; };
[ "lassethostrup@gmail.com" ]
lassethostrup@gmail.com
190677057d68a020857c915b1091d385a8bb0ff3
f316a49629e4531e4e2e216d492573fe634be892
/pointer.cpp
73b07c81ba533ace298c451b717e4bb349a48728
[]
no_license
asdfghwunai/C-plusplus
a79a2346bbf1b7921b55ee68e6dd908c22d28b6a
7be33331539237c3f474d8b759cc9170c74fb456
refs/heads/master
2020-03-17T12:40:53.237642
2018-09-19T14:11:58
2018-09-19T14:11:58
133,598,435
0
0
null
null
null
null
UTF-8
C++
false
false
2,686
cpp
//=====数组指针与一维数组====== char a[5]={1,2,3,4,5}; char (*p3)[5]=&a; //也可以指向一维 char (*p4)[5]=(char (*)[5])a; //Clion必须强制类型转换一下,不然编辑阶段出错 cout<<&a<<" "<<p3+1<<" "<<p4+1<<endl; //0x7ffce31b1880 0x7ffce31b1885 0x7ffce31b1885 //======数组指针与二维数组====== int a[5][5]; int (*p)[4]; p=(int (*)[4])a; //Clion必须强制类型转换一下 printf("%p %d",&p[4][2]-&a[4][2],&p[4][2]-&a[4][2]); //0xfffffffffffffffc -4 /*---方法-- int (*p)[4]已说明加一次跳过4个int,还要注意指针加减是以元素为单位 p代表整个数组对象的地址,*p代表首元素的地址,*(*p+i)就代表一维数组中第i个数 二维数组==数组指针---一维指针--元素 指针数组==二维指针----一维指针----元素 */ //===a和&a==== int a[5]={1,2,3,4,5}; int *p1=(int *)(&a+1); int *p2=(int *)((int)a+1); //CLion又通不过,int *转int报错 printf("%x %x",*(p1-1),*p2); //5 0x200 00 00 /*--方法--- 第一个好说 第二个先写出a的数组内存分配,小端模式下由低地址到高地址: 01 00 00 00,02 00 00 00,03 00 00 00.... int(a)+1 是从第一个元素的第二个字节处开始取为 00 00 00 02,所以*p2为0x2 00 00 00 */ //=====一维数组的形参======= char a[]; char *b; void fun(char *p) void fun(char p[100]) void fun(char p[]) //=====二维数组的形参======= char a[3][4]; void fun(char (*p)[4]) void fun(char a[][4]) //====指针数组的形参==== char *a[5]; void fun(char **p) //====函数指针===== (*(void (*p)())0)() /*---方法---- 这里注意一个运算符优先级问题 强制类型和*是一个级别,但结合方向从右到左 */ //----函数指针------fun是个变量,不是函数啊 char * (*fun)(char *p); /*--一级就构建成功-----*/ //----函数指针数组----- char * (*fun[3])(char *p); //*fun[3] 就是一个数组,挺简单的进化到指针数组 /*--一级建指针,二级建数组----*/ //----函数指针数组指针----- char * (* (*fun)[3])(char *p); /*---先建建数组指针,一个指针指向这个数组指针,数组里的元素是函数指针---*/ //----动态建立二维数组--- //为邻接矩阵开辟空间和赋初值 arc = new int*[this->vexnum]; dis = new Dis[this->vexnum]; for (int i = 0; i < this->vexnum; i++) { arc[i]=new int[this->vexnum]; } //=========面试题==== /*-----1--------*/ char *p[]={"TENCENT","CAMPUS","RECRUITING"}; char **pp[]={p+2,p+1,p}; //对象是二级指针 char ***ppp=pp; //指向三级指针 printf("%s",**++ppp); //解引到一级 printf("%s",*++*++ppp); //解引到一级 //"CAMPUS" "CAMPUS"
[ "noreply@github.com" ]
noreply@github.com
59e497855fb8d14f7e5775fbfaf651b4f6793711
0f074515020efbaca94c3d8951fe0426275a382a
/source/win-direct2d/classes/CT/CTFontDescriptor.cpp
6bf6dd453eeef8c749b1a7f3e34276ceb0d00106
[ "MIT" ]
permissive
DeepInThought/opendl
38d9fe52392add49cc5ffe20b4a3fcf42115bdb6
0d5780c84de5477b3118f58809e871a3e0b21a98
refs/heads/master
2020-05-09T12:16:29.018500
2019-04-12T07:57:28
2019-04-12T07:57:28
181,107,083
1
1
null
2019-04-13T01:46:50
2019-04-13T01:46:49
null
UTF-8
C++
false
false
29
cpp
#include "CTFontDescriptor.h"
[ "Daniel@Win10" ]
Daniel@Win10
a842a1f8ff653c8cd346648c20042f70d8efe417
e15994a177f41a4eaec24d438261625e277f43bd
/Chapter07_ApplyingRetroEffect/Chapter07_ApplyingRetroEffect/RetroFilter.hpp
f541c147ba97e93f516ed780ecf3a7a8b1a34b62
[]
no_license
dingdaojun/opencv_for_ios_book_samples
e85cddd3f189b6ff475a28f325033a39ff6b0eda
95bfe7f06cf01f3fcf8d69cdf328de47e4efc8ad
refs/heads/master
2016-09-02T02:27:30.286128
2015-05-06T02:47:24
2015-05-06T02:47:24
35,135,854
7
3
null
null
null
null
UTF-8
C++
false
false
1,340
hpp
/***************************************************************************** * RetroFilter.hpp ****************************************************************************** * by Kirill Kornyakov and Alexander Shishkov, 15th May 2013 ****************************************************************************** * Chapter 7 of the "OpenCV for iOS" book * * Applying a retro effect demonstrates another interesting photo * effect that makes photos look old. * * Copyright Packt Publishing 2013. * http://bit.ly/OpenCV_for_iOS_book *****************************************************************************/ #pragma once #include "opencv2/core/core.hpp" void alphaBlendC1(cv::Mat src, cv::Mat dst, cv::Mat alpha); class RetroFilter { public: struct Parameters { cv::Size frameSize; cv::Mat fuzzyBorder; cv::Mat scratches; }; RetroFilter(const Parameters& params); virtual ~RetroFilter() {}; void applyToPhoto(const cv::Mat& frame, cv::Mat& retroFrame); void applyToVideo(const cv::Mat& frame, cv::Mat& retroFrame); protected: Parameters params_; cv::RNG rng_; float multiplier_; cv::Mat borderColor_; cv::Mat scratchColor_; std::vector<cv::Mat> sepiaPlanes_; cv::Mat sepiaH_; cv::Mat sepiaS_; };
[ "dingdaojun@smartdevices.com.cn" ]
dingdaojun@smartdevices.com.cn
516f1c93c166247a7fb63b504acbba0d15137d74
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/google/cloud/documentai/v1/internal/document_processor_auth_decorator.cc
0d9ab3541d28480294970d4698c6c8e606e02bda
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
googleapis/google-cloud-cpp
b96a6ee50c972371daa8b8067ddd803de95f54ba
178d6581b499242c52f9150817d91e6c95b773a5
refs/heads/main
2023-08-31T09:30:11.624568
2023-08-31T03:29:11
2023-08-31T03:29:11
111,860,063
450
351
Apache-2.0
2023-09-14T21:52:02
2017-11-24T00:19:31
C++
UTF-8
C++
false
false
16,004
cc
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/documentai/v1/document_processor_service.proto #include "google/cloud/documentai/v1/internal/document_processor_auth_decorator.h" #include <google/cloud/documentai/v1/document_processor_service.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace documentai_v1_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN DocumentProcessorServiceAuth::DocumentProcessorServiceAuth( std::shared_ptr<google::cloud::internal::GrpcAuthenticationStrategy> auth, std::shared_ptr<DocumentProcessorServiceStub> child) : auth_(std::move(auth)), child_(std::move(child)) {} StatusOr<google::cloud::documentai::v1::ProcessResponse> DocumentProcessorServiceAuth::ProcessDocument( grpc::ClientContext& context, google::cloud::documentai::v1::ProcessRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ProcessDocument(context, request); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncBatchProcessDocuments( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::BatchProcessRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncBatchProcessDocuments(cq, *std::move(context), request); }); } StatusOr<google::cloud::documentai::v1::FetchProcessorTypesResponse> DocumentProcessorServiceAuth::FetchProcessorTypes( grpc::ClientContext& context, google::cloud::documentai::v1::FetchProcessorTypesRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->FetchProcessorTypes(context, request); } StatusOr<google::cloud::documentai::v1::ListProcessorTypesResponse> DocumentProcessorServiceAuth::ListProcessorTypes( grpc::ClientContext& context, google::cloud::documentai::v1::ListProcessorTypesRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ListProcessorTypes(context, request); } StatusOr<google::cloud::documentai::v1::ProcessorType> DocumentProcessorServiceAuth::GetProcessorType( grpc::ClientContext& context, google::cloud::documentai::v1::GetProcessorTypeRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetProcessorType(context, request); } StatusOr<google::cloud::documentai::v1::ListProcessorsResponse> DocumentProcessorServiceAuth::ListProcessors( grpc::ClientContext& context, google::cloud::documentai::v1::ListProcessorsRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ListProcessors(context, request); } StatusOr<google::cloud::documentai::v1::Processor> DocumentProcessorServiceAuth::GetProcessor( grpc::ClientContext& context, google::cloud::documentai::v1::GetProcessorRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetProcessor(context, request); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncTrainProcessorVersion( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::TrainProcessorVersionRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncTrainProcessorVersion(cq, *std::move(context), request); }); } StatusOr<google::cloud::documentai::v1::ProcessorVersion> DocumentProcessorServiceAuth::GetProcessorVersion( grpc::ClientContext& context, google::cloud::documentai::v1::GetProcessorVersionRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetProcessorVersion(context, request); } StatusOr<google::cloud::documentai::v1::ListProcessorVersionsResponse> DocumentProcessorServiceAuth::ListProcessorVersions( grpc::ClientContext& context, google::cloud::documentai::v1::ListProcessorVersionsRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ListProcessorVersions(context, request); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncDeleteProcessorVersion( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::DeleteProcessorVersionRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncDeleteProcessorVersion(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncDeployProcessorVersion( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::DeployProcessorVersionRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncDeployProcessorVersion(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncUndeployProcessorVersion( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::UndeployProcessorVersionRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncUndeployProcessorVersion(cq, *std::move(context), request); }); } StatusOr<google::cloud::documentai::v1::Processor> DocumentProcessorServiceAuth::CreateProcessor( grpc::ClientContext& context, google::cloud::documentai::v1::CreateProcessorRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->CreateProcessor(context, request); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncDeleteProcessor( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::DeleteProcessorRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncDeleteProcessor(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncEnableProcessor( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::EnableProcessorRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncEnableProcessor(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncDisableProcessor( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::DisableProcessorRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncDisableProcessor(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncSetDefaultProcessorVersion( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::SetDefaultProcessorVersionRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncSetDefaultProcessorVersion(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncReviewDocument( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::ReviewDocumentRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncReviewDocument(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncEvaluateProcessorVersion( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::cloud::documentai::v1::EvaluateProcessorVersionRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncEvaluateProcessorVersion(cq, *std::move(context), request); }); } StatusOr<google::cloud::documentai::v1::Evaluation> DocumentProcessorServiceAuth::GetEvaluation( grpc::ClientContext& context, google::cloud::documentai::v1::GetEvaluationRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetEvaluation(context, request); } StatusOr<google::cloud::documentai::v1::ListEvaluationsResponse> DocumentProcessorServiceAuth::ListEvaluations( grpc::ClientContext& context, google::cloud::documentai::v1::ListEvaluationsRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ListEvaluations(context, request); } future<StatusOr<google::longrunning::Operation>> DocumentProcessorServiceAuth::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncGetOperation(cq, *std::move(context), request); }); } future<Status> DocumentProcessorServiceAuth::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::shared_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { auto& child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::shared_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) return make_ready_future(std::move(context).status()); return child->AsyncCancelOperation(cq, *std::move(context), request); }); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace documentai_v1_internal } // namespace cloud } // namespace google
[ "noreply@github.com" ]
noreply@github.com
be434cd8dfc0d7b92126c0944bf5b72d10ef818a
a01851ad710157c72e2a122a1f7735639f6db225
/Offer T03.cpp
6751c9e4873861e53f211382051915848c6c3e77
[]
no_license
we-are-kicking-lhx/xinxinalgorithm
9089629b210a5a0e199f374c74afc24742644f03
e988e3bca6438af6933378f374afb2627a5708fe
refs/heads/master
2021-06-27T10:50:22.979162
2020-11-23T07:01:23
2020-11-23T07:01:23
173,912,054
2
0
null
null
null
null
UTF-8
C++
false
false
325
cpp
nclass Solution { public: int findRepeatNumber(vector<int>& nums) { for(int i = 0;i < nums.size();i++){ while(i != nums[i]){ if(nums[nums[i]] == nums[i]) return nums[i]; swap(nums[nums[i]],nums[i]); } } return 0; } };
[ "1828151761@qq.com" ]
1828151761@qq.com
c44ebd8b63f878d711b3c72eb0f173e054deaf0d
105cea794f718d34d0c903f1b4b111fe44018d0e
/content/browser/interest_group/ad_auction_service_impl.h
df44625975cc41e0a4481cef253f3c805111235f
[ "BSD-3-Clause" ]
permissive
blueboxd/chromium-legacy
27230c802e6568827236366afe5e55c48bb3f248
e6d16139aaafff3cd82808a4660415e762eedf12
refs/heads/master.lion
2023-08-12T17:55:48.463306
2023-07-21T22:25:12
2023-07-21T22:25:12
242,839,312
164
12
BSD-3-Clause
2022-03-31T17:44:06
2020-02-24T20:44:13
null
UTF-8
C++
false
false
9,210
h
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_INTEREST_GROUP_AD_AUCTION_SERVICE_IMPL_H_ #define CONTENT_BROWSER_INTEREST_GROUP_AD_AUCTION_SERVICE_IMPL_H_ #include <map> #include <memory> #include <set> #include <vector> #include "base/containers/unique_ptr_adapters.h" #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/uuid.h" #include "content/browser/fenced_frame/fenced_frame_url_mapping.h" #include "content/browser/interest_group/auction_runner.h" #include "content/browser/interest_group/auction_worklet_manager.h" #include "content/browser/interest_group/bidding_and_auction_serializer.h" #include "content/browser/interest_group/interest_group_auction_reporter.h" #include "content/common/content_export.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/document_service.h" #include "content/services/auction_worklet/public/mojom/private_aggregation_request.mojom-forward.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/client_security_state.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" #include "third_party/blink/public/common/interest_group/auction_config.h" #include "third_party/blink/public/mojom/interest_group/ad_auction_service.mojom.h" #include "third_party/blink/public/mojom/interest_group/interest_group_types.mojom-forward.h" #include "third_party/blink/public/mojom/parakeet/ad_request.mojom.h" #include "url/gurl.h" #include "url/origin.h" namespace content { class AdAuctionPageData; class InterestGroupManagerImpl; struct BiddingAndAuctionServerKey; class RenderFrameHost; class RenderFrameHostImpl; class PrivateAggregationManager; // Implements the AdAuctionService service called by Blink code. class CONTENT_EXPORT AdAuctionServiceImpl final : public DocumentService<blink::mojom::AdAuctionService>, public AuctionWorkletManager::Delegate { public: // Factory method for creating an instance of this interface that is // bound to the lifetime of the frame or receiver (whichever is shorter). static void CreateMojoService( RenderFrameHost* render_frame_host, mojo::PendingReceiver<blink::mojom::AdAuctionService> receiver); // blink::mojom::AdAuctionService. void JoinInterestGroup(const blink::InterestGroup& group, JoinInterestGroupCallback callback) override; void LeaveInterestGroup(const url::Origin& owner, const std::string& name, LeaveInterestGroupCallback callback) override; void LeaveInterestGroupForDocument() override; void UpdateAdInterestGroups() override; void RunAdAuction( const blink::AuctionConfig& config, mojo::PendingReceiver<blink::mojom::AbortableAdAuction> abort_receiver, RunAdAuctionCallback callback) override; void DeprecatedGetURLFromURN( const GURL& urn_url, bool send_reports, DeprecatedGetURLFromURNCallback callback) override; void DeprecatedReplaceInURN( const GURL& urn_url, std::vector<blink::mojom::AdKeywordReplacementPtr> replacements, DeprecatedReplaceInURNCallback callback) override; void GetInterestGroupAdAuctionData( const url::Origin& seller, GetInterestGroupAdAuctionDataCallback callback) override; void CreateAdRequest(blink::mojom::AdRequestConfigPtr config, CreateAdRequestCallback callback) override; void FinalizeAd(const std::string& ads_guid, const blink::AuctionConfig& config, FinalizeAdCallback callback) override; scoped_refptr<network::WrapperSharedURLLoaderFactory> GetRefCountedTrustedURLLoaderFactory(); // AuctionWorkletManager::Delegate implementation: network::mojom::URLLoaderFactory* GetFrameURLLoaderFactory() override; network::mojom::URLLoaderFactory* GetTrustedURLLoaderFactory() override; void PreconnectSocket( const GURL& url, const net::NetworkAnonymizationKey& network_anonymization_key) override; RenderFrameHostImpl* GetFrame() override; scoped_refptr<SiteInstance> GetFrameSiteInstance() override; network::mojom::ClientSecurityStatePtr GetClientSecurityState() override; using DocumentService::origin; using DocumentService::render_frame_host; private: using ReporterList = std::list<std::unique_ptr<InterestGroupAuctionReporter>>; class BiddingAndAuctionDataConstructionState { public: BiddingAndAuctionDataConstructionState(); BiddingAndAuctionDataConstructionState( BiddingAndAuctionDataConstructionState&& other); ~BiddingAndAuctionDataConstructionState(); base::TimeTicks start_time; BiddingAndAuctionData data; base::Uuid request_id; url::Origin seller; GetInterestGroupAdAuctionDataCallback callback; }; // `render_frame_host` must not be null, and DocumentService guarantees // `this` will not outlive the `render_frame_host`. AdAuctionServiceImpl( RenderFrameHost& render_frame_host, mojo::PendingReceiver<blink::mojom::AdAuctionService> receiver); // `this` can only be destroyed by DocumentService. ~AdAuctionServiceImpl() override; // Checks if a join or leave interest group is allowed to be sent from the // current renderer. If not, returns false and invokes // ReportBadMessageAndDeleteThis(). bool JoinOrLeaveApiAllowedFromRenderer(const url::Origin& owner); // Returns true if `origin` is allowed to perform the specified // `interest_group_api_operation` in this frame. Must be called on worklet / // interest group origins before using them in any interest group API. bool IsInterestGroupAPIAllowed(ContentBrowserClient::InterestGroupApiOperation interest_group_api_operation, const url::Origin& origin) const; AdAuctionPageData* GetAdAuctionPageData(); // Deletes `auction`. void OnAuctionComplete( RunAdAuctionCallback callback, GURL urn_uuid, FencedFrameURLMapping::Id fenced_frame_urls_map_id, AuctionRunner* auction, bool manually_aborted, absl::optional<blink::InterestGroupKey> winning_group_key, absl::optional<blink::AdSize> requested_ad_size, absl::optional<blink::AdDescriptor> ad_descriptor, std::vector<blink::AdDescriptor> ad_component_descriptors, std::vector<std::string> errors, std::unique_ptr<InterestGroupAuctionReporter> reporter); void OnReporterComplete(ReporterList::iterator reporter_it); void MaybeLogPrivateAggregationFeatures( const std::vector<auction_worklet::mojom::PrivateAggregationRequestPtr>& private_aggregation_requests); void OnGotAuctionData(BiddingAndAuctionDataConstructionState state, BiddingAndAuctionData data); void OnGotBiddingAndAuctionServerKey( BiddingAndAuctionDataConstructionState state, absl::optional<BiddingAndAuctionServerKey> key); InterestGroupManagerImpl& GetInterestGroupManager() const; url::Origin GetTopWindowOrigin() const; // To avoid race conditions associated with top frame navigations (mentioned // in document_service.h), we need to save the values of the main frame // URL and origin in the constructor. const url::Origin main_frame_origin_; const GURL main_frame_url_; mojo::Remote<network::mojom::URLLoaderFactory> frame_url_loader_factory_; mojo::Remote<network::mojom::URLLoaderFactory> trusted_url_loader_factory_; // Ref counted wrapper of `trusted_url_loader_factory_`. This will be used for // reporting requests, which might happen after the frame is destroyed, when // `trusted_url_loader_factory_` no longer being available. scoped_refptr<network::WrapperSharedURLLoaderFactory> ref_counted_trusted_url_loader_factory_; // This must be before `auctions_`, since auctions may own references to // worklets it manages. AuctionWorkletManager auction_worklet_manager_; // Use a map instead of a list so can remove entries without destroying them. // TODO(mmenke): Switch to std::set() and use extract() once that's allowed. std::map<AuctionRunner*, std::unique_ptr<AuctionRunner>> auctions_; ReporterList reporters_; // Safe to keep as it will outlive the associated `RenderFrameHost` and // therefore `this`, being tied to the lifetime of the `StoragePartition`. const raw_ptr<PrivateAggregationManager> private_aggregation_manager_; // Whether a UseCounter has already been logged for usage of the Private // Aggregation API in general and the extended Private Aggregation API, // respectively. bool has_logged_private_aggregation_web_features_ = false; bool has_logged_extended_private_aggregation_web_feature_ = false; base::WeakPtrFactory<AdAuctionServiceImpl> weak_ptr_factory_{this}; }; } // namespace content #endif // CONTENT_BROWSER_INTEREST_GROUP_AD_AUCTION_SERVICE_IMPL_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
60b14a600e0d0f95f58508d778576cf5cd975608
a8e5571038152f09de6ad5550065e573b8bb92d8
/c++/練習問題解答例/Practice3-2.cpp
f3e962df59c7541ceeedf625d8841824cdabdffa
[]
no_license
ikdds/CppBook_SampleCode
3144654453ff6f01d685221641712db48ec5428a
6ee085f45e5a6ce82d1a849c20d81e5cc0881477
refs/heads/master
2020-06-08T16:04:09.263170
2019-06-22T17:22:12
2019-06-22T17:22:12
193,258,869
0
0
null
null
null
null
UTF-8
C++
false
false
92
cpp
#include<iostream> using namespace std; int main(void){ cout << 3.141*5 << endl; }
[ "abe12@mccc.jp" ]
abe12@mccc.jp
bcd94811942914e1c10fa38963b9856391e63e57
aedec0779dca9bf78daeeb7b30b0fe02dee139dc
/Modules/IO/src/GIPLImageWriter.cc
26ff975dc744af7ec64b89e6b2c35275fe2e3b00
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BioMedIA/MIRTK
ca92f52b60f7db98c16940cd427a898a461f856c
973ce2fe3f9508dec68892dbf97cca39067aa3d6
refs/heads/master
2022-08-08T01:05:11.841458
2022-07-28T00:03:25
2022-07-28T10:18:00
48,962,880
171
78
Apache-2.0
2022-07-28T10:18:01
2016-01-03T22:25:55
C++
UTF-8
C++
false
false
4,127
cc
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2008-2015 Imperial College London * Copyright 2008-2015 Daniel Rueckert, Julia Schnabel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "GIPL.h" #include "mirtk/GIPLImageWriter.h" #include "mirtk/ImageWriterFactory.h" namespace mirtk { // Register image reader with object factory during static initialization mirtkAutoRegisterImageWriterMacro(GIPLImageWriter); // ----------------------------------------------------------------------------- Array<string> GIPLImageWriter::Extensions() { Array<string> exts(1); exts[0] = ".gipl"; return exts; } // ----------------------------------------------------------------------------- void GIPLImageWriter::Initialize() { // Initialize base class ImageWriter::Initialize(); // Write image dimensions this->WriteAsShort(_Input->X(), 0); this->WriteAsShort(_Input->Y(), 2); this->WriteAsShort(_Input->Z(), 4); this->WriteAsShort(_Input->T(), 6); // Write type switch (_Input->GetScalarType()) { case MIRTK_VOXEL_CHAR: { this->WriteAsShort(GIPL_CHAR, 8); break; } case MIRTK_VOXEL_UNSIGNED_CHAR: { this->WriteAsShort(GIPL_U_CHAR, 8); break; } case MIRTK_VOXEL_SHORT: { this->WriteAsShort(GIPL_SHORT, 8); break; } case MIRTK_VOXEL_UNSIGNED_SHORT: { this->WriteAsShort(GIPL_U_SHORT, 8); break; } case MIRTK_VOXEL_FLOAT: { this->WriteAsShort(GIPL_FLOAT, 8); break; } case MIRTK_VOXEL_DOUBLE: { this->WriteAsShort(GIPL_DOUBLE, 8); break; } default: cerr << this->NameOfClass() << "::Initialize: Not supported for this image type" << endl; exit(1); } // Write voxel dimensions double xsize, ysize, zsize, tsize; _Input->GetPixelSize(&xsize, &ysize, &zsize, &tsize); this->WriteAsFloat(static_cast<float>(xsize), 10); this->WriteAsFloat(static_cast<float>(ysize), 14); this->WriteAsFloat(static_cast<float>(zsize), 18); this->WriteAsFloat(static_cast<float>(tsize), 22); // Write patient description for (int i = 0; i < 80; i++) { this->WriteAsChar(char(0), 26 + i*sizeof(char)); } // Write image orientation double xaxis[3], yaxis[3], zaxis[3]; _Input->GetOrientation(xaxis, yaxis, zaxis); this->WriteAsFloat(static_cast<float>(xaxis[0]), 106); this->WriteAsFloat(static_cast<float>(xaxis[1]), 110); this->WriteAsFloat(static_cast<float>(xaxis[2]), 114); this->WriteAsFloat(static_cast<float>(yaxis[0]), 122); this->WriteAsFloat(static_cast<float>(yaxis[1]), 126); this->WriteAsFloat(static_cast<float>(yaxis[2]), 130); // Write identifier this->WriteAsInt(0, 154); // Write spare bytes for (int i = 0; i < 28; i++) { this->WriteAsChar(char(0), 158 + i*sizeof(char)); } // Write flag and orientation this->WriteAsChar(char(0), 186); this->WriteAsChar(char(0), 187); // Write min and max values double min, max; _Input->GetMinMaxAsDouble(&min, &max); this->WriteAsDouble(min, 188); this->WriteAsDouble(max, 196); // Write origin double pos[3]; _Input->GetOrigin(pos[0], pos[1], pos[2]); this->WriteAsDouble(pos[0], 204); this->WriteAsDouble(pos[1], 212); this->WriteAsDouble(pos[2], 220); this->WriteAsDouble(.0, 228); // Write magic number this->WriteAsFloat(.0f, 236); this->WriteAsFloat(.0f, 240); this->WriteAsUInt(GIPL_MAGIC_EXT, 244); this->WriteAsFloat(.0f, 248); this->WriteAsUInt(GIPL_MAGIC1, 252); // Calculate data address _Start = GIPL_HEADERSIZE; } } // namespace mirtk
[ "andreas.schuh.84@gmail.com" ]
andreas.schuh.84@gmail.com
b7d5f7342142837179cb19c823337f982570bc0d
2cb738d554ef506568197a9a1111e223c6e4a1d2
/5.Challenge 1/Conversion.cpp
987c6634b55ec31d364b328d42127a6aa58b73e3
[]
no_license
palaktyagi000/Daily-CPP-Practice
d135c7ffebf24e22185bd2e3dfce0ac8438303fb
4854d33f142d0982c77ace8e52a5290e266ca667
refs/heads/master
2023-07-05T05:18:07.645960
2021-08-20T08:49:14
2021-08-20T08:49:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
287
cpp
//Conversion (Fahrenheit to celsius) #include<iostream> using namespace std; int main(){ int max_F, min_F, step; cin>>min_F>>max_F>>step; int C; while(min_F<=100){ C = (5 * (min_F - 32))/9; cout<<min_F<<" "<<C<<endl; min_F = min_F + step; } return 0; }
[ "palaktyagi000@gmail.com" ]
palaktyagi000@gmail.com
03178ae6262041597b8d69c57b9a78d3fa637a10
f9561abe199be749d16106fc181e00d6c921e75e
/include/ScreenZone.h
4b29623560c5f7ac93ca37af6e5128c9fde2cf24
[]
no_license
marsaud/sdl1
e1794d9203b9a4448ee89e10708021f7846647c9
cadb0e029ef9d96d1f94e70058c5d3c6ff7aff74
refs/heads/master
2021-01-25T08:54:35.045678
2014-11-13T20:49:03
2014-11-13T20:49:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
437
h
#ifndef SCREENZONE_H #define SCREENZONE_H #include <string> #include <SDL/SDL.h> #include <SDL/SDL_ttf.h> class ScreenZone { public: ScreenZone(Sint16 const textZoneLeft, Sint16 const textZoneTop, TTF_Font* const font); virtual ~ScreenZone(); void render(SDL_Surface* screen, std::string const& display); protected: private: SDL_Rect m_textPos; SDL_Color m_color; TTF_Font* m_font; }; #endif // SCREENZONE_H
[ "marsaud.fabrice@neuf.fr" ]
marsaud.fabrice@neuf.fr
7031a5c668ab582ccda119a8143c3d3e7d24bb33
ab1c643f224197ca8c44ebd562953f0984df321e
/snapin/wsecmgr/genserv.cpp
d88cdae78a5746ea991eb3bad274b8f3339744b8
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_admin
e162e0452fb2067f0675745f2273d5c569798709
d36e522f16bd866384bec440517f954a1a5c4a4d
refs/heads/master
2023-04-12T13:25:45.807158
2021-04-13T16:33:59
2021-04-13T16:33:59
357,613,696
0
1
null
null
null
null
UTF-8
C++
false
false
16,756
cpp
//+-------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1994 - 2001. // // File: genserv.cpp // // Contents: Functions for handling the services within SCE // // History: // //--------------------------------------------------------------------------- #include "stdafx.h" #include "afxdlgs.h" #include "cookie.h" #include "snapmgr.h" #include "cservice.h" #include "aservice.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // Event handlers for IFrame::Notify void CSnapin::CreateProfServiceResultList(MMC_COOKIE cookie, FOLDER_TYPES type, PEDITTEMPLATE pSceInfo, LPDATAOBJECT pDataObj ) { if ( pSceInfo == NULL || pSceInfo->pTemplate == NULL ) { return; } PSCE_SERVICES pAllServices=NULL, pConfigService; DWORD rc; rc = SceEnumerateServices( &pAllServices, TRUE//FALSE ); if ( rc == NO_ERROR ) { for ( PSCE_SERVICES pThisService=pAllServices; pThisService != NULL; pThisService = pThisService->Next ) { for ( pConfigService=pSceInfo->pTemplate->pServices; pConfigService != NULL; pConfigService = pConfigService->Next ) { if ( _wcsicmp(pThisService->ServiceName, pConfigService->ServiceName) == 0 ) { break; } } // // no matter if config exist for the service, add it // PWSTR DisplayName=pThisService->DisplayName; if ( DisplayName == NULL && pConfigService != NULL ) { DisplayName = pConfigService->DisplayName; } if ( DisplayName == NULL ) { DisplayName = pThisService->ServiceName; } AddResultItem(DisplayName, (LONG_PTR)pThisService, (LONG_PTR)pConfigService, ITEM_PROF_SERV, -1, cookie, FALSE, pThisService->ServiceName, (LONG_PTR)pAllServices, pSceInfo, pDataObj, NULL, IDS_SYSTEM_SERVICES); //assign an ID to this item } // // add the ones not exist in the current system // for ( pConfigService=pSceInfo->pTemplate->pServices; pConfigService != NULL; pConfigService = pConfigService->Next ) { for ( pThisService=pAllServices; pThisService != NULL; pThisService = pThisService->Next ) { if ( _wcsicmp(pThisService->ServiceName, pConfigService->ServiceName) == 0 ) break; } if ( pThisService == NULL ) { // // the configuration does not exist on local system // PWSTR DisplayName=pConfigService->DisplayName; if ( DisplayName == NULL ) { DisplayName = pConfigService->ServiceName; } AddResultItem( DisplayName, 0, (LONG_PTR)pConfigService, ITEM_PROF_SERV, -1, cookie, FALSE, pConfigService->ServiceName, (LONG_PTR)pAllServices, pSceInfo, pDataObj, NULL, IDS_SYSTEM_SERVICES); //Assign an ID to this item } } } } void CSnapin::DeleteServiceResultList(MMC_COOKIE cookie) { CFolder* pFolder = (CFolder *)cookie; // pFolder could be NULL for the root. if ( pFolder == NULL ) return; FOLDER_TYPES type = pFolder->GetType(); if ( type != AREA_SERVICE && type != AREA_SERVICE_ANALYSIS ) return; if ( m_pSelectedFolder == pFolder && m_resultItemHandle ) { POSITION pos = NULL; CResult *pResult = NULL; if (m_pSelectedFolder->GetResultItem( m_resultItemHandle, pos, &pResult) != ERROR_SUCCESS) { if ( pResult != NULL ) { PSCE_SERVICES pAllServices = (PSCE_SERVICES)(pResult->GetID()); SceFreeMemory(pAllServices, SCE_STRUCT_SERVICES); } } } } //+-------------------------------------------------------------------------- // // Method: CreateAnalysisServiceResultList // // Synopsis: Create the list of items to display in the result pane // when in the Analysis/Service section // // // Arguments: [cookie] - // [type] - // [pSceInfo] - // [pBase] - // [pDataObj] - // // Returns: none // //--------------------------------------------------------------------------- void CSnapin::CreateAnalysisServiceResultList(MMC_COOKIE cookie, FOLDER_TYPES type, PEDITTEMPLATE pSceInfo, PEDITTEMPLATE pBase, LPDATAOBJECT pDataObj ) { if ( pSceInfo == NULL || pBase == NULL ) { return; } PSCE_SERVICES pAllServices=NULL, pConfigService, pAnalService; DWORD rc; rc = SceEnumerateServices( &pAllServices, FALSE ); if ( rc == NO_ERROR ) { for ( PSCE_SERVICES pThisService=pAllServices; pThisService != NULL; pThisService = pThisService->Next ) { // // look for base setting on this service // for ( pConfigService=pBase->pTemplate->pServices; pConfigService != NULL; pConfigService = pConfigService->Next ) { if ( _wcsicmp(pThisService->ServiceName, pConfigService->ServiceName) == 0 ) { break; } } // // look for current setting on this service // for ( pAnalService=pSceInfo->pTemplate->pServices; pAnalService != NULL; pAnalService = pAnalService->Next ) { if ( _wcsicmp(pThisService->ServiceName, pAnalService->ServiceName) == 0 ) { break; } } if ( NULL == pAnalService ) { if ( NULL != pConfigService ) { // // a matched item, use base info as the analysis info // PWSTR DisplayName=pThisService->DisplayName; if ( NULL == DisplayName ) DisplayName = pConfigService->DisplayName; if ( NULL == DisplayName ) DisplayName = pThisService->ServiceName; AddResultItem(DisplayName, (LONG_PTR)pConfigService, // use the same base info (LONG_PTR)pConfigService, ITEM_ANAL_SERV, 0, cookie, FALSE, pThisService->ServiceName, (LONG_PTR)pAllServices, pBase, pDataObj, NULL, IDS_SYSTEM_SERVICES); // Assign an ID to this item } else { // // a new service // PWSTR DisplayName=pThisService->DisplayName; if ( NULL == DisplayName ) DisplayName = pThisService->ServiceName; AddResultItem(DisplayName, (LONG_PTR)pConfigService, // use the same base info (LONG_PTR)pConfigService, ITEM_ANAL_SERV, SCE_STATUS_NEW_SERVICE, cookie, FALSE, pThisService->ServiceName, (LONG_PTR)pAllServices, pBase, pDataObj, NULL, IDS_SYSTEM_SERVICES); // Assign an ID to this item } } else { if ( NULL != pConfigService ) { // // a matched or mismatched item, depending on status // PWSTR DisplayName=pThisService->DisplayName; if ( NULL == DisplayName ) DisplayName = pConfigService->DisplayName; if ( NULL == DisplayName ) DisplayName = pAnalService->DisplayName; if ( NULL == DisplayName ) DisplayName = pThisService->ServiceName; AddResultItem(DisplayName, (LONG_PTR)pAnalService, (LONG_PTR)pConfigService, ITEM_ANAL_SERV, pAnalService->Status, cookie, FALSE, pThisService->ServiceName, (LONG_PTR)pAllServices, pBase, pDataObj, NULL, IDS_SYSTEM_SERVICES); // Assign an ID to this item } else { // // a not configured service, use last analysis as default // PWSTR DisplayName=pThisService->DisplayName; if ( NULL == DisplayName ) DisplayName = pAnalService->DisplayName; if ( NULL == DisplayName ) DisplayName = pThisService->ServiceName; AddResultItem(DisplayName, (LONG_PTR)pAnalService, 0, ITEM_ANAL_SERV, SCE_STATUS_NOT_CONFIGURED, cookie, FALSE, pThisService->ServiceName, (LONG_PTR)pAllServices, pBase, pDataObj, NULL, IDS_SYSTEM_SERVICES); // Assign an ID to this item } } } // // ignore the services not existing on the current system // /* for ( pConfigService=pSceInfo->pTemplate->pServices; pConfigService != NULL; pConfigService = pConfigService->Next ) { for ( pThisService=pAllServices; pThisService != NULL; pThisService = pThisService->Next ) { if ( _wcsicmp(pThisService->ServiceName, pConfigService->ServiceName) == 0 ) break; } if ( pThisService == NULL ) { // // the configuration does not exist on local system // PWSTR DisplayName=pConfigService->DisplayName; if ( DisplayName == NULL ) { DisplayName = pConfigService->ServiceName; } AddResultItem( DisplayName, 0, (DWORD)pConfigService, ITEM_PROF_SERV, -1, cookie,false, pConfigService->ServiceName,(DWORD)pAllServices,pSceInfo); } } */ } } HRESULT CSnapin::GetDisplayInfoForServiceNode(RESULTDATAITEM *pResult, CFolder *pFolder, CResult *pData) { if ( NULL == pResult || NULL == pFolder || NULL == pData ) { return E_INVALIDARG; } // get display info for columns 1,2, and 3 PSCE_SERVICES pService = (PSCE_SERVICES)(pData->GetBase()); PSCE_SERVICES pSetting = (PSCE_SERVICES)(pData->GetSetting()); if ( pResult->nCol > 3 ) { m_strDisplay = L""; } else if ((pResult->nCol == 3) && ((GetModeBits() & MB_RSOP) == MB_RSOP)) { m_strDisplay = pData->GetSourceGPOString(); } else if ( NULL == pService ) { if ( pFolder->GetType() == AREA_SERVICE_ANALYSIS && NULL != pSetting ) { m_strDisplay.LoadString(IDS_NOT_CONFIGURED); //(IDS_INSPECTED); } else { m_strDisplay.LoadString(IDS_NOT_CONFIGURED); } } else if ( pFolder->GetType() == AREA_SERVICE_ANALYSIS && (NULL == pSetting || NULL == pSetting->General.pSecurityDescriptor )) { m_strDisplay.LoadString(IDS_CONFIGURED); } else if (pResult->nCol == 1) { // both pService and pSetting exist // startup value if ( pFolder->GetType() == AREA_SERVICE ) { switch ( pService->Startup ) { case SCE_STARTUP_AUTOMATIC: m_strDisplay.LoadString(IDS_AUTOMATIC); break; case SCE_STARTUP_MANUAL: m_strDisplay.LoadString(IDS_MANUAL); break; default: m_strDisplay.LoadString(IDS_DISABLED); } } else { // analysis area if ( pService->Startup == pSetting->Startup ) { m_strDisplay.LoadString(IDS_OK); } else { m_strDisplay.LoadString(IDS_INVESTIGATE); } } } else if ( pResult->nCol == 2 ) { // column 2 - permission if ( pService->SeInfo & DACL_SECURITY_INFORMATION ) { if ( pFolder->GetType() == AREA_SERVICE ) { m_strDisplay.LoadString(IDS_CONFIGURED); } else { // analysis area if ( pService == pSetting || pSetting->Status == 0 ) { m_strDisplay.LoadString(IDS_OK); } else { m_strDisplay.LoadString(IDS_INVESTIGATE); } } } else {// permission is not configured m_strDisplay.LoadString(IDS_NOT_CONFIGURED); } } pResult->str = (LPOLESTR)(LPCTSTR)m_strDisplay; return S_OK; } //+-------------------------------------------------------------------------- // // Method: SetupLinkServiceNodeToBase // // Synopsis: // // // // Arguments: [bAdd] - // [theNode] - // // Returns: none // //--------------------------------------------------------------------------- void CSnapin::SetupLinkServiceNodeToBase(BOOL bAdd, LONG_PTR theNode) { PEDITTEMPLATE pet; PSCE_PROFILE_INFO pBaseInfo; // // look for the address stored in m_pData->GetBase() // if found it, delete it. // if (0 == theNode) { return; } pet = GetTemplate(GT_COMPUTER_TEMPLATE, AREA_SYSTEM_SERVICE); if (NULL == pet) { return; } pBaseInfo = pet->pTemplate; PSCE_SERVICES pServParent, pService; for ( pService=pBaseInfo->pServices, pServParent=NULL; pService != NULL; pServParent=pService, pService=pService->Next ) { if ( theNode == (LPARAM)pService ) { // // find the service node // if ( !bAdd ) { // // unlink // if ( pServParent == NULL ) { // // the first service // pBaseInfo->pServices = pService->Next; } else { pServParent->Next = pService->Next; } pService->Next = NULL; } break; } } if ( bAdd && NULL == pService ) { // // need to add this one // pService = (PSCE_SERVICES)theNode; pService->Next = pBaseInfo->pServices; pBaseInfo->pServices = pService; } return; } void CSnapin::AddServiceNodeToProfile(PSCE_SERVICES pNode) { PEDITTEMPLATE pet; PSCE_PROFILE_INFO pProfileInfo; if ( pNode ) { pet = GetTemplate(GT_LAST_INSPECTION, AREA_SYSTEM_SERVICE); if (!pet) { return; } pProfileInfo = pet->pTemplate; pNode->Next = pProfileInfo->pServices; pProfileInfo->pServices = pNode; } return; }
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
d0652b35fde616c6709707780689173382dc7c2d
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Trigger/TrigEvent/TrigParticleTPCnv/src/TrigEFBphysContainerCnv_tlp2.cxx
222b0a5dbee344e45d7ddbfe494447187860729c
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
710
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #include "TrigParticleTPCnv/TrigEFBphysContainerCnv_tlp2.h" TrigEFBphysContainerCnv_tlp2::TrigEFBphysContainerCnv_tlp2() { // add the "main" base class converter (ie. TrigEFBphysContainerCnv) addMainTPConverter(); // Add all converters defined in this top level converter: // never change the order of adding converters! addTPConverter( &m_EFBphysCnv); } void TrigEFBphysContainerCnv_tlp2::setPStorage( TrigEFBphysContainer_tlp2 *storage ) { setMainCnvPStorage( &storage->m_TrigEFBphysContainers ); m_EFBphysCnv. setPStorage(&storage->m_EFBphys); }
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
e4f2a7ab4eaeaf02c2937f34b063fdee20962266
9cd5a1ed41407be7718cc449846e2c8dd5b85164
/Obstaculo.h
b8324c6653e92c9afa16c6103cb657b93c9d6c9d
[]
no_license
maiyq1/MovColis
23f93b0493f6ddc8b5fc6b624b7b79d826b3a681
997fa1ea89b830b8becff6a5defad3b051e7c5dc
refs/heads/master
2023-05-28T21:46:33.185752
2021-06-14T17:40:28
2021-06-14T17:40:28
376,898,645
0
0
null
null
null
null
UTF-8
C++
false
false
968
h
#pragma once #include "Entidad.h" class Obstaculo : public Entidad { public: Obstaculo() { x = rand() % 200; y = rand() % 200; ancho = alto = rand() % 25 + 25; } }; class Obstaculos { private: vector <Obstaculo*> obstaculos; public: Obstaculos(int n, Rectangle obj) { for (int i = 0; i < n; i++) { Obstaculo* obs = new Obstaculo(); if (obs->Area().IntersectsWith(obj) == false && Colision(obs->Area()) == false) obstaculos.push_back(obs); else { delete obs; i--; } } } ~Obstaculos() { for (int i = 0; i < obstaculos.size(); i++) delete obstaculos.at(i); } bool Colision(Rectangle obj) { for each (Obstaculo * obs in obstaculos) { if (obs->NextArea().IntersectsWith(obj)) return true; } return false; } void Mover(Graphics^ g) { for each (Obstaculo * obs in obstaculos) obs->Mover(g); } void Mostrar(Graphics^ g) { for each (Obstaculo * obs in obstaculos) obs->Mostrar(g); } };
[ "mijael.yq2002@gmail.com" ]
mijael.yq2002@gmail.com
b59faa2746a2ecd782e3487c3d9ce1dd18183ce5
a226793d4c3cc9c3a8f3ca8f7ec71f7165ccf4c3
/src/qt/optionsdialog.h
a0faa206a4b32cf1c1c5a68dbccb950a7c6f00ef
[ "MIT" ]
permissive
Stasis-Project/Stasis-Core
d70282be76177407a369dc9fb2abcd411596856d
39ff9d159634a81dd036a0d74fc738a783c25f41
refs/heads/master
2020-04-13T02:43:17.800246
2018-12-23T21:09:23
2018-12-23T21:09:23
162,910,781
1
0
null
null
null
null
UTF-8
C++
false
false
1,487
h
#ifndef OPTIONSDIALOG_H #define OPTIONSDIALOG_H #include <QDialog> namespace Ui { class OptionsDialog; } class OptionsModel; class MonitoredDataMapper; class QValidatedLineEdit; /** Preferences dialog. */ class OptionsDialog : public QDialog { Q_OBJECT public: explicit OptionsDialog(QWidget *parent = 0); ~OptionsDialog(); void setModel(OptionsModel *model); void setMapper(); protected: bool eventFilter(QObject *object, QEvent *event); private slots: /* enable only apply button */ void enableApplyButton(); /* disable only apply button */ void disableApplyButton(); /* enable apply button and OK button */ void enableSaveButtons(); /* disable apply button and OK button */ void disableSaveButtons(); /* set apply button and OK button state (enabled / disabled) */ void setSaveButtonState(bool fState); void on_okButton_clicked(); void on_cancelButton_clicked(); void on_applyButton_clicked(); void showRestartWarning_Proxy(); void showRestartWarning_Lang(); void updateDisplayUnit(); void handleProxyIpValid(QValidatedLineEdit *object, bool fState); void enableDarksend(); signals: void proxyIpValid(QValidatedLineEdit *object, bool fValid); private: Ui::OptionsDialog *ui; OptionsModel *model; MonitoredDataMapper *mapper; bool fRestartWarningDisplayed_Proxy; bool fRestartWarningDisplayed_Lang; bool fProxyIpValid; }; #endif // OPTIONSDIALOG_H
[ "jared@stasisgaming.com" ]
jared@stasisgaming.com
54e2fc13ba6b1dd17e31f21c80f33c9505366fe2
2f15e9ddbb6e2b6bf708f1a5c63cba52d35dd0e4
/videosource.h
aafb946a9d084f78367d6022f5794d50ff8deb04
[]
no_license
7956968/CameraExperiment
ba31c2d355601a1501c5c1aa11382846a50039a6
4daecd141218f58d48fb74d8d3ccfee11e12b0db
refs/heads/master
2020-12-06T02:08:44.642394
2018-03-08T16:32:22
2018-03-08T16:32:22
232,311,137
0
1
null
2020-01-07T11:34:26
2020-01-07T11:34:25
null
UTF-8
C++
false
false
347
h
#ifndef VIDEOSOURCE_H #define VIDEOSOURCE_H #include <QObject> #include "videoframe.h" class VideoSource: public QObject { Q_OBJECT public: VideoSource(QObject * parent = nullptr); public Q_SLOTS: void setFrame(const VideoFramePtr & frame); Q_SIGNALS: void frameReady(const VideoFramePtr & frame); }; #endif // VIDEOSOURCE_H
[ "fran.nadales@displaynote.com" ]
fran.nadales@displaynote.com
6e1854912a05a5a5966a4255b28a33c827dddf22
0c0cc27767828a8b3bfef84683c8250d985f7ac6
/extensions/common/extension_features.cc
5d189678bd025c3ad4cc0b8f0b35e935b51d7dae
[ "BSD-3-Clause" ]
permissive
sharpie33/chromium
1cb882b849fed8dcfd7f5375ebecc2ace82c4b81
82e92e2ad746093bebb73b807e44482dbf9d6695
refs/heads/master
2023-01-08T05:05:05.415432
2020-02-09T17:43:42
2020-02-09T17:43:42
238,395,399
1
0
BSD-3-Clause
2020-02-05T07:47:43
2020-02-05T07:47:42
null
UTF-8
C++
false
false
2,361
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/common/extension_features.h" namespace extensions_features { // Controls whether we redirect the NTP to the chrome://extensions page or show // a middle slot promo, and which of the the three checkup banner messages // (performance focused, privacy focused or neutral) to show. const base::Feature kExtensionsCheckup{"ExtensionsCheckup", base::FEATURE_DISABLED_BY_DEFAULT}; // Parameters for ExtensionsCheckup feature. const char kExtensionsCheckupEntryPointParameter[] = "entry_point"; const char kExtensionsCheckupBannerMessageParameter[] = "banner_message_type"; // Constants for ExtensionsCheckup parameters. // Indicates that the user should be shown the chrome://extensions page on // startup. const char kStartupEntryPoint[] = "startup"; // Indicates that the user should be shown a promo on the NTP leading to the // chrome://extensions page. const char kNtpPromoEntryPoint[] = "promo"; // Indicates the focus of the message shown on chrome://the extensions page // banner and the NTP promo. const char kPerformanceMessage[] = "0"; const char kPrivacyMessage[] = "1"; const char kNeutralMessage[] = "2"; // Controls whether the CORB allowlist [1] is also applied to OOR-CORS (e.g. // whether non-allowlisted content scripts can bypass CORS in OOR-CORS mode). // See also: https://crbug.com/920638 // // [1] // https://www.chromium.org/Home/chromium-security/extension-content-script-fetches const base::Feature kCorbAllowlistAlsoAppliesToOorCors{ "CorbAllowlistAlsoAppliesToOorCors", base::FEATURE_DISABLED_BY_DEFAULT}; const char kCorbAllowlistAlsoAppliesToOorCorsParamName[] = "AllowlistForCorbAndCors"; // Forces requests to go through WebRequestProxyingURLLoaderFactory. const base::Feature kForceWebRequestProxyForTest{ "ForceWebRequestProxyForTest", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables the UI in the install prompt which lets a user choose to withhold // requested host permissions by default. const base::Feature kAllowWithholdingExtensionPermissionsOnInstall{ "AllowWithholdingExtensionPermissionsOnInstall", base::FEATURE_DISABLED_BY_DEFAULT}; } // namespace extensions_features
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
397ae987a3e8382fdd899f8a258ac1431ae7f672
2ee540793f0a390d3f418986aa7e124083760535
/Online Judges/AtCoder/Beginner Contest 124/c.cpp
6725abbb5008c85f29af98b5773fc35f117c5615
[]
no_license
dickynovanto1103/CP
6323d27c3aed4ffa638939f26f257530993401b7
f1e5606904f22bb556b1d4dda4e574b409abc17c
refs/heads/master
2023-08-18T10:06:45.241453
2023-08-06T23:58:54
2023-08-06T23:58:54
97,298,343
0
0
null
null
null
null
UTF-8
C++
false
false
781
cpp
#include <bits/stdc++.h> using namespace std; #define inf 1000000000 #define unvisited -1 #define visited 1 #define eps 1e-9 #define mp make_pair #define pb push_back #define pi acos(-1.0) #define uint64 unsigned long long #define FastSlowInput ios_base::sync_with_stdio(false); cin.tie(NULL); typedef long long ll; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; int main(){ string s; cin>>s; int n,i,j; n = s.length(); string s1 = "", s2 = ""; bool is0 = false; for(i=0;i<n;i++){ if(is0){ s1 += '0'; s2 += '1'; is0 = false; }else{ s1 += '1'; s2 += '0'; is0 = true; } } int ans1 = 0, ans2 = 0; for(i=0;i<n;i++){ if(s1[i] != s[i]){ans1++;} if(s2[i] != s[i]){ans2++;} } printf("%d\n",min(ans1,ans2)); return 0; };
[ "dickynovanto1103@gmail.com" ]
dickynovanto1103@gmail.com
978ec33c02b43d2f7917fbbeaf4c4e88e73f1e48
7d793727110eaa9d7bb19de1ebbfb2421c21027c
/BattleTankGame/Source/BattleTankGame/Public/TankTrack.h
c263b2b74949f8f279329275b6877edd19605bf9
[]
no_license
BeauTaapken/BattleTank
e2363cb5cf9b07754b92eb301b228e2e1ede30a6
9baa26889d8bd580b75f58b17eb563727b305c41
refs/heads/develop
2022-12-06T12:34:08.811907
2022-04-25T14:08:45
2022-04-25T14:08:45
246,575,359
0
0
null
2023-08-30T15:52:47
2020-03-11T13:14:53
C++
UTF-8
C++
false
false
1,010
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/StaticMeshComponent.h" #include "TankTrack.generated.h" /** * TankTrack is used to set maximum driving force and to apply forces to the tank. */ UCLASS(meta = (BlueprintSpawnableComponent)) class BATTLETANKGAME_API UTankTrack : public UStaticMeshComponent { GENERATED_BODY() public: // Sets a throttle between -1 and +1 UFUNCTION(BlueprintCallable, Category = "Input") void SetThrottle(float Throttle); // Max force per track in Newtons UPROPERTY(EditDefaultsOnly) float TrackMaxDrivingForce = 40000000;// Assume 40 tonne tank and 1g acceleration private: UTankTrack(); virtual void BeginPlay() override; UFUNCTION() void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit); void ApplySidewaysForce(); void DriveTrack(); float CurrentThrottle = 0; };
[ "beau@lioncode.nl" ]
beau@lioncode.nl
fff37313d192450681fb9f7a7ebcc80cab277ee0
b654bc8c1ca3cb7dfd32eb669b301a31d1b96a5d
/drishti/QGLViewer/VRender/Vector2.cpp
a95fdbf8fd792c9af1de3d00ab7fb01eed2bca31
[ "MIT" ]
permissive
RussellGarwood/drishti
8e895b0edace1a165c538e1b4694f7b0103b482e
ddfe6cf028d48cb100d534f54e0c646f12eb086c
refs/heads/master
2020-03-27T00:08:32.340775
2018-08-21T17:51:15
2018-08-21T17:51:15
145,597,467
0
0
MIT
2018-08-21T17:32:28
2018-08-21T17:32:28
null
UTF-8
C++
false
false
4,140
cpp
/* This file is part of the VRender library. Copyright (C) 2005 Cyril Soler (Cyril.Soler@imag.fr) Version 1.0.0, released on June 27, 2005. http://artis.imag.fr/Members/Cyril.Soler/VRender VRender is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. VRender is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VRender; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************************** Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.6.2. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #include "Vector2.h" #include "Vector3.h" #include <math.h> #include <algorithm> #ifdef WIN32 # include <windows.h> #endif using namespace vrender; using namespace std; const Vector2 Vector2::inf(FLT_MAX, FLT_MAX); //! Default constructor Vector2::Vector2 () { _xyz[0] = 0.0; _xyz[1] = 0.0; } // ----------------------------------------------------------------------------- //! Default destructor Vector2::~Vector2 () { } // ----------------------------------------------------------------------------- //! Copy constructor Vector2::Vector2 (const Vector2& u) { setXY(u[0],u[1]); } // ----------------------------------------------------------------------------- //! Create a vector from real values Vector2::Vector2 (double x,double y) { setXY(x,y); } Vector2::Vector2 (const Vector3& u) { _xyz[0] = u[0]; _xyz[1] = u[1]; } // ----------------------------------------------------------------------------- //! Inverse Vector2 vrender::operator- (const Vector2& u) { return Vector2(-u[0], -u[1]) ; } // ----------------------------------------------------------------------------- //! Left multiplication by a real value Vector2 operator* (double r,const Vector2& u) { return Vector2(r*u[0], r*u[1]) ; } // ----------------------------------------------------------------------------- //! Norm double Vector2::norm () const { return sqrt( _xyz[0]*_xyz[0] + _xyz[1]*_xyz[1] ); } // ----------------------------------------------------------------------------- //! Square norm (self dot product) double Vector2::squareNorm () const { return _xyz[0]*_xyz[0] + _xyz[1]*_xyz[1] ; } // ----------------------------------------------------------------------------- //! Infinite norm double Vector2::infNorm() const { return max(fabs(_xyz[0]),fabs(_xyz[1])) ; } // ----------------------------------------------------------------------------- //! Out stream override: prints the 3 vector components std::ostream& operator<< (std::ostream& out,const Vector2& u) { out << u[0] << " " << u[1] ; return ( out ); } Vector2 Vector2::mini(const Vector2& v1,const Vector2& v2) { return Vector2(std::min(v1[0],v2[0]),std::min(v1[1],v2[1])) ; } Vector2 Vector2::maxi(const Vector2& v1,const Vector2& v2) { return Vector2(std::max(v1[0],v2[0]),std::max(v1[1],v2[1])) ; }
[ "russell.garwood@manchester.ac.uk" ]
russell.garwood@manchester.ac.uk