blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
0a722a2641053477d2833cb391b78e7414afa2a3
9e34cb0e055dad7d0c1a1182d96a510c39331c63
/sdk/add_on/scripthelper/scripthelper.cpp
2709c4f5db6b3a7f24d33c79777d52ae3515b213
[]
no_license
jacobsologub/angelscript-module
25ea6ae1101abca9cccf8a1a034bd04376e5170b
f476f18282fdd79f074705c547df31b1daf8fb8e
refs/heads/master
2016-09-08T01:39:50.898995
2012-08-30T23:07:03
2012-08-30T23:07:03
5,622,089
3
1
null
null
null
null
UTF-8
C++
false
false
13,181
cpp
#include <string.h> #include "scripthelper.h" #include <string> #include <assert.h> #include <stdio.h> using namespace std; BEGIN_AS_NAMESPACE int CompareRelation(asIScriptEngine *engine, void *lobj, void *robj, int typeId, int &result) { // TODO: If a lot of script objects are going to be compared, e.g. when sorting an array, // then the method id and context should be cached between calls. int retval = -1; asIScriptFunction *func = 0; asIObjectType *ot = engine->GetObjectTypeById(typeId); if( ot ) { // Check if the object type has a compatible opCmp method for( asUINT n = 0; n < ot->GetMethodCount(); n++ ) { asIScriptFunction *f = ot->GetMethodByIndex(n); if( strcmp(f->GetName(), "opCmp") == 0 && f->GetReturnTypeId() == asTYPEID_INT32 && f->GetParamCount() == 1 ) { asDWORD flags; int paramTypeId = f->GetParamTypeId(0, &flags); // The parameter must be an input reference of the same type if( flags != asTM_INREF || typeId != paramTypeId ) break; // Found the method func = f; break; } } } if( func ) { // Call the method asIScriptContext *ctx = engine->CreateContext(); ctx->Prepare(func); ctx->SetObject(lobj); ctx->SetArgAddress(0, robj); int r = ctx->Execute(); if( r == asEXECUTION_FINISHED ) { result = (int)ctx->GetReturnDWord(); // The comparison was successful retval = 0; } ctx->Release(); } return retval; } int CompareEquality(asIScriptEngine *engine, void *lobj, void *robj, int typeId, bool &result) { // TODO: If a lot of script objects are going to be compared, e.g. when searching for an // entry in a set, then the method and context should be cached between calls. int retval = -1; asIScriptFunction *func = 0; asIObjectType *ot = engine->GetObjectTypeById(typeId); if( ot ) { // Check if the object type has a compatible opEquals method for( asUINT n = 0; n < ot->GetMethodCount(); n++ ) { asIScriptFunction *f = ot->GetMethodByIndex(n); if( strcmp(f->GetName(), "opEquals") == 0 && f->GetReturnTypeId() == asTYPEID_BOOL && f->GetParamCount() == 1 ) { asDWORD flags; int paramTypeId = f->GetParamTypeId(0, &flags); // The parameter must be an input reference of the same type if( flags != asTM_INREF || typeId != paramTypeId ) break; // Found the method func = f; break; } } } if( func ) { // Call the method asIScriptContext *ctx = engine->CreateContext(); ctx->Prepare(func); ctx->SetObject(lobj); ctx->SetArgAddress(0, robj); int r = ctx->Execute(); if( r == asEXECUTION_FINISHED ) { result = ctx->GetReturnByte() ? true : false; // The comparison was successful retval = 0; } ctx->Release(); } else { // If the opEquals method doesn't exist, then we try with opCmp instead int relation; retval = CompareRelation(engine, lobj, robj, typeId, relation); if( retval >= 0 ) result = relation == 0 ? true : false; } return retval; } int ExecuteString(asIScriptEngine *engine, const char *code, asIScriptModule *mod, asIScriptContext *ctx) { // Wrap the code in a function so that it can be compiled and executed string funcCode = "void ExecuteString() {\n"; funcCode += code; funcCode += "\n;}"; // If no module was provided, get a dummy from the engine asIScriptModule *execMod = mod ? mod : engine->GetModule("ExecuteString", asGM_ALWAYS_CREATE); // Compile the function that can be executed asIScriptFunction *func = 0; int r = execMod->CompileFunction("ExecuteString", funcCode.c_str(), -1, 0, &func); if( r < 0 ) return r; // If no context was provided, request a new one from the engine asIScriptContext *execCtx = ctx ? ctx : engine->CreateContext(); r = execCtx->Prepare(func); if( r < 0 ) { func->Release(); if( !ctx ) execCtx->Release(); return r; } // Execute the function r = execCtx->Execute(); // Clean up func->Release(); if( !ctx ) execCtx->Release(); return r; } int WriteConfigToFile(asIScriptEngine *engine, const char *filename) { int c, n; FILE *f = 0; #if _MSC_VER >= 1400 // MSVC 8.0 / 2005 fopen_s(&f, filename, "wt"); #else f = fopen(filename, "wt"); #endif if( f == 0 ) return -1; asDWORD currAccessMask = 0; string currNamespace = ""; // Make sure the default array type is expanded to the template form bool expandDefArrayToTempl = engine->GetEngineProperty(asEP_EXPAND_DEF_ARRAY_TO_TMPL) ? true : false; engine->SetEngineProperty(asEP_EXPAND_DEF_ARRAY_TO_TMPL, true); // Write enum types and their values fprintf(f, "// Enums\n"); c = engine->GetEnumCount(); for( n = 0; n < c; n++ ) { int typeId; asDWORD accessMask; const char *nameSpace; const char *enumName = engine->GetEnumByIndex(n, &typeId, &nameSpace, 0, &accessMask); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } if( nameSpace != currNamespace ) { fprintf(f, "namespace %s\n", nameSpace); currNamespace = nameSpace; } fprintf(f, "enum %s\n", enumName); for( int m = 0; m < engine->GetEnumValueCount(typeId); m++ ) { const char *valName; int val; valName = engine->GetEnumValueByIndex(typeId, m, &val); fprintf(f, "enumval %s %s %d\n", enumName, valName, val); } } // Enumerate all types fprintf(f, "\n// Types\n"); c = engine->GetObjectTypeCount(); for( n = 0; n < c; n++ ) { asIObjectType *type = engine->GetObjectTypeByIndex(n); asDWORD accessMask = type->GetAccessMask(); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } const char *nameSpace = type->GetNamespace(); if( nameSpace != currNamespace ) { fprintf(f, "namespace %s\n", nameSpace); currNamespace = nameSpace; } if( type->GetFlags() & asOBJ_SCRIPT_OBJECT ) { // This should only be interfaces assert( type->GetSize() == 0 ); fprintf(f, "intf %s\n", type->GetName()); } else { // Only the type flags are necessary. The application flags are application // specific and doesn't matter to the offline compiler. The object size is also // unnecessary for the offline compiler fprintf(f, "objtype \"%s\" %u\n", engine->GetTypeDeclaration(type->GetTypeId()), (unsigned int)(type->GetFlags() & 0xFF)); } } c = engine->GetTypedefCount(); for( n = 0; n < c; n++ ) { int typeId; asDWORD accessMask; const char *nameSpace; const char *typeDef = engine->GetTypedefByIndex(n, &typeId, &nameSpace, 0, &accessMask); if( nameSpace != currNamespace ) { fprintf(f, "namespace %s\n", nameSpace); currNamespace = nameSpace; } if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } fprintf(f, "typedef %s \"%s\"\n", typeDef, engine->GetTypeDeclaration(typeId)); } c = engine->GetFuncdefCount(); for( n = 0; n < c; n++ ) { asIScriptFunction *funcDef = engine->GetFuncdefByIndex(n); asDWORD accessMask = funcDef->GetAccessMask(); const char *nameSpace = funcDef->GetNamespace(); if( nameSpace != currNamespace ) { fprintf(f, "namespace %s\n", nameSpace); currNamespace = nameSpace; } if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } fprintf(f, "funcdef \"%s\"\n", funcDef->GetDeclaration()); } // Write the object types members fprintf(f, "\n// Type members\n"); c = engine->GetObjectTypeCount(); for( n = 0; n < c; n++ ) { asIObjectType *type = engine->GetObjectTypeByIndex(n); const char *nameSpace = type->GetNamespace(); if( nameSpace != currNamespace ) { fprintf(f, "namespace %s\n", nameSpace); currNamespace = nameSpace; } string typeDecl = engine->GetTypeDeclaration(type->GetTypeId()); if( type->GetFlags() & asOBJ_SCRIPT_OBJECT ) { for( asUINT m = 0; m < type->GetMethodCount(); m++ ) { asIScriptFunction *func = type->GetMethodByIndex(m); asDWORD accessMask = func->GetAccessMask(); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } fprintf(f, "intfmthd %s \"%s\"\n", typeDecl.c_str(), func->GetDeclaration(false)); } } else { asUINT m; for( m = 0; m < type->GetFactoryCount(); m++ ) { asIScriptFunction *func = type->GetFactoryByIndex(m); asDWORD accessMask = func->GetAccessMask(); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } fprintf(f, "objbeh \"%s\" %d \"%s\"\n", typeDecl.c_str(), asBEHAVE_FACTORY, func->GetDeclaration(false)); } for( m = 0; m < type->GetBehaviourCount(); m++ ) { asEBehaviours beh; asIScriptFunction *func = type->GetBehaviourByIndex(m, &beh); fprintf(f, "objbeh \"%s\" %d \"%s\"\n", typeDecl.c_str(), beh, func->GetDeclaration(false)); } for( m = 0; m < type->GetMethodCount(); m++ ) { asIScriptFunction *func = type->GetMethodByIndex(m); asDWORD accessMask = func->GetAccessMask(); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } fprintf(f, "objmthd \"%s\" \"%s\"\n", typeDecl.c_str(), func->GetDeclaration(false)); } for( m = 0; m < type->GetPropertyCount(); m++ ) { asDWORD accessMask; type->GetProperty(m, 0, 0, 0, 0, 0, &accessMask); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } fprintf(f, "objprop \"%s\" \"%s\"\n", typeDecl.c_str(), type->GetPropertyDeclaration(m)); } } } // Write functions fprintf(f, "\n// Functions\n"); c = engine->GetGlobalFunctionCount(); for( n = 0; n < c; n++ ) { asIScriptFunction *func = engine->GetGlobalFunctionByIndex(n); const char *nameSpace = func->GetNamespace(); if( nameSpace != currNamespace ) { fprintf(f, "namespace %s\n", nameSpace); currNamespace = nameSpace; } asDWORD accessMask = func->GetAccessMask(); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } fprintf(f, "func \"%s\"\n", func->GetDeclaration()); } // Write global properties fprintf(f, "\n// Properties\n"); c = engine->GetGlobalPropertyCount(); for( n = 0; n < c; n++ ) { const char *name; int typeId; bool isConst; asDWORD accessMask; const char *nameSpace; engine->GetGlobalPropertyByIndex(n, &name, &nameSpace, &typeId, &isConst, 0, 0, &accessMask); if( accessMask != currAccessMask ) { fprintf(f, "access %X\n", accessMask); currAccessMask = accessMask; } if( nameSpace != currNamespace ) { fprintf(f, "namespace %s\n", nameSpace); currNamespace = nameSpace; } fprintf(f, "prop \"%s%s %s\"\n", isConst ? "const " : "", engine->GetTypeDeclaration(typeId), name); } // Write string factory fprintf(f, "\n// String factory\n"); int typeId = engine->GetStringFactoryReturnTypeId(); if( typeId > 0 ) fprintf(f, "strfactory \"%s\"\n", engine->GetTypeDeclaration(typeId)); // Write default array type fprintf(f, "\n// Default array type\n"); typeId = engine->GetDefaultArrayTypeId(); if( typeId > 0 ) fprintf(f, "defarray \"%s\"\n", engine->GetTypeDeclaration(typeId)); fclose(f); // Restore original settings engine->SetEngineProperty(asEP_EXPAND_DEF_ARRAY_TO_TMPL, expandDefArrayToTempl); return 0; } void PrintException(asIScriptContext *ctx, bool printStack) { if( ctx->GetState() != asEXECUTION_EXCEPTION ) return; asIScriptEngine *engine = ctx->GetEngine(); const asIScriptFunction *function = ctx->GetExceptionFunction(); printf("func: %s\n", function->GetDeclaration()); printf("modl: %s\n", function->GetModuleName()); printf("sect: %s\n", function->GetScriptSectionName()); printf("line: %d\n", ctx->GetExceptionLineNumber()); printf("desc: %s\n", ctx->GetExceptionString()); if( printStack ) { printf("--- call stack ---\n"); for( asUINT n = 1; n < ctx->GetCallstackSize(); n++ ) { function = ctx->GetFunction(n); if( function ) { if( function->GetFuncType() == asFUNC_SCRIPT ) { printf("%s (%d): %s\n", function->GetScriptSectionName(), ctx->GetLineNumber(n), function->GetDeclaration()); } else { // The context is being reused by the application for a nested call printf("{...application...}: %s\n", function->GetDeclaration()); } } else { // The context is being reused by the script engine for a nested call printf("{...script engine...}\n"); } } } } END_AS_NAMESPACE
[ "jacob.sologub@gmail.com" ]
jacob.sologub@gmail.com
6e670a51e73421f82c9c91d467d680721a1297e2
cbce1565c63336b851b726cfb84bea99035c86e2
/dddlll/codechef/DISCHAR/DISCHAR-5275690.cpp
595f0ad382fae7bca87a9edd87c806e8cc374e81
[]
no_license
devanshdalal/CompetitiveProgrammingAlgos
3ad301c19e1b133e72e3b96a10a976a7955c4e25
ab19db4c4fed6f880537a9c45e5ccc50ceed9d97
refs/heads/master
2021-01-17T12:24:58.822428
2016-06-17T04:00:00
2016-06-17T04:00:00
51,207,702
2
0
null
null
null
null
UTF-8
C++
false
false
788
cpp
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> #include<cmath> #include<cstdlib> #include<queue> #include<map> #define DD ios_base::sync_with_stdio(false) #define maxx 10000001 #define eps 0.0000001 typedef long long ll; typedef unsigned long long ul; typedef double d; using namespace std; const ll mod = 1000000007; int main(){ int t,i,j,k,l,n,m,p,q; scanf("%d",&t); char a[100001]; while(t--){ bool count[200]; for (i = 97; i < 123; ++i) { count[i]=0; } scanf("%s",a); l=strlen(a); for ( i = 0; i <l; ++i) { count[a[i]]=1; } int ans=0; for (i = 97; i < 123; ++i) { ans+=count[i]; } printf("%d\n", ans); } return 0; }
[ "mr.devanshdalal@gmail.com" ]
mr.devanshdalal@gmail.com
4c440df3118ced8a612246756b6163567e9aef0f
7c63a96fad4257f4959ffeba0868059fc96566fb
/cpp/qt/m_shlee-qt_5_3/ch_08-buttons_checkboxes_radiobuttons/05-groupbox_using/buttons.cpp
34107157331ab7faa930d60a7d810f5a34c39fc1
[ "MIT" ]
permissive
ordinary-developer/education
b426148f5690f48e0ed4853adfc3740bd038b72c
526e5cf86f90eab68063bb7c75744226f2c54b8d
refs/heads/master
2023-08-31T14:42:37.237690
2023-08-30T18:15:18
2023-08-30T18:15:18
91,232,306
8
0
null
null
null
null
UTF-8
C++
false
false
1,788
cpp
#include "buttons.hpp" #include <QtWidgets> Buttons::Buttons(QWidget* parentWidget) : QGroupBox{ "QGroupBox", parentWidget } { resize(100, 150); setCheckable(true); setChecked(true); m_redRadioButton = new QRadioButton{"&Red"}; m_greenRadioButton = new QRadioButton{"&Green"}; m_blueRadioButton = new QRadioButton{"&Blue"}; m_greenRadioButton->setChecked(true); connect(m_redRadioButton, &QRadioButton::clicked, this, &Buttons::slotButtonClicked); connect(m_greenRadioButton, &QRadioButton::clicked, this, &Buttons::slotButtonClicked); connect(m_blueRadioButton, &QRadioButton::clicked, this, &Buttons::slotButtonClicked); m_checkBox = new QCheckBox{"&Light"}; m_checkBox->setChecked(true); connect(m_checkBox, &QCheckBox::clicked, this, &Buttons::slotButtonClicked); QPushButton* button{ new QPushButton{"&Exit"} }; connect(button, &QPushButton::clicked, qApp, &QApplication::quit); QVBoxLayout* boxLayout{ new QVBoxLayout{} }; boxLayout->addWidget(m_redRadioButton); boxLayout->addWidget(m_greenRadioButton); boxLayout->addWidget(m_blueRadioButton); boxLayout->addWidget(m_checkBox); boxLayout->addWidget(button); setLayout(boxLayout); slotButtonClicked(); } void Buttons::slotButtonClicked() { QPalette palette{}; int light{ m_checkBox->isChecked() ? 150 : 80 }; if (m_redRadioButton->isChecked()) palette.setColor(backgroundRole(), QColor(Qt::red).light(light)); else if(m_greenRadioButton->isChecked()) palette.setColor(backgroundRole(), QColor(Qt::green).light(light)); else palette.setColor(backgroundRole(), QColor(Qt::blue).light(light)); setPalette(palette); }
[ "merely.ordinary.developer@gmail.com" ]
merely.ordinary.developer@gmail.com
f11db64bca2856f39ceb259d01218c1f24e325f7
8a4f1bc7eef8879ccfc5efb5963c088aad8761f7
/zengine/zengine/config_file_xml_handler.cc
745980d72c0e76c658fcdaf37377e6cf34f56504
[ "Apache-2.0" ]
permissive
live0717/zengine
dad07be0e0f8b634b80c3d6681b8a11591d53f5c
11619d5923f4a52dee8dc252f0fe64a4d882678c
refs/heads/master
2020-12-11T07:45:10.834924
2014-01-06T14:46:25
2014-01-06T14:46:25
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,848
cc
// Copyright (C) 2012 by wubenqi // Distributable under the terms of either the Apache License (Version 2.0) or // the GNU Lesser General Public License, as specified in the COPYING file. // // By: wubenqi<wubenqi@gmail.com> // #include "zengine/config_file_xml_handler.h" #include "base/string_util.h" #include "base2/xml/xml_attributes.h" namespace { const std::string kConfigXMLIniElement("XMLIni"); const std::string kConfigSectionElement("Section"); const std::string kConfigItemElement("Item"); const std::string kConfigNameAttribute("name"); const ConfigFile::KeyValuePairList kEmptyKeyValusePairList; } ConfigFileXmlHandler::ConfigFileXmlHandler(ConfigFile::SectionMap& config_map) : config_map_(config_map) { } bool ConfigFileXmlHandler::ElementStart(const std::string& element, const base::XMLAttributes& attributes) { // std::string t = kConfigNameAttribute; current_element_ = element; std::string* attr_val = NULL; if (element==kConfigXMLIniElement) { // ¿ªÊ¼ config_map_.clear(); } else if (element==kConfigSectionElement) { if (!attributes.GetValue(kConfigNameAttribute, &attr_val)) { return false; } //section_ = *attr_val; std::pair<ConfigFile::SectionMap::iterator, bool> result = config_map_.insert(std::make_pair(*attr_val, kEmptyKeyValusePairList)); if (result.second) { } else { LOG(ERROR) << "ConfigFileXmlHandler::ElementStart - config_map_.insert() error while parsing config file: '" << element << "' is unknown."; } current_it_ = result.first; } else if (element==kConfigItemElement) { if (!attributes.GetValue(kConfigNameAttribute, &attr_val)) { return false; } current_it_->second.push_back(std::make_pair(*attr_val, EmptyString())); } else { LOG(ERROR) << "ConfigFileXmlHandler::ElementStart - Unexpected data was found while parsing config file: '" << element << "' is unknown."; return false; } return true; } bool ConfigFileXmlHandler::ElementEnd(const std::string& element) { if (element==kConfigXMLIniElement) { } else if (element==kConfigSectionElement) { //section_.clear(); } else if (element==kConfigItemElement) { //key_.clear(); //value_.clear(); } else { LOG(ERROR) << "ConfigFileXmlHandler::ElementStart - Unexpected data was found while parsing config file: '" << element << "' is unknown."; return false; } return true; } bool ConfigFileXmlHandler::Text(const std::string& text) { if (current_element_==kConfigItemElement) { TrimWhitespaceASCII(text, TRIM_ALL, &(current_it_->second.rbegin()->second)); } else { LOG(ERROR) << "ConfigFileXmlHandler::ElementStart - Unexpected data was found while parsing config file: '" << current_element_ << "' is unknown."; return false; } return true; }
[ "wubenqi@gmail.com" ]
wubenqi@gmail.com
ff117dd2e6eaf9bb4bfe6cfddc657ac34b964acc
03f7da7cf46a53a329cd27163fb4669f1c960234
/geographic/image-browser/src/gui/Main_Window.cpp
920a9b2b3490db65a1edc4edbe4d75e806f2acb1
[]
no_license
marvins/Code_Sandbox
4529208dd01f6e6ff1049056ea0f22e0732e295b
8bc17cb7c282f3f1a01722e97387214c21d4d505
refs/heads/master
2023-05-13T14:29:55.751479
2023-05-05T20:41:47
2023-05-05T20:41:47
3,795,461
10
5
null
null
null
null
UTF-8
C++
false
false
1,378
cpp
/** * @file Main_Window.cpp * @author Marvin Smith * @date 3/2/2018 */ #include "Main_Window.hpp" // Qt Libraries #include <QSplitter> // ArcGIS Libraries #include <Map.h> #include <MapGraphicsView.h> using namespace Esri::ArcGISRuntime; /********************************/ /* Constructor */ /********************************/ Main_Window::Main_Window( const Geo_Options& options ) : m_class_name("Main_Window"), m_options(options) { Initialize_GUI(); } /****************************************/ /* Initialize the GUI */ /****************************************/ void Main_Window::Initialize_GUI() { // Build the Central Widget m_main_widget = new QSplitter(this); // Build the Asset-Manager m_asset_panel = new Asset_Panel(m_options); m_main_widget->addWidget(m_asset_panel); // Add the ArcGIS Map Initialize_Map(); setCentralWidget(m_main_widget); } /****************************************/ /* Initialize the Map */ /****************************************/ void Main_Window::Initialize_Map() { // Create a map using the Imagery with labels basemap m_map = new Map(Basemap::imageryWithLabels(this), this); // Create a map view, and pass in the map m_mapView = new MapGraphicsView(m_map, this); m_main_widget->addWidget(m_mapView); }
[ "marvin_smith1@me.com" ]
marvin_smith1@me.com
6beb7ab5d1e35984ece1ddb06ad160141ddfd40c
0ef4f71c8ff2f233945ee4effdba893fed3b8fad
/misc_microsoft_gamedev_source_code/misc_microsoft_gamedev_source_code/xgame/trigger.h
9ecaad79eec02da5363c62161e49586accb475e4
[]
no_license
sgzwiz/misc_microsoft_gamedev_source_code
1f482b2259f413241392832effcbc64c4c3d79ca
39c200a1642102b484736b51892033cc575b341a
refs/heads/master
2022-12-22T11:03:53.930024
2020-09-28T20:39:56
2020-09-28T20:39:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,308
h
//============================================================================== // trigger.h // // Copyright (c) 2006 Ensemble Studios //============================================================================== #pragma once // xsystem #include "xmlreader.h" #include "gamefilemacros.h" // forward declarations class BTrigger; class BTriggerCondition; class BTriggerEffect; class BTriggerScript; typedef uint BTriggerID; __declspec(selectany) extern const BTriggerID cInvalidTriggerID = 0xFFFFFFFF; //============================================================================== // class BTrigger //============================================================================== class BTrigger : public IPoolable { public: #ifndef BUILD_FINAL enum { cPerformanceWarningThreshold = 1000, cInfiniteLoopWarningThreshold = 50000, }; const BSimString& getName() const { return(mName); } #endif BTrigger(){} ~BTrigger(){} virtual void onAcquire(); virtual void onRelease(); DECLARE_FREELIST(BTrigger, 6); bool loadFromXML(BXMLNode node); bool timeToEvaluate(DWORD currentUpdateTime); void updateAsyncConditions(); bool evaluateConditions(DWORD currentUpdateTime); void fireEffects(bool onTrue); void setAsyncConditionState(long conditionID, bool state); void resetEvaluateCount() { mEvaluateCount = 0; } bool hasEvaluationsRemaining(); // Accessors bool isStartActive() const { return (mbStartActive); } bool isConditional() const { return (mbConditional); } BTriggerID getID() const { return (mID); } void setID(BTriggerID v) { mID = v; } BTriggerID getEditorID() const { return (mEditorID); } DWORD getActivatedTime() const { return (mActivatedTime); } DWORD getEvaluateTime() const { return (mNextEvaluateTime); } void onActivated(); void setParentTriggerScript(BTriggerScript* pParentScript) { mpParentTriggerScript = pParentScript; } BTriggerScript* getParentTriggerScript() { return (mpParentTriggerScript); } uint getNumberConditions() const { return mConditions.size(); } BTriggerCondition* getConditionByIndex(uint index) { return mConditions[index]; } GFDECLAREVERSION(); bool save(BStream* pStream, int saveType) const; bool load(BStream* pStream, int saveType); protected: // 52 bytes total #ifndef BUILD_FINAL BSimString mName; long mGroupID; #endif BSmallDynamicSimArray<BTriggerCondition*> mConditions; // 8 bytes BSmallDynamicSimArray<BTriggerEffect*> mEffectsOnTrue; // 8 bytes BSmallDynamicSimArray<BTriggerEffect*> mEffectsOnFalse; // 8 bytes BTriggerID mID; // 4 bytes - The unique ID of the trigger (so we can compare ID's not names.) BTriggerID mEditorID; // 4 bytes - Editor side id BTriggerScript* mpParentTriggerScript; // 4 bytes - The parent trigger script. DWORD mActivatedTime; // 4 bytes - The game time this trigger became active DWORD mNextEvaluateTime; // 4 bytes - How long has it been since the last condition evaluation. DWORD mEvaluateFrequency; // 4 bytes - How long do we wait between evaluation times. DWORD mEvaluateCount; // 4 bytes - How many times has the trigger been updated THIS UPDATE frame. (Reset to 0 each update.) DWORD mEvaluateLimit; // 4 bytes - How many times can the trigger be evaluated per update. (0 means unlimited) bool mbStartActive : 1; // 1 byte - Does this trigger start active? bool mbConditional : 1; // Is this trigger a conditional? bool mbOrConditions : 1; // Do we OR the conditions on this trigger? };
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
2744ff49df5153129582304b8ad68d76db398000
22964c1b05c503fc88d26b5e1cfa558308e7342f
/string/first_none_repeat_charactor.cpp
7d7f542bae3bb75ec1ead2cd30b23c6e114764c5
[]
no_license
oceanwavechina/algorithm
8f67088ac80b236d076333c63e3161f7bf0fff11
d3fae2f5ed1a636eca1f35cdc9a5703238957efd
refs/heads/master
2021-11-29T00:21:25.798080
2021-09-22T09:29:42
2021-09-22T09:29:42
180,058,662
0
0
null
null
null
null
UTF-8
C++
false
false
1,995
cpp
/* * first_none_repeat_charactor.cpp * * Created on: Jul 12, 2021 * Author: liuyanan */ #include <iostream> #include <string> using namespace std; /* 题目: 在字符串中找出第一个只出现一次的字符。 比如,输入 "abaccdeff", 则输出 'b' 玩法是这样: 创建一个 hash_table: key是可能出现的字符(这里设置为256),value是key出现的次数 然后遍历两次,第一次记录每个字符出现的次数,第二次查找出现1次的字符 需要注意的是,两次都是遍历给定的字符串,然后根据字符操作查找 hash_table */ char first_none_repeat_charactor(const char* p_str) { if(! p_str) { return '\0'; } // 先初始化 hash 表 const int table_size = 256; unsigned hash_table[table_size]; for(unsigned i=0; i<table_size; ++i) { hash_table[i] = 0; } // 把字符串放到hash表中 const char* p_cursor = p_str; // // 这里也算是一个考点吧, 为什么不能吧 const 放在 p_cursor 前边 // const 直接修饰谁,那谁就是不可变的, // 1. p_cursor 是指针,紧挨着放到它前边那p_cursor (即 char* const p_cursor) 指针本身就是不可修改的 // 2. const 紧挨着放到 *p_cursor 前边 (即 const char *p_cursor),那 *p_cursor, 也就是指针指向的数据是不可修改的 // // char* const p_cursor = p_str; while(*p_cursor != '\0') { hash_table[*p_cursor] += 1; ++p_cursor; } // // 找到第一个元素 // 注意,我们是在遍历一次 源字符串, 而不是遍历 hash table // 因为题目的一个要点是要找 **第一次** 出现的元素 // p_cursor = p_str; while(*p_cursor != '\0') { if(hash_table[*p_cursor] == 1) { return *p_cursor; } ++p_cursor; } return '\0'; } int main(int argc, char **argv) { const char* p_str = "zbaccdeff"; cout << "target charactor of [" << p_str << "], is: " << first_none_repeat_charactor(p_str) << endl; return 0; }
[ "" ]
394c21a225fe64e2949cb688620a1073a595d967
045346d5df7a707712e9f93e4c18186c34dae18d
/echo/multiFork/server.cpp
6916a5ab1fb8ba57a0271b3f3e451ed59754f5ba
[]
no_license
chenbk85/network-programming
fb1cb085e7215c586f7c9bc7428ba2d2cbe84ce1
3c12edc892003d731ef64224a47051c2009f8fb7
refs/heads/master
2021-01-15T07:56:56.905856
2013-04-13T13:13:49
2013-04-13T13:13:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,083
cpp
/*Copyright 2012 NDSL. All Rights Reserved. * ===================================================================================== * Filename: server.cpp * Description: * Version: 1.0 * Created: 12/20/2012 03:40:42 PM * Author: dongyuchi (dongyuchi), dongyuchi@gmail.com * Company: UESTC.NDSL * ===================================================================================== */ #include<iostream> #include<time.h> #include<sys/time.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<string.h> #include<stdlib.h> #include<stdio.h> #include<errno.h> #include<unistd.h> #include<signal.h> #include<sys/wait.h> #define BufferLength 1024 int main(int argc, char* argv[]) { int connfd, listenfd; int ret; struct sockaddr_in servaddr; pid_t pid; char buff[BufferLength]; if(argc < 2) { std::cerr<<"usage: "<<argv[0]<<" port"<<std::endl; return -1; } // create new socket listenfd = socket(AF_INET, SOCK_STREAM, 0); // handle socket error if(listenfd < 0) { perror("socket error!"); return -1; } // configure struct 'servaddr' servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); // bind struct 'servaddr' to server socket ret = bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); if(ret < 0) { perror("bind error!"); return -1; } // tell kernel to listen at server socket ret = listen(listenfd, 64); if(ret < 0) { perror("listen error!"); return -1; } // server is listening... std::cout<<"server is listening ..."<<std::endl; // step into loop to handle request while(true) { // accept a request connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); if(connfd < 0) { // if interrupt occurs if(errno == EINTR) { continue; } perror("accept error!"); break; } // fork new child process to handle request if((pid = fork()) == 0) { // if this is child process close(listenfd); while(true) { bzero(buff, sizeof(buff)); ret = read(connfd, buff, sizeof(buff)); if( ret <= 0) { if( ret == 0) { close(connfd); break; } if( errno == EINTR) { continue; } close(connfd); perror("read error!"); break; } ret = write(connfd, buff, strlen(buff)); if(ret < 0 ) { perror("write error!"); break; } } exit(1); } // end child process // this is in parent process close(connfd); } return 0; }
[ "dongyuchi@gmail.com" ]
dongyuchi@gmail.com
550586e8f707c787fb7307fe19cd90adecd09016
ed1e63c58302f6ed7e5dfe4fa125b2abecf64ab3
/1_23/pending/disjoint_sets.hpp
7e329398f293e4938248aa0786182d4bd764c896
[]
no_license
codemonkeyhe/boost
21f1f9531d5318b3e75ccdae5eb724aaf2870e28
1888a1af58d82ea151a8d29805fad9ee6f5d8660
refs/heads/master
2020-03-28T19:44:13.901950
2018-09-16T14:48:19
2018-09-16T14:48:19
149,004,613
0
0
null
null
null
null
UTF-8
C++
false
false
7,711
hpp
// //======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // This file is part of the Generic Graph Component Library // // You should have received a copy of the License Agreement for the // Generic Graph Component Library along with the software; see the // file LICENSE. If not, contact Office of Research, University of Notre // Dame, Notre Dame, IN 46556. // // Permission to modify the code and to distribute modified code is // granted, provided the text of this NOTICE is retained, a notice that // the code was modified is included with the above COPYRIGHT NOTICE and // with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE // file is distributed with the modified code. // // LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. // By way of example, but not limitation, Licensor MAKES NO // REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY // PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS // OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS // OR OTHER RIGHTS. //======================================================================= // #ifndef BOOST_DISJOINT_SETS_HPP #define BOOST_DISJOINT_SETS_HPP #include <boost/graph/properties.hpp> #include <boost/pending/detail/disjoint_sets.hpp> namespace boost { struct find_with_path_halving { template <class ParentPA, class Vertex> Vertex operator()(ParentPA p, Vertex v) { return detail::find_representative_with_path_halving(pc, v); } }; struct find_with_full_path_compression { template <class ParentPA, class Vertex> Vertex operator()(ParentPA p, Vertex v){ return detail::find_representative_with_full_compression(p, v); } }; // This is a generalized functor to provide disjoint sets operations // with "union by rank" and "path compression". A disjoint-set data // structure maintains a collection S={S1, S2, ..., Sk} of disjoint // sets. Each set is identified by a representative, which is some // member of of the set. Sets are represented by rooted trees. Two // heuristics: "union by rank" and "path compression" are used to // speed up the operations. // Disjoint Set requires two vertex properties for internal use. A // RankPA and a ParentPA. The RankPA must map Vertex to some Integral type // (preferably the size_type associated with Vertex). The ParentPA // must map Vertex to Vertex. template <class RankPA, class ParentPA, class FindCompress = find_with_full_path_compression > class disjoint_sets { typedef disjoint_sets self; inline disjoint_sets() {} public: inline disjoint_sets(RankPA r, ParentPA p) : rank(r), parent(p) {} inline disjoint_sets(const self& c) : rank(c.rank), parent(c.parent) {} // Make Set -- Create a singleton set containing vertex x template <class Element> inline void make_set(Element x) { put(parent, x, x); typedef typename property_traits<RankPA>::value_type R; put(rank, x, R()); } // Link - union the two sets represented by vertex x and y template <class Element> inline void link(Element x, Element y) { detail::link_sets(parent, rank, x, y, rep); } // Union-Set - union the two sets containing vertex x and y template <class Element> inline void union_set(Element x, Element y) { link(find_set(x), find_set(y)); } // Find-Set - returns the Element representative of the set // containing Element x and applies path compression. template <class Element> inline Element find_set(Element x) { return rep(parent, x); } template <class ElementIterator> inline std::size_t count_sets(ElementIterator first, ElementIterator last) { std::size_t count = 0; for ( ; first != last; ++first) if (get(parent, *first) == *first) ++count; return count; } template <class ElementIterator> inline void normalize_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::normalize_node(parent, *first); } template <class ElementIterator> inline void compress_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::find_representative_with_full_compression(parent, *first); } protected: RankPA rank; ParentPA parent; FindCompress rep; }; template <class ID = identity_property_map, class InverseID = identity_property_map, class FindCompress = find_with_full_path_compression > class disjoint_sets_with_storage { typedef typename property_traits<ID>::value_type Index; typedef std::vector<Index> ParentContainer; typedef std::vector<unsigned char> RankContainer; public: typedef typename ParentContainer::size_type size_type; disjoint_sets_with_storage(size_type n = 0, ID id_ = ID(), InverseID inv = InverseID()) : id(id_), id_to_vertex(inv), rank(n, 0), parent(n) { for (Index i = 0; i < n; ++i) parent[i] = i; } // note this is not normally needed template <class Element> inline void make_set(Element x) { parent[x] = x; rank[x] = 0; } template <class Element> inline void link(Element x, Element y) { extend_sets(x,y); detail::link_sets(&parent[0], &rank[0], get(id,x), get(id,y), rep); } template <class Element> inline void union_set(Element x, Element y) { Element rx = find_set(x); Element ry = find_set(y); link(rx, ry); } template <class Element> inline Element find_set(Element x) { return id_to_vertex[rep(&parent[0], get(id,x))]; } template <class ElementIterator> inline std::size_t count_sets(ElementIterator first, ElementIterator last) { std::size_t count = 0; for ( ; first != last; ++first) if (parent[*first] == *first) ++count; return count; } template <class ElementIterator> inline void normalize_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::normalize_node(&parent[0], *first); } template <class ElementIterator> inline void compress_sets(ElementIterator first, ElementIterator last) { for (; first != last; ++first) detail::find_representative_with_full_compression(&parent[0], *first); } const ParentContainer& parents() { return parent; } protected: template <class Element> inline void extend_sets(Element x, Element y) { Index needed = get(id,x) > get(id,y) ? get(id,x) + 1 : get(id,y) + 1; if (needed > parent.size()) { rank.insert(rank.end(), needed - rank.size(), 0); for (Index k = parent.size(); k < needed; ++k) parent.push_back(k); } } ID id; InverseID id_to_vertex; RankContainer rank; ParentContainer parent; FindCompress rep; }; } // namespace boost #endif // BOOST_DISJOINT_SETS_HPP
[ "328679181@qq.com" ]
328679181@qq.com
9833b59369e2b5402a0849d17828f09b060924f3
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin_custom.cc
1ee5aa3994a272d8d3615672a60dfd8df591f5ff
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
621
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 "third_party/blink/renderer/core/css/properties/longhands/stroke_linejoin.h" namespace blink { namespace CSSLonghand { const CSSValue* StrokeLinejoin::CSSValueFromComputedStyleInternal( const ComputedStyle& style, const SVGComputedStyle& svg_style, const LayoutObject*, Node*, bool allow_visited_style) const { return CSSIdentifierValue::Create(svg_style.JoinStyle()); } } // namespace CSSLonghand } // namespace blink
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
ea00d3b36139dbaee412f05ccb42743c6d5d792d
6ce125bb07f84fd28e6d1c1dcd791e9855a5cc77
/External/Quiver/Source/Quiver/Quiver/Animation/AnimationData.h
f104096d443e434210921bd34b1f8478287e6d4d
[ "MIT" ]
permissive
rachelnertia/Quarrel
1c416b8133dd2ea4b5d48df7ca66f110049247cc
69616179fc71305757549c7fcaccc22707a91ba4
refs/heads/master
2020-05-30T15:34:18.428644
2019-06-02T08:42:57
2019-06-02T08:42:57
189,823,291
0
2
null
null
null
null
UTF-8
C++
false
false
2,346
h
#pragma once #include <chrono> #include <json.hpp> #include <optional.hpp> #include "Quiver/Animation/AnimationId.h" #include "Quiver/Animation/Rect.h" #include "Quiver/Animation/TimeUnit.h" namespace qvr { namespace Animation { struct Frame; } class AnimationData { public: friend AnimationId GenerateAnimationId(const AnimationData& animation); AnimationData() = default; static std::experimental::optional<AnimationData> FromJson(const nlohmann::json& j); static std::experimental::optional<AnimationData> FromJsonFile(const std::string filename); nlohmann::json ToJson() const; void Clear(); bool IsValid() const; int GetFrameCount() const { return mFrameTimes.size(); } int GetRectCount() const { return mFrameRects.size(); } int GetAltViewsPerFrame() const { return mAltViewsPerFrame; } std::experimental::optional<Animation::Frame> GetFrame(const int frameIndex) const; std::experimental::optional<Animation::Rect> GetRect(const int frameIndex, const int viewIndex = 0) const; std::experimental::optional<Animation::TimeUnit> GetTime(const int frameIndex) const; std::vector<Animation::TimeUnit> GetTimes() const; std::vector<Animation::Rect> GetRects() const; bool AddFrame(const Animation::Frame& frame); bool InsertFrame( const Animation::Frame& frame, const int frameIndex); bool AddFrames(const std::vector<Animation::Frame>& frames); bool RemoveFrame(const int index); bool SetFrame(const int index, const Animation::Frame& frame); bool SetFrameTime(const int index, const Animation::TimeUnit time); bool SetFrameRect(const int frameIndex, const int viewIndex, const Animation::Rect& rect); bool SwapFrames(const int index1, const int index2); private: std::vector<Animation::Rect> mFrameRects; std::vector<Animation::TimeUnit> mFrameTimes; unsigned mAltViewsPerFrame = 0; }; namespace Animation { struct Frame { TimeUnit mTime; Rect mBaseRect; std::vector<Rect> mAltRects; }; inline bool operator==(const Frame& lhs, const Frame& rhs) { if (lhs.mTime != rhs.mTime) return false; if (lhs.mBaseRect != rhs.mBaseRect) return false; if (lhs.mAltRects != rhs.mAltRects) return false; return true; } inline bool operator!=(const Frame& lhs, const Frame& rhs) { return !(lhs == rhs); } } }
[ "nershly@gmail.com" ]
nershly@gmail.com
4dfc8af381f0aa852035c7c97bc06151b5ec6e38
dab16faeec5a1882c3aa65d823fa669e5e832111
/Wintruder/Observers.cpp
d9910c6a7f3e37b9907ab0b78cdec8c6852ed7f1
[]
no_license
paul-hc/DevTools
adaa6b20bedfb941a6114c70b97c2776c543946c
84be93c23d8d2a272b6d5d09c4129a6cd87a2aa4
refs/heads/master
2023-08-31T18:17:21.143856
2023-08-31T17:51:12
2023-08-31T17:51:12
116,268,930
0
1
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include "stdafx.h" #include "Observers.h" #include "AppService.h" #ifdef _DEBUG #define new DEBUG_NEW #endif void IWndObserver::OutputTargetWnd( void ) { OnTargetWndChanged( app::GetTargetWnd() ); }
[ "phc.2nd@gmail.com" ]
phc.2nd@gmail.com
5a301de474a368e9bd6c53c6e0a976a6a762c26a
0c7e20a002108d636517b2f0cde6de9019fdf8c4
/Sources/Elastos/External/conscrypt/src/org/conscrypt/CDefaultSSLContextImpl.cpp
0cda3d4a784aeb88e80cd9391523a5a3106894a2
[ "Apache-2.0" ]
permissive
kernal88/Elastos5
022774d8c42aea597e6f8ee14e80e8e31758f950
871044110de52fcccfbd6fd0d9c24feefeb6dea0
refs/heads/master
2021-01-12T15:23:52.242654
2016-10-24T08:20:15
2016-10-24T08:20:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,185
cpp
#include "org/conscrypt/CDefaultSSLContextImpl.h" using Elastos::Security::CKeyStoreHelper; using Elastos::Security::IKeyStore; using Elastos::Security::IKeyStoreHelper; using Elastos::Core::CSystem; using Elastos::Core::ISystem; using Elastos::IO::CBufferedInputStream; using Elastos::IO::ICloseable; using Elastos::IO::CFileInputStream; using Elastos::IO::IBufferedInputStream; using Elastos::IO::IFileInputStream; using Elastos::IO::IInputStream; using Elastosx::Net::Ssl::CKeyManagerFactoryHelper; using Elastosx::Net::Ssl::CTrustManagerFactoryHelper; using Elastosx::Net::Ssl::IKeyManagerFactory; using Elastosx::Net::Ssl::IKeyManagerFactoryHelper; using Elastosx::Net::Ssl::ITrustManagerFactory; using Elastosx::Net::Ssl::ITrustManagerFactoryHelper; namespace Org { namespace Conscrypt { AutoPtr<ArrayOf<IKeyManager*> > CDefaultSSLContextImpl::KEY_MANAGERS; AutoPtr<ArrayOf<ITrustManager*> > CDefaultSSLContextImpl::TRUST_MANAGERS; CAR_OBJECT_IMPL(CDefaultSSLContextImpl) CAR_INTERFACE_IMPL(CDefaultSSLContextImpl, OpenSSLContextImpl, IDefaultSSLContextImpl) ECode CDefaultSSLContextImpl::constructor() { return OpenSSLContextImpl::constructor(NULL); } ECode CDefaultSSLContextImpl::GetKeyManagers( /* [out, callee] */ ArrayOf<IKeyManager*>** result) { VALIDATE_NOT_NULL(result) if (KEY_MANAGERS != NULL) { *result = KEY_MANAGERS; REFCOUNT_ADD(*result) return NOERROR; } // find KeyStore, KeyManagers AutoPtr<ISystem> system; CSystem::AcquireSingleton((ISystem**)&system); String keystore; system->GetProperty(String("javax.net.ssl.keyStore"), &keystore); if (keystore == NULL) { *result = NULL; return NOERROR; } String keystorepwd; system->GetProperty(String("javax.net.ssl.keyStorePassword"), &keystorepwd); AutoPtr<ArrayOf<Char32> > pwd = (keystorepwd == NULL) ? NULL : keystorepwd.GetChars(); AutoPtr<IKeyStoreHelper> ksHelper; CKeyStoreHelper::AcquireSingleton((IKeyStoreHelper**)&ksHelper); String type; ksHelper->GetDefaultType(&type); AutoPtr<IKeyStore> ks; ksHelper->GetInstance(type, (IKeyStore**)&ks); AutoPtr<IInputStream> is; // try { AutoPtr<IFileInputStream> fis; CFileInputStream::New(keystore, (IFileInputStream**)&fis); CBufferedInputStream::New(IInputStream::Probe(fis), (IBufferedInputStream**)&is); ks->Load(is, pwd); // } finally { if (is != NULL) { ICloseable::Probe(is)->Close(); } // } AutoPtr<IKeyManagerFactoryHelper> kmfHelper; CKeyManagerFactoryHelper::AcquireSingleton((IKeyManagerFactoryHelper**)&kmfHelper); String kmfAlg; kmfHelper->GetDefaultAlgorithm(&kmfAlg); AutoPtr<IKeyManagerFactory> kmf; kmfHelper->GetInstance(kmfAlg, (IKeyManagerFactory**)&kmf); kmf->Init(ks, pwd); kmf->GetKeyManagers((ArrayOf<IKeyManager*>**)&KEY_MANAGERS); *result = KEY_MANAGERS; REFCOUNT_ADD(*result) return NOERROR; } ECode CDefaultSSLContextImpl::GetTrustManagers( /* [out, callee] */ ArrayOf<ITrustManager*>** result) { VALIDATE_NOT_NULL(result) if (TRUST_MANAGERS != NULL) { *result = TRUST_MANAGERS; REFCOUNT_ADD(*result) return NOERROR; } // find TrustStore, TrustManagers AutoPtr<ISystem> system; CSystem::AcquireSingleton((ISystem**)&system); String keystore; system->GetProperty(String("javax.net.ssl.trustStore"), &keystore); if (keystore == NULL) { *result = NULL; return NOERROR; } String keystorepwd; system->GetProperty(String("javax.net.ssl.trustStorePassword"), &keystorepwd); AutoPtr<ArrayOf<Char32> > pwd = (keystorepwd == NULL) ? NULL : keystorepwd.GetChars(); // TODO Defaults: jssecacerts; cacerts AutoPtr<IKeyStoreHelper> ksHelper; CKeyStoreHelper::AcquireSingleton((IKeyStoreHelper**)&ksHelper); String type; ksHelper->GetDefaultType(&type); AutoPtr<IKeyStore> ks; ksHelper->GetInstance(type, (IKeyStore**)&ks); AutoPtr<IInputStream> is; // try { AutoPtr<IFileInputStream> fis; CFileInputStream::New(keystore, (IFileInputStream**)&fis); CBufferedInputStream::New(IInputStream::Probe(fis), (IBufferedInputStream**)&is); ks->Load(is, pwd); // } finally { if (is != NULL) { ICloseable::Probe(is)->Close(); } // } AutoPtr<ITrustManagerFactoryHelper> tmfHelper; CTrustManagerFactoryHelper::AcquireSingleton((ITrustManagerFactoryHelper**)&tmfHelper); String tmfAlg; tmfHelper->GetDefaultAlgorithm(&tmfAlg); AutoPtr<ITrustManagerFactory> tmf; tmfHelper->GetInstance(tmfAlg, (ITrustManagerFactory**)&tmf); tmf->Init(ks); tmf->GetTrustManagers((ArrayOf<ITrustManager*>**)&TRUST_MANAGERS); *result = TRUST_MANAGERS; REFCOUNT_ADD(*result) return NOERROR; } ECode CDefaultSSLContextImpl::EngineInit( /* [in] */ ArrayOf<IKeyManager*>* km, /* [in] */ ArrayOf<ITrustManager*>* tm, /* [in] */ ISecureRandom* sr) { // throw new KeyManagementException("Do not init() the default SSLContext "); return E_KEY_MANAGEMENT_EXCEPTION; } } // namespace Conscrypt } // namespace Org
[ "ma.li@kortide.com" ]
ma.li@kortide.com
68134e70d2276caedb7b2dbf589537c1815b7bf8
c459b460a5f2f73d3047ac486eed5ffb40f71581
/geometry_library/geometry_library/include/Vec2.h
95a000aec97c5f80b30bf3629381bcbbe2149688
[]
no_license
uddipan/Geometry_library
29c3ca99a440124b5334f53251bb48a8dfdcb714
e4578d7650e246113943e376d1d915928c00601a
refs/heads/master
2021-01-20T00:08:05.568429
2017-05-01T15:13:21
2017-05-01T15:13:21
89,082,854
0
0
null
null
null
null
UTF-8
C++
false
false
2,626
h
/*************************************************************************** * Vec2.h * * * * Vec2 is a trivial encapsulation of 2D floating-point coordinates. * * It has all of the obvious operators defined as inline functions. * * * * History: * * 04/01/2003 Initial coding. * * Originally designed by Prov Jim Arvo at UC Irvine * ***************************************************************************/ #ifndef __VEC2_INCLUDED__ #define __VEC2_INCLUDED__ struct Vec2 { inline Vec2() { x = 0; y = 0; } inline Vec2(double a, double b) { x = a; y = b; } double x; double y; }; inline double LengthSquared(const Vec2 &A) { return A.x * A.x + A.y * A.y; } inline double Length(const Vec2 &A) { return sqrt(LengthSquared(A)); } inline Vec2 operator+(const Vec2 &A, const Vec2 &B) { return Vec2(A.x + B.x, A.y + B.y); } inline Vec2 operator-(const Vec2 &A, const Vec2 &B) { return Vec2(A.x - B.x, A.y - B.y); } inline Vec2 operator-(const Vec2 &A) // Unary minus. { return Vec2(-A.x, -A.y); } inline Vec2 operator*(double a, const Vec2 &A) { return Vec2(a * A.x, a * A.y); } inline Vec2 operator*(const Vec2 &A, double a) { return Vec2(a * A.x, a * A.y); } inline double operator*(const Vec2 &A, const Vec2 &B) // Inner product. { return (A.x * B.x) + (A.y * B.y); } inline Vec2 operator/(const Vec2 &A, double c) { return Vec2(A.x / c, A.y / c); } inline double operator^(const Vec2 &A, const Vec2 &B) // Z-component of Cross product. { return A.x * B.y - A.y * B.x; } inline Vec2 &operator+=(Vec2 &A, const Vec2 &B) { A.x += B.x; A.y += B.y; return A; } inline Vec2 &operator-=(Vec2 &A, const Vec2 &B) { A.x -= B.x; A.y -= B.y; return A; } inline Vec2 &operator*=(Vec2 &A, double a) { A.x *= a; A.y *= a; return A; } inline Vec2 &operator/=(Vec2 &A, double a) { A.x /= a; A.y /= a; return A; } inline Vec2 Unit(const Vec2 &A) { double d = LengthSquared(A); return d > 0.0 ? A / sqrt(d) : Vec2(0, 0); } inline std::ostream &operator<<(std::ostream &out, const Vec2 &A) { out << "(" << A.x << ", " << A.y << ") "; return out; } #endif
[ "uddipanm@gmail.com" ]
uddipanm@gmail.com
509808aef8a2dbe7c8cd66126f0ee2c69e1a4d30
8e6cab3c60082fe50c27da58166751b15c7470a2
/h12/h12.cpp
31d39d24d0adcebfdbb3d9635c56fbea6d104121
[]
no_license
occ-cs150/s19-hw-starters
989a8596c8ae51e0da3f2445976fb37a0678a50a
e3f2ab17e7626bc593d77d787f717fb298f5449b
refs/heads/master
2020-04-13T13:05:20.177608
2019-07-25T22:55:15
2019-07-25T22:55:15
163,220,007
0
2
null
null
null
null
UTF-8
C++
false
false
2,042
cpp
/** * @author Put your name here * @date Put the date here * @file h12.cpp */ #include <string> #include <iostream> using namespace std; string STUDENT = "WHO AM I?"; // Add your Canvas/occ-email ID #include "h12.h" // Add your code here /////////////// STUDENT TESTING //////////////////// int run() { // Just some samples for class cout << "Load images/paris.jpg" << endl; // 1. Load a jpg file using 4 bytes per pixel (bpp RGBA) int width, height, bpp, channels = 4; unsigned char * paris = stbi_load("images/paris.jpg", // input file &width, &height, &bpp, // pointers (out) channels); // channels (in) // Now write it out in current folder as a 4-bytes-per-pixel PNG if (stbi_write_png("paris.png", width, height, channels, paris, width * channels)) cout << "Find paris.png in current folder." << endl; else cout << "Couldn't write paris.png" << endl; // IMPORTANT - free the memory stbi_image_free(paris); // 2. Load a png file using 1 byte per pixel (Gray scale) cout << "Loading images/stegosuarus.png as gray scale." << endl; channels = 1; unsigned char * stego = stbi_load("images/stegosaurus.png", &width, &height, &bpp, channels); cout << "Writing as stego-bw.bmp in current folder: "; if (stbi_write_bmp("stego-bw.bmp", width, height, channels, stego)) cout << "Success!" << endl; else cout << "Failed!" << endl; stbi_image_free(stego); // 3. Load a png file using 3 bytes (RGB only) cout << "Load images/Vermeer-Milkmaid.png, 3 bpp." << endl; channels = 3; int quality = 50; // medium quality jpg auto vermeer = stbi_load("images/Vermeer-Milkmaid.png", &width, &height, &bpp, channels); stbi_write_jpg("vermeer.jpg", width, height, channels, stego, quality); stbi_image_free(vermeer); cout << "Saved as vermeer.jpg in current folder." << endl; return 0; }
[ "occ.computerscience@gmail.com" ]
occ.computerscience@gmail.com
ca49ac71bf964cdd222be431e722ae1829e50205
14c7f0417b04f1af61b4dbbbb2a9634dd631d573
/sources/base/forms.cc
179bcce8eba00b638fe5b4dc5ffc222bb01db9d7
[]
no_license
masterleinad/CFL
c328b5c7dd550538b0f76b3f826cceaf007ff920
9a7c72f0def5508f21ff4c2a6c0949699c585d05
refs/heads/master
2022-10-10T23:14:16.278833
2020-06-09T20:56:28
2020-06-09T20:56:28
82,568,048
1
1
null
null
null
null
UTF-8
C++
false
false
28
cc
#include <cfl/base/forms.h>
[ "daniel.arndt@iwr.uni-heidelberg.de" ]
daniel.arndt@iwr.uni-heidelberg.de
00c67027d982d53dbefb38bc19b6a756139e5fb3
140d78334109e02590f04769ec154180b2eaf78d
/aws-cpp-sdk-AWSMigrationHub/source/model/NotifyMigrationTaskStateResult.cpp
b71b0f42970745cfb5145843c1fbe4fa66f33d79
[ "Apache-2.0", "MIT", "JSON" ]
permissive
coderTong/aws-sdk-cpp
da140feb7e5495366a8d2a6a02cf8b28ba820ff6
5cd0c0a03b667c5a0bd17394924abe73d4b3754a
refs/heads/master
2021-07-08T07:04:40.181622
2017-08-22T21:50:00
2017-08-22T21:50:00
101,145,374
0
1
Apache-2.0
2021-05-04T21:06:36
2017-08-23T06:24:37
C++
UTF-8
C++
false
false
1,357
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/AWSMigrationHub/model/NotifyMigrationTaskStateResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::MigrationHub::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; NotifyMigrationTaskStateResult::NotifyMigrationTaskStateResult() { } NotifyMigrationTaskStateResult::NotifyMigrationTaskStateResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } NotifyMigrationTaskStateResult& NotifyMigrationTaskStateResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { AWS_UNREFERENCED_PARAM(result); return *this; }
[ "henso@amazon.com" ]
henso@amazon.com
13d3e110aef015252ad8763e61a0c563292b48ae
db8be521b8e2eab424f594a50886275d68dd5a1b
/Competitive Programming/codechef/COOK45/DIREL.cpp
8f1dbac5afe5ee6ca4f87607ce5cbdda2459fc57
[]
no_license
purnimamehta/Articles-n-Algorithms
7f2aa8046c8eef0e510689771a493f84707e9297
aaea50bf1627585b935f8e43465360866b3b4eac
refs/heads/master
2021-01-11T01:01:53.382696
2017-01-15T04:12:44
2017-01-15T04:12:44
70,463,305
10
4
null
null
null
null
UTF-8
C++
false
false
2,083
cpp
#include<iostream> #include<set> #include<vector> #include<list> #include<map> using namespace std; struct person { list<int> parent; list<int> child; list<int> brothers; }; int main() { freopen("test.txt","r",stdin); ios_base::sync_with_stdio(false); int n,r; cin>>n>>r; map<string,int> id; int currentID=0; vector<person> P(n); for(int i=0;i<r;i++) { //first person string name1; cin>>name1; int id1; if(id.find(name1)==id.end()) { id[name1]=currentID; currentID++; } id1=id[name1]; string is; cin>>is; //relation string relation; cin>>relation; string of; cin>>of; //-- second person string name2; cin>>name2; int id2; if(id.find(name2)==id.end()) { id[name2]=currentID; currentID++; } id2=id[name2]; switch(relation[0]) { case 'f': parentList[id2].push_back(id1); childList[id1].push_back(id2); break; case 'm': parentList[id2].push_back(id1); childList[id1].push_back(id2); break; case 'd': childList[id2].push_back(id1); childList[id1].push_back(id1); break; case 's': if(relation[1]=='o') { childList[id2].push_back(id1); childList[id1].push_back(id1); } else { brotherList[id2].push_back(id1);brotherList[id1].push_back(id2); } break; case 'b': brotherList[id2].push_back(id1);brotherList[id1].push_back(id2); break; } } vector<vector<int> > G(n,vector<int>(n,10000)); // all pair shortest path problem vector<vector<vector<int> > > dist(n+1,vector<vector<int> >(n+1,vector<int>(n+1))); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) dist[0][i][j]=G[i-1][j-1]; vector<vector<int> > P(n,vector<int>(n)); for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { if(dist[k-1][i][j]>dist[k-1][i][k]+dist[k-1][k][j] ) { dist[k][i][j]=dist[k-1][i][k]+dist[k-1][k][j]; P[i][j]=k; } else dist[k][i][j]=dist[k-1][i][j]; } int q; cin>>q; while(q--) { string a,b; cin>>a>>b; cout<<dist.back()[id[a]+1][id[b]+1]<<endl; } }
[ "me@lefeeza.com" ]
me@lefeeza.com
f4a4a27cd49a9a08bc02a69b7198e2e197c66f59
23b3fe726bc41c2af5e38645f39d11ebb8cfb773
/Kasiopea/2016-2017/Domácí kolo/VybiraniUlohC++.cpp
d8938d498cde57b6c2b12db4c988e3fad70d2185
[]
no_license
vmichal/Competitive
f4106deb6a786aa3203841b6f3ac5e5390b3ecf2
e357a20c1365176f25343c5f9fd88edc2e1db4e9
refs/heads/master
2020-12-23T21:02:57.635998
2020-08-09T15:52:22
2020-08-09T15:52:22
237,273,916
0
0
null
null
null
null
UTF-8
C++
false
false
495
cpp
// VybiraniUlohC++.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> void Solve() { int pocetUloh; std::cin >> pocetUloh; int maximum = 0, index = 0, mistni; for (int i = 1; i <= pocetUloh; i++) { std::cin >> mistni; if (mistni > maximum) { maximum = mistni; index = i; } } std::cout << index << "\n"; } int main() { int pocetTestu; std::cin >> pocetTestu; for (int i = 0; i < pocetTestu; i++) { Solve(); } }
[ "michavo3@fel.cvut.cz" ]
michavo3@fel.cvut.cz
01ce40f1bd8e8a68eb1cb70719b25dbd6fb25c8b
feff5dadc85629c0947abf87a79f86ace8c84539
/codeforces/round756/D.cpp
68bdd41232e49a41116308dcc4994015e0fc864b
[]
no_license
Redleaf23477/ojcodes
af7582d9de8619509fa4ffa5338b2a59d9176608
7ee3053a88a78f74764bc473b3bd4887ceac6734
refs/heads/master
2023-08-13T22:34:58.000532
2023-08-10T15:54:05
2023-08-10T15:54:05
107,507,680
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
#include <bits/stdc++.h> using namespace std; using LL = long long int; void solve() { int n; cin >> n; vector<int> pa(n), perm(n); vector<vector<int>> tree(n); for (int i = 0; i < n; i++) { cin >> pa[i]; pa[i]--; if (pa[i] != i) tree[pa[i]].emplace_back(i); } for (auto &x : perm) { cin >> x; x--; } vector<int> dist(n, 0), wei(n, 0); set<int> cand; // find root for (int i = 0; i < n; i++) { if (pa[i] == i) { cand.insert(i); break; } } int len = 0; for (auto p : perm) { if (cand.count(p) == 0) { cout << "-1\n"; return; } dist[p] = len, wei[p] = dist[p] - dist[pa[p]]; len++; cand.erase(p); for (auto v : tree[p]) { cand.insert(v); } } for (auto w : wei) { cout << w << " "; } cout << "\n"; } int main() { ios::sync_with_stdio(false); cin.tie(); int T; cin >> T; while (T--) { solve(); } }
[ "schpokeool@gmail.com" ]
schpokeool@gmail.com
edd6315a55eb5f85559f9822af4a3ddca9cb769b
fc4800fb60cc6a2a98bc2ea99e3b9b6921b7e6c6
/res/ErosRequest.h
8d0ea3c932d528c3ca0e2c01ad0984a3ece2bd5c
[]
no_license
JohannesLaier/cpp-app-server
a3afaed750b0bf4a1e2b56f400309a895ad02e61
f95b5f706a146e1b5e20c022c1f900b946ec3ffc
refs/heads/master
2020-03-22T06:23:14.326660
2018-07-03T20:56:46
2018-07-03T20:56:46
139,629,900
0
0
null
null
null
null
UTF-8
C++
false
false
1,234
h
#ifndef __EROSREQUEST_H__ #define __EROSREQUEST_H__ #include <string> #include <vector> #include <map> class ErosRequest { public: struct HeaderItem { std::string name; std::string value; }; private: int versionMajor; int versionMinor; bool keepAlive; std::string path; std::string method; std::string content; std::vector<HeaderItem> headers; std::map<std::string, std::string> parameter; public: std::string getParameter(const std::string& key) { return parameter[key]; } void setVersionMajor(int version) { versionMajor = version; } void setVersionMinor(int version) { versionMinor = version; } void setPath(std::string p) { path = p; } void setMethod(std::string m) { method = m; } void setContent(std::string c) { content = c; } void setKeepAlive(bool ka) { keepAlive = ka; } int getVersionMajor() { return versionMajor; } int getVersionMinor() { return versionMinor; } std::string getPath() { return path; } std::string getMethod() { return method; } std::string getContent() { return content; } std::vector<HeaderItem>& getHeaders() { return headers; } }; #endif
[ "JohannesLaier@gmail.com" ]
JohannesLaier@gmail.com
8cb13fbe45e7bb278307dfda8d3d961f93346367
76deee42b4baaac862770d5377df5c744ea377dc
/Chapter 7/ProgrammingExercise08b/ProgrammingExercise08b.cpp
823aa0b93ec7b2c4275e4ce8437772d78cf968a3
[]
no_license
DanielEverland/Learning-cpp
d7e3facd73d6b8c519b5e2a189216d56f098f905
cf715249412dd15a0b9f1f868deca67a19cb9d83
refs/heads/master
2022-02-03T06:46:32.199555
2019-06-25T11:15:28
2019-06-25T11:15:28
157,078,809
0
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
// ProgrammingExercise08b.cpp #include <iostream> #include <array> #include <string> // constant data const int Seasons = 4; const char* Snames [Seasons] { "Spring", "Summer", "Fall", "Winter" }; struct expenses { double expenses[Seasons]; }; // function to modify array object void fill(expenses* pa); // function that uses array object without modifying it void show(expenses da); int main() { expenses expenses; fill(&expenses); show(expenses); } void fill(expenses* pa) { using namespace std; for (int i = 0; i < Seasons; i++) { cout << "Enter " << Snames[i] << " expenses: "; cin >> pa->expenses[i]; } } void show(expenses da) { using namespace std; double total = 0.0; cout << "\nEXPENSES\n"; for (int i = 0; i < Seasons; i++) { cout << Snames[i] << ": $" << da.expenses[i] << endl; total += da.expenses[i]; } cout << "Total Expenses: $" << total << endl; }
[ "danieleverland@gmail.com" ]
danieleverland@gmail.com
152920040d7d8a4f8b136799bd179ae07991c285
57e31fb322af3400569b40a15d9e45faeea81169
/GameServer/config.h
219d1e04af0fcb1c598f533ad7e8a51ff1a08cc6
[]
no_license
MSMsssss/BattleOfTank
f360b1251e8012f4bab1fe7d44364e22b42f1f67
f0d0790c9c668bb74e0377d524efdfb68287a6e2
refs/heads/master
2022-11-22T10:57:17.826559
2020-07-22T08:34:19
2020-07-22T08:34:19
281,616,606
0
0
null
null
null
null
UTF-8
C++
false
false
2,421
h
#ifndef CONFIG_H #define CONFIG_H #include <QHostAddress> #include <QHash> class Config { public: Config(); public: static QHostAddress serverAddress; static quint16 serverPort; // 登录状态回复 static const int LoginSuccess = 1; static const int PlayerNameError = 2; static const int PasswordError = 3; static const int RepeatLogin = 4; // 请求加入游戏回复 static const int RoomIsFull = 1; static const int JoinSuccess = 2; static const int RoomNotExists = 3; static const int RepeatJoin = 4; /******************************************** * 每个数据包长度不定,前两个字节为数据长度,后两个字节为 * 数据类型。 * ******************************************/ static const quint16 EmptyPacket = 0; //固定尺寸的无效数据包,用于督促操作系统尽快发送数据 static const quint16 LoginRequestPacket = 1; //登陆请求,包含昵称和密码。 static const quint16 LoginReplyPacket = 2; //登陆回复,返回登陆结果。 static const quint16 RegisterRequestPacket = 3; //注册请求 static const quint16 RegisterReplyPacket = 4; //注册结果回复 static const quint16 PlayerOperationPacket = 5; //玩家操作 static const quint16 RoomsInfoRequestPacket = 6; //房间信息请求数据包 static const quint16 ReplyRoomsInfoRequestPacket = 7; //回复房间信息请求数据包 static const quint16 GameStatusPacket = 8; // 游戏状态数据包 static const quint16 RequestJoinRoomPacket = 9; //请求加入房间数据包 static const quint16 ReplyJoinRoomPacket = 10; //回复加入房间数据包 static const quint16 PlayerInfoListPacket = 11; //玩家信息包 static const quint16 ProjectileInfoListPacket = 12; // 子弹信息包 static const quint16 BlockInfoListPacket = 13; //墙体信息包 static const quint16 KillListPacket = 14; //击杀列表包 static const quint16 ParticleEmitPacket = 15; //粒子发射包 static const quint16 MapInfoPacket = 16; //地图信息包 static const quint16 GameInfoPacket = 17; //游戏局势信息 static const bool TestMode = true; // 逻辑帧间隔时间,单位ms static const int FrameInterval = 50; // 仅作测试使用 static const QHash<QString, QString> playerAccountList; }; #endif // CONFIG_H
[ "1301797927@qq.com" ]
1301797927@qq.com
0574e626cf7553f1448534464520081db7695032
5f3365cf749aa2054e63ad9d1e1c800c5802fbec
/People/Teacher.h
0f52cdcd81c3b4001f978ed2452c9522db6fde5c
[]
no_license
0x81-sh/cpp-inheritance-schoolHR
6fd6eea1d045fdedf36d349dfac646772471dab4
60ebf8c42cd0dfa3236f5530fc95f4f16f4a2e95
refs/heads/master
2023-08-27T15:29:05.080366
2021-11-13T20:45:12
2021-11-13T20:45:12
427,768,791
0
0
null
null
null
null
UTF-8
C++
false
false
433
h
#pragma once #include "Person.h" class Teacher : public Person { private: int employeeNum; protected: Map& convert(Map &ref) const override; public: Teacher(const std::string &firstName = "", const std::string &lastName = "", int socSecNum = 0, const Date& dateOfBirth = {1, 1, 2000}, int employeeNum = 0); int getEmployeeNum() const; void setEmployeeNum(int employeeNum); };
[ "ulrich.barnstedt@gmail.com" ]
ulrich.barnstedt@gmail.com
c07676eed07da044c99df4914ca29aaa925da36d
fcc579036adef53f9d1bd3ddc2e8f918adec9618
/src/devices/VRPN_PhantomOmni.cxx
6f737f7d3cd3dd5a33300e0fa0c1bdfba74ca59e
[]
no_license
engelfaul/tissueRV
513cc32d6576d0a54d57f8edb463140557b9386c
da851453e0ce4a848f8263b097ca29a3f96133f7
refs/heads/master
2020-03-20T22:58:12.031418
2018-11-11T02:55:06
2018-11-11T02:55:06
137,823,356
0
0
null
2018-11-11T02:55:07
2018-06-19T01:07:25
C++
UTF-8
C++
false
false
733
cxx
#include "VRPN_PhantomOmni.h" // ------------------------------------------------------------------------- VRPN_Device_Callback_Macro( VRPN_PhantomOmni, Tracker, vrpn_TRACKERCB ); // ------------------------------------------------------------------------- VRPN_PhantomOmni:: VRPN_PhantomOmni( unsigned int B ) : Superclass( B ) { } // ------------------------------------------------------------------------- VRPN_PhantomOmni:: ~VRPN_PhantomOmni( ) { } // ------------------------------------------------------------------------- void VRPN_PhantomOmni:: linkHandlers( ) { this->m_Device.Tracker->register_change_handler( this, VRPN_Device_Callback_Name_Macro( VRPN_PhantomOmni, Tracker ) ); } // eof - $RCSfile$
[ "carlospabon777@gmail.com" ]
carlospabon777@gmail.com
1f69ef1235580eeaa07f2236feaf801a5e55087a
515d4cea84eb2dd70b67b1b1bfc64de14fdd0d3d
/arduino/src/buttons.cpp
a3b0d063e1f49653bc71e76f089e19d9c3a23ff2
[]
no_license
Pigaco/hosts
cc618566dcedca9442850ce0aeb18286d2b5decb
64a872aeeb179ce38513d553a015c7165956b73e
refs/heads/master
2021-01-22T03:13:58.418832
2016-11-14T12:41:57
2016-11-14T12:41:57
38,927,975
1
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
#include <buttons.hpp> #include <PlayerManager.hpp> #include "../../host_defines.h" #include <main.hpp> namespace Buttons { void setCallbackFunc(host_input_callback_func callback) { getPlayerMgr()->setCallbackFunc(callback); } }
[ "mail@maximaximal.com" ]
mail@maximaximal.com
0751877fa3c4d9c505deda8dbc6d6d6d4a1ac122
55bedcb8629003aedacccfc6cd40931531d5aa7e
/Homework5-Q2/q2.hpp
e6456a3ec1651951513721bb37757de3ed3f2990
[]
no_license
RajShah-94/Homework5
5af1d970c19a968cada7cc23d09db7b31aa37360
a6f5b7a6980ff6a5f702a5f3747b10e1a51ffcfe
refs/heads/master
2020-05-21T13:01:25.434232
2014-02-28T17:00:36
2014-02-28T17:00:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
431
hpp
/* * q2.hpp * * Created on: 28 Feb 2014 * Author: rajru_000 */ #ifndef Q2_HPP_ #define Q2_HPP_ MyClass operator+(const MyClass & a) const { // declares operator that can between object my class (sum operator) MyClass b(*this); // creates a duplicate instance of the current myClass object b += a; // adds value of a to running value of b return b; // returns myClass object } #endif /* Q2_HPP_ */
[ "rajshah94@gmail.com" ]
rajshah94@gmail.com
44262aec0dce9cce228350dd7478e27d05e97579
f9df7ac6edbebdeb795eced8e2cda20d2e8fae49
/RadeonGPUAnalyzerGUI/include/qt/rgSourceCodeEditor.h
be7dd14a22dca780aa2181cfdc78c570fe1fae58
[ "MIT" ]
permissive
alphonsetai/RGA
6c4f908a60f02a2b7ab5018070aa779187f45099
76cd5f36b40bd5e3de40bfb3e79c410aa4c132c9
refs/heads/master
2020-03-09T12:11:53.445548
2019-01-07T06:56:30
2019-01-07T06:56:30
128,779,678
0
0
MIT
2019-01-07T06:56:31
2018-04-09T13:52:24
C++
UTF-8
C++
false
false
4,534
h
#pragma once // Qt. #include <QPlainTextEdit> #include <QObject> // Local. #include <RadeonGPUAnalyzerGUI/include/qt/rgSyntaxHighlighter.h> // Forward declarations. class QPaintEvent; class QResizeEvent; class QSize; class QWidget; class LineNumberArea; class rgSourceCodeEditor : public QPlainTextEdit { Q_OBJECT public: rgSourceCodeEditor(QWidget* pParent = nullptr); // Get the selected line number that the cursor is on. int GetSelectedLineNumber() const; // Retrieve the text at the specified line. bool GetTextAtLine(int lineNumber, QString& text) const; // A callback used to paint the line number area. void LineNumberAreaPaintEvent(QPaintEvent* pEvent); // Compute the width of the line number area. int LineNumberAreaWidth() const; // Scroll the editor to the given line number. void ScrollToLine(int lineNumber); // Sets the contents of the source code view. void setText(const QString& txt); // Clears the contents of the source code view. void clearText(const QString& txt); signals: // A signal emitted when the source editor is hidden. void EditorHidden(); // A signal emitted when the source editor is resized. void EditorResized(); // A signal emitted when the user changes the selected line index. void SelectedLineChanged(rgSourceCodeEditor* pEditor, int lineIndex); public slots: // Apply a colored highlight to the background of each given row. void SetHighlightedLines(const QList<int>& lineIndices); protected: // An overridden paint handler responsible for painting a blinking cursor when the editor doesn't have focus. virtual void paintEvent(QPaintEvent* pEvent) override; // An overridden resize handler responsible for recomputing editor geometry. virtual void resizeEvent(QResizeEvent* pEvent) override; // An overridden "widget was hidden" handler used to emit a signal indicating a visibility change. virtual void hideEvent(QHideEvent* pEvent) override; private slots: // A handler invoked when the blinking cursor toggled between visible and hidden. void HandleToggleCursorVisibility(); // A handler invoked when the line number area width is changed. void UpdateLineNumberAreaWidth(int newBlockCount); // A handler invoked when the cursor has been moved within the document. void UpdateCursorPosition(); // A handler invoked when the line number area is updated. void UpdateLineNumberArea(const QRect &, int); private: // Connect the editor signals. void ConnectSignals(); // Used to append a row highlight selection for the current line. void HighlightCursorLine(QList<QTextEdit::ExtraSelection>& selections); // Used to append row highlights for correlated source code lines. void HighlightCorrelatedSourceLines(QList<QTextEdit::ExtraSelection>& selections); // Helper function that performs the logic which is related to a cursor position update // event, while taking into account the type of the event: correlation vs. user selection. void UpdateCursorPositionHelper(bool isCorrelated); // The flag indicating if the cursor is visible or hidden. bool m_isCursorVisible; // A timer used to toggle the visibility of the blinking cursor. QTimer* m_pCursorBlinkTimer; // The list of rows painted with the highlight color. QList<int> m_highlightedRowIndices; // The line number display widget. QWidget* m_pLineNumberArea = nullptr; // The syntax highlighter used to alter the rendering of keywords in the source editor. rgSyntaxHighlight* m_pSyntaxHighlight = nullptr; }; // A widget used to paint the line number gutter in the source editor. class LineNumberArea : public QWidget { public: LineNumberArea(rgSourceCodeEditor* pEditor) : QWidget(pEditor), m_pCodeEditor(pEditor) {} // Override the sizeHint based on the line number gutter width. virtual QSize sizeHint() const override { return QSize(m_pCodeEditor->LineNumberAreaWidth(), 0); } protected: // Overridden paint for drawing the gutter with line numbers. virtual void paintEvent(QPaintEvent* pEvent) override { m_pCodeEditor->LineNumberAreaPaintEvent(pEvent); } // Overridden double click event for the line number gutter area. virtual void mouseDoubleClickEvent(QMouseEvent* pEvent) override {} private: // The editor where line numbers will be painted. rgSourceCodeEditor* m_pCodeEditor = nullptr; };
[ "amit.bm3@gmail.com" ]
amit.bm3@gmail.com
da3a97b190b0d2bd9ae0955baf516d867aa10856
ba981da87bf277a926c8ac492da189fc779c674d
/09 Ninth/1249. Minimum Remove to Make Valid Parentheses.cpp
03d204c6457c77b1799198345a582c1209f1fb8f
[]
no_license
arpitsangwan/Friendly-contests
499ab75c40b70ea5f411de068efe2b0ecda61680
05760ae9e7e4cbdcd7d528b0b0b937752b4dee9f
refs/heads/main
2023-06-06T09:15:56.345940
2021-06-28T18:38:22
2021-06-28T18:38:22
347,100,724
1
0
null
null
null
null
UTF-8
C++
false
false
633
cpp
//https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ class Solution { public: string minRemoveToMakeValid(string s) { int co=0; string ans=""; for(int i=0;i<s.length();i++){ if(s[i]=='('){co++;} if(s[i]==')'){co--;} if(co>=0){ans+=s[i];} if(co<0){co=0;} } int i=ans.size()-1; while(co>0){ if(ans[i]=='('){ co--; ans=ans.substr(0,i)+ans.substr(i+1); } else{i--;} } return ans; } };
[ "arpitsangwan3@gmail.com" ]
arpitsangwan3@gmail.com
81325260c61c8c3ba0d4577daff6cdc8df5d42c9
53e776f993683b12dc0745b9e3c1744a48260f6c
/dadt/internal/common/device.h
eab89bfd7ed8a45d1147db90f3e5641255081bfe
[ "MIT" ]
permissive
amazingyyc/DADT
3e427d658b998b09810a2a5268e8eae6ea062f7f
da6cf2c15923d2be6a10d2c5ece95ff6a6f98ebc
refs/heads/master
2022-05-02T15:00:18.292150
2022-04-14T14:52:49
2022-04-14T14:52:49
200,825,374
9
0
MIT
2022-04-14T14:52:50
2019-08-06T10:00:21
C++
UTF-8
C++
false
false
1,766
h
#pragma once #include <cstring> #include <memory> namespace dadt { // a device type, for now only CPU enum class DeviceType : uint8_t { kCPU = 0, kGPU = 1, }; // used to allocate memory from device class IAllocator { public: // malloc memory from device virtual void* Malloc(size_t) = 0; // free memory to device virtual void Free(void*) = 0; // zero the memory virtual void Zero(void*, size_t) = 0; }; class CPUAllocator : public IAllocator { public: void* Malloc(size_t) override; void Free(void*) override; // zero the memory void Zero(void*, size_t) override; }; class GPUAllocator : public IAllocator { private: // the gpu device id int device_id_; public: GPUAllocator(int device_id); void* Malloc(size_t) override; void Free(void*) override; // zero the memory void Zero(void*, size_t) override; }; class Device { private: // the device id // CPU is -1 // GPU is corresponding the real GPU device int device_id_; // device type DeviceType device_type_; // memory allocator std::unique_ptr<IAllocator> allocator_; public: Device(int, DeviceType); ~Device() = default; bool operator==(const Device&) const; int device_id(); DeviceType device_type(); // malloc memory from device void* Malloc(size_t); // free the memory void Free(void*); // zero the memory void Zero(void*, size_t); public: static Device* DDevice(int device_id); static Device* CPUDevice(); static Device* GPUDevice(int device_id); }; // this two funcion is thread-safe std::shared_ptr<Device> get_cpu_device(); std::shared_ptr<Device> get_gpu_device(int device_id); } // namespace dadt
[ "amazingyyc@outlook.com" ]
amazingyyc@outlook.com
3227054c83409d34c5f610ef5f1a99f05868cf79
ebf7654231c1819cef2097f60327c968b2fa6daf
/server/scene_server/messager/Scene_Server_Request.cpp
06221e942be26f8d25f4bf1915cd6bb2a28c3304
[]
no_license
hdzz/game-server
71195bdba5825c2c37cb682ee3a25981237ce2ee
0abf247c107900fe36819454ec6298f3f1273e8b
refs/heads/master
2020-12-30T09:15:17.606172
2015-07-29T07:40:01
2015-07-29T07:40:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
48,737
cpp
/* * Scene_Server_Request.cpp * * Created on: Jan 22, 2014 * Author: ti */ #include "Scene_Server_Request.h" #include "Scene_Client_Request.h" #include "Scene_Monitor.h" #include "Scene_Public.h" #include "Pool_Manager.h" #include "Scene_Player.h" #include "Fighter_Detail.h" #include "Msg_Inner_Enum.h" #include "Msg_Inner_Struct.h" #include "NPC/NPC_Manager.h" #include "NPC/hero/Hero.h" #include "Global_Scene_Manager.h" #include "Err_Code.h" #include "Battle_Scene.h" #include "heroer/Logic_Heroer_Def.h" #include "team/Scene_Team_Manager.h" #include "war/Scene_War_Manager.h" #include "Move_Scene.h" #include "dragon/Scene_Dragon_Vale_Manager.h" #include "gang/Scene_Gang_Global_Manager.h" #include "main_scene/Main_Scene_Manager.h" #include "main_scene/Main_Scene.h" #include "valentine_monster/Valentine_Monster_Manager.h" #include "world_boss/Gang_Boss_Manager.h" #include "world_boss/World_Boss_Manager.h" #include "honor_arena/Honor_Arena_Manager.h" #include "scene_outpost/Scene_Outpost_Manager.h" #include "Config_Cache_Scene.h" #include "campfire/Campfire_Data_Manager.h" #include "campfire/Scene_Campfire.h" #include "Msg_Active_Struct.h" #include "Msg_Dungeon_Struct.h" #include "Config_Cache_Arena.h" #include "public/Public_Def.h" #include "Msg_Role_Scene_Struct.h" #include "team/Team_Arena_Controler.h" #include "inner_arena/Inner_Arena_Manager.h" #include "knight_trials/Scene_Knight_Trials_Manager.h" #include "expedition_scene/Expedition_Global_Scene_Manager.h" #include "answer/Answer_Scene_Manager.h" #include "module/campfire_scene/Campfire_Scene_Manager.h" Scene_Server_Request::Scene_Server_Request() { // TODO Auto-generated constructor stub monitor_ = SCENE_MONITOR; } Scene_Server_Request::~Scene_Server_Request() { // TODO Auto-generated destructor stub } int Scene_Server_Request::find_player_by_buf(Block_Buffer &buf, Scene_Player *&player) { role_id_t role_id = 0; if (buf.read_int64(role_id)) { MSG_USER_TRACE("read role id:%ld", role_id); return CALL_RETURN; } player = monitor()->find_scene_player_by_role_id(role_id); if (! player) { MSG_USER_TRACE("can not find scene player:%ld", role_id); return CALL_RETURN; } return 0; } int Scene_Server_Request::logic_login_ready(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { if (player) { MSG_TRACE_ABORT("player exist!"); return -1; } Scene_Player *s_player = POOL_MANAGER->pop_scene_player(); if (!s_player) { MSG_TRACE_ABORT("pop player error"); return -1; } s_player->load_detail(buf); // 如果上线时场景还存在就进入场景,否则回去通知逻辑服回滚场景 int des_scene = 0; int exist_scene = s_player->login_scene_exist(des_scene); if (exist_scene) { s_player->module_init(); monitor()->bind_scene_player(*s_player); s_player->notice_enter_scene(); } Block_Buffer inner_buf; inner_buf.make_message(LOGIC_SCENE_LOGIN_READY); inner_buf.write_int32(exist_scene); inner_buf.write_int32(des_scene); inner_buf.finish_message(); inner_buf.make_head(inner_buf.get_msg_id(), s_player->role_id()); monitor()->send_to_server_by_cid(cid, inner_buf); MSG_DEBUG("login scene finish, role:%ld", role_id); return 0; } int Scene_Server_Request::logic_logout_ready(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { if (!player) { MSG_USER("can not find player, role:%ld", role_id); return 0; } Time_Value sign_out_flag; sign_out_flag.deserialize(buf); int out_reason = 0, need_return = 0; buf.read_int32(out_reason); buf.read_int32(need_return); Monitor_Unique_ID logic_muid = player->monitor_link().logic_muid; if (player) { MSG_DEBUG("scene logout success, role:%ld, out_reason:%d, notice_logic:%d, force:%d", role_id, out_reason, need_return, player->fighter_detail().force); player->sign_out(!need_return); monitor()->unbind_scene_player(role_id); } else { MSG_USER("scene logout error, role:%ld, out_reason:%d, notice_logic:%d", role_id, out_reason, need_return); } // 登陆错误时不需要回去 if (need_return) { Block_Buffer inner_buf; inner_buf.make_message(LOGIC_SCENE_LOGOUT_READY); sign_out_flag.serialize(inner_buf); inner_buf.finish_message(); inner_buf.make_head(inner_buf.get_msg_id(), role_id); monitor()->send_to_monitor(logic_muid, inner_buf); } return 0; } int Scene_Server_Request::process_20110001(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); player->load_scene_detail(buf); return 0; } int Scene_Server_Request::process_20200050(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); // 战斗中,退出战斗 if (player->is_in_battle()){ player->exit_battle_scene(14); player->notify_gate_exit_battle(14); } Coord coord; Monitor_Unique_ID scene_muid; Create_Scene_Args scene_args; scene_muid.deserialize(buf); coord.deserialize(buf); scene_args.deserialize(buf); int src_scene_id = player->move_scene_id(); {// tbay const Scene_Config* target_cfg = CONFIG_CACHE_SCENE->scene_config_cache(scene_muid.id); if(target_cfg){ if(target_cfg->type == Tbay_Scene_Type){ int64_t monster_role_id = scene_args.id; if(player->move_scene()){ Mover* mover = player->move_scene()->find_mover_with_layer(0, monster_role_id); if(mover && mover->monster_self()){ int target_id = 0; int target_time = 0; int target_type = 0; mover->monster_self()->get_ex_param(target_id, target_time, target_type); scene_args.type = target_type; scene_args.sub_sort = player->move_scene_id(); scene_args.int_value = target_time; } } } } } player->set_rela_scene_id(scene_muid.id); player->gang_war_info().exit_ = true; player->exit_move_scene(false); player->set_scene_muid(scene_muid); player->set_create_scene_args(scene_args.type, scene_args.time, scene_args.id, scene_args.sort, scene_args.sub_sort, scene_args.int_value); player->set_grid_coord(coord.grid_coord().x, coord.grid_coord().y); player->set_pixel_coord(coord.pixel_coord().x, coord.pixel_coord().y); player->scene_init(); Block_Buffer inner_buf; inner_buf.make_message(INNER_TRAN_SCENE_SAME_PRO); scene_muid.serialize(inner_buf); coord.serialize(inner_buf); inner_buf.finish_message(); player->send_to_logic(inner_buf); player->notice_enter_scene(); MSG_DEBUG("tran scene in same process , role:%ld, src:%d, des scene:%d", role_id, src_scene_id, player->move_scene_id()); return 0; } int Scene_Server_Request::process_20200055(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); Monitor_Unique_ID logic_muid = player->monitor_link().logic_muid; if (player) { MSG_DEBUG("logout scene success, role:%ld, scene:%d", role_id, player->move_scene_id()); if (player->move_scene_id() == 0) { MSG_TRACE_ABORT("scene tran error, role:%ld", role_id); } //在不同进程转场景时调用sign_out_ex,这个是非掉线的,要将offline_exit设为false player->sign_out(false, false); monitor()->unbind_scene_player(role_id); } else { MSG_USER("logout scene error, role:%ld, scene:%d", role_id, player->monitor_link().scene_muid.id); } Block_Buffer inner_buf; inner_buf.make_message(INNER_ASK_SCENE_SIGN_OUT); inner_buf.copy(&buf); inner_buf.finish_message(); inner_buf.make_head(inner_buf.get_msg_id(), role_id); return monitor()->send_to_monitor(logic_muid, inner_buf); } int Scene_Server_Request::process_20200056(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { if (player) { MSG_TRACE_ABORT("player exist! role:%ld", role_id); return -1; } Scene_Player *s_player = POOL_MANAGER->pop_scene_player(); if (!s_player) { MSG_TRACE_ABORT("pop player error"); return -1; } s_player->buff_insert_handle_switch() = true; s_player->load_detail(buf); s_player->module_init(); monitor()->bind_scene_player(*s_player); Block_Buffer inner_buf; inner_buf.make_message(INNER_ASK_SCENE_SIGN_IN); s_player->monitor_link().scene_muid.serialize(inner_buf); s_player->grid_coord().serialize(inner_buf); inner_buf.finish_message(); inner_buf.make_head(inner_buf.get_msg_id(), s_player->role_id()); monitor()->send_to_server_by_cid(cid, inner_buf); s_player->notice_enter_scene(); MSG_DEBUG("transmit scene finish, role:%ld", role_id); return 0; } int Scene_Server_Request::process_20200100(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int from = 0; Prop_Setter_Vec setter_vec; Prop_Setter setter; buf.read_int32(from); uint16_t vec_size = 0; if(buf.read_uint16(vec_size)) { return -1; } setter_vec.reserve(vec_size); for(uint16_t i = 0; i < vec_size; ++i) { setter.reset(); if(setter.deserialize(buf)) { return -1; } switch (setter.prop_type) { case PT_EXP_CURRENT: { player->modify_experience(setter.basic); break; } default : { setter_vec.push_back(setter); } } } if (! setter_vec.empty()) { //player->fight_modify_fight_prop(setter_vec, true); player->modify_props_normal(setter_vec, false, from); } return 0; } int Scene_Server_Request::process_20300000(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //JUDGE_PLAYER_NULL(player, role_id); MSG_20300000 msg; msg.deserialize(buf); Drops* drops = NPC_MANAGER->find_drops_npc(msg.drops_role_id); if(drops){ drops->erase_drops_item(msg.item_index, role_id, player); } return 0; } int Scene_Server_Request::process_20100018(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100018 msg; msg.deserialize(buf); JUDGE_PLAYER_NULL(player, role_id); return player ->learn_skill(msg.skill_id, msg.skill_lv, msg.page_id); } int Scene_Server_Request::process_20100019(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100019 msg; msg.deserialize(buf); JUDGE_PLAYER_NULL(player, role_id); return player->erase_skill(msg.type, msg.page_id); } int Scene_Server_Request::process_20100020(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100020 msg; msg.deserialize(buf); JUDGE_PLAYER_NULL(player, role_id); return player->change_skill_loc(msg.skill_id, msg.new_loc, msg.page_id); } int Scene_Server_Request::process_20100022(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100022 msg; msg.deserialize(buf); JUDGE_PLAYER_NULL(player, role_id); //return player->open_a_talent_page(msg.page_id); return player->open_a_talent(msg.page_id); } int Scene_Server_Request::process_20100023(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100023 msg; msg.deserialize(buf); JUDGE_PLAYER_NULL(player, role_id); return player->use_a_talent_page(msg.page_id); } int Scene_Server_Request::process_20100025(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100025 msg; msg.deserialize(buf); JUDGE_PLAYER_NULL(player, role_id); return player->skill_cost_and_save(msg.type, msg.arg1, msg.arg2); } int Scene_Server_Request::process_20300020(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ JUDGE_PLAYER_NULL(player, role_id); MSG_20300020 msg; msg.deserialize(buf); if(msg.plot_step == 0){ player->begin_plot(msg.plot_id); }else{ player->end_plot(msg.plot_id); } return 0; } int Scene_Server_Request::process_20300030(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ JUDGE_PLAYER_NULL(player, role_id); if (player->is_in_battle()) { MSG_DEBUG("creat arena fail player in battle"); return ERROR_PLAYER_IN_BATTLE; } if (player->dead_status()) { MSG_DEBUG("creat arena fail player dead"); return ERROR_PLAYER_DIE; } Battle_Scene *scene = GLOBAL_SCENE_MANAGER->create_battle_scene(player->move_scene()); if(!scene){ return -1; } scene->set_battle_type(Battle_Scene::BATTLE_TYPE_ARENA); int fight_map_id = CONFIG_CACHE_ARENA->get_arena_fight_map_id(); scene->set_map_id(fight_map_id); // role_id_t match_role_id = 0; // buf.read_int64(match_role_id); // if(match_role_id == 0){ // // }else{ // // } int32_t inner_area = 0; int8_t career = 0; int8_t gender = 0; std::string role_name; buf.read_int32(inner_area); buf.read_int8(career); buf.read_int8(gender); buf.read_string(role_name); int8_t size = 0; buf.read_int8(size); Int_Vec avatar_vec; for (int8_t i=0; i<size; ++i) { int avatar_id = 0; buf.read_int32(avatar_id); avatar_vec.push_back(avatar_id); } NPC_Addition_Info add_info; add_info.birth_coord.x = 1; add_info.birth_coord.y = 5; add_info.ex_val1 = career; add_info.ex_val2 = gender; add_info.name = role_name; int monster_type = 63800108; Player_Monster* player_monster; player_monster = NPC_MANAGER->create_player_monster(monster_type, NULL, add_info, scene, buf); if(player_monster == NULL){ MSG_DEBUG("creat arena monster fail"); return -1; } player_monster->set_player_monster_avatar(avatar_vec); player_monster->hero_battle_birth(buf, scene); player_monster->battle_enter_appaer(scene); double morale_init = player_monster->fighter_detail().fetch_fight_property(Property_Type::PT_INIT_MORALE, Prop_Value::ELEM_NORMAL); Hero* hero = player_monster->find_hero(); if(0 != hero) { morale_init += hero->fighter_detail().fetch_fight_property(Property_Type::PT_INIT_MORALE, Prop_Value::ELEM_NORMAL); } player_monster->reset_morale_and_hp(morale_init, player_monster->blood_max(), false); if(player->set_battle_position(0, Position_Key::LINE_TWO_FRONT, scene) == 0){ player->enter_battle_scene(scene); } return 0; } int Scene_Server_Request::process_20300032(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ return INNER_ARENA_AREA_MANAGER->inner_arena_sync_rank_info(buf); } int Scene_Server_Request::process_20300033(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ return INNER_ARENA_AREA_MANAGER->inner_arena_fetch_fight_data(buf); } int Scene_Server_Request::process_20300034(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ return INNER_ARENA_AREA_MANAGER->inner_arena_match_player(buf); } int Scene_Server_Request::process_20300035(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ return INNER_ARENA_AREA_MANAGER->inner_arena_fetch_rank_info(buf); } int Scene_Server_Request::process_20300038(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ return INNER_ARENA_AREA_MANAGER->inner_arena_battle_result(buf); } int Scene_Server_Request::process_20300040(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf){ return INNER_ARENA_AREA_MANAGER->inner_arena_season_finish(buf); } int Scene_Server_Request::process_20400000(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int8_t detail_type = 0; buf.read_int8(detail_type); if (detail_type != OUTER_HERO_ONLY && detail_type != FIGHT_HERO_ONLY && detail_type != OUTER_FIGHT_HERO) { return -1; } switch (detail_type) { case OUTER_HERO_ONLY: process_20400000_1(buf, player); break; case FIGHT_HERO_ONLY: process_20400000_2(buf, player); break; case OUTER_FIGHT_HERO: process_20400000_3(buf, player); break; default: break; } return 0; } int Scene_Server_Request::process_20400000_1(Block_Buffer &buf, Scene_Player *player) { Hero_Base_Detail detail; detail.reset(); detail.deserialize(buf); Hero *hero = SCENE_PUBLIC->find_master_id_hero(detail.master_role_id); if (! hero) { hero = POOL_MANAGER->pop_hero(); if (hero) { hero->reset(); detail.hero_role_id = NPC_MANAGER->generate_hero_order(); //生成hero地图服id hero->init(detail.hero_role_id, player->move_scene(), player->grid_coord()); NPC_MANAGER->hero_map()[detail.hero_role_id] = hero; SCENE_PUBLIC->bind_master_id_hero(detail.master_role_id, *hero); } } if (hero && !hero->validate_battle_scene()) { hero->refresh_hero_base_detail(detail); } return 0; } int Scene_Server_Request::process_20400000_2(Block_Buffer &buf, Scene_Player *player) { Hero_Base_Detail detail; detail.reset(); detail.deserialize(buf); Hero *hero = SCENE_PUBLIC->find_fight_hero(detail.master_role_id); if (! hero) { hero = POOL_MANAGER->pop_hero(); if (hero) { hero->reset(); detail.hero_role_id = NPC_MANAGER->generate_hero_order(); //生成hero地图服id hero->init(detail.hero_role_id, player->move_scene(), player->grid_coord()); NPC_MANAGER->hero_map()[detail.hero_role_id] = hero; SCENE_PUBLIC->bind_fight_hero(detail.master_role_id, *hero); } } if (hero && !hero->validate_battle_scene()) { hero->refresh_hero_base_detail(detail); } return 0; } int Scene_Server_Request::process_20400000_3(Block_Buffer &buf, Scene_Player *player) { Hero_Base_Detail detail; detail.reset(); detail.deserialize(buf); // 跟随英雄 { Hero *outer_hero = SCENE_PUBLIC->find_master_id_hero(detail.master_role_id); if (! outer_hero) { outer_hero = POOL_MANAGER->pop_hero(); if (outer_hero) { outer_hero->reset(); detail.hero_role_id = NPC_MANAGER->generate_hero_order(); //生成hero地图服id outer_hero->init(detail.hero_role_id, player->move_scene(), player->grid_coord()); NPC_MANAGER->hero_map()[detail.hero_role_id] = outer_hero; SCENE_PUBLIC->bind_master_id_hero(detail.master_role_id, *outer_hero); } } if (outer_hero && !outer_hero->validate_battle_scene()) { outer_hero->refresh_hero_base_detail(detail); } } // 战斗英雄 { Hero *fight_hero = SCENE_PUBLIC->find_fight_hero(detail.master_role_id); if (! fight_hero) { fight_hero = POOL_MANAGER->pop_hero(); if (fight_hero) { fight_hero->reset(); detail.hero_role_id = NPC_MANAGER->generate_hero_order(); //生成hero地图服id fight_hero->init(detail.hero_role_id, player->move_scene(), player->grid_coord()); NPC_MANAGER->hero_map()[detail.hero_role_id] = fight_hero; SCENE_PUBLIC->bind_fight_hero(detail.master_role_id, *fight_hero); } } if (fight_hero && !fight_hero->validate_battle_scene()) { fight_hero->refresh_hero_base_detail(detail); } } return 0; } int Scene_Server_Request::process_20400001(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int8_t detail_type = 0; buf.read_int8(detail_type); if (detail_type != OUTER_HERO_ONLY && detail_type != FIGHT_HERO_ONLY && detail_type != OUTER_FIGHT_HERO) { return -1; } switch (detail_type) { case OUTER_HERO_ONLY: process_20400001_1(buf); break; case FIGHT_HERO_ONLY: process_20400001_2(buf); break; case OUTER_FIGHT_HERO: process_20400001_3(buf); break; default: break; } return 0; } int Scene_Server_Request::process_20400001_1(Block_Buffer &buf) { Fighter_Detail detail; detail.reset(); detail.deserialize(buf); role_id_t master_role_id = 0; buf.read_int64(master_role_id); Hero *hero = SCENE_PUBLIC->find_master_id_hero(master_role_id); if (hero && !hero->validate_battle_scene()) { hero->refresh_hero_fighter_detail(detail); } else { MSG_USER("cannot find outer_hero, master_role_id = %ld", master_role_id); return -1; } return 0; } int Scene_Server_Request::process_20400001_2(Block_Buffer &buf) { Fighter_Detail detail; detail.reset(); detail.deserialize(buf); role_id_t master_role_id = 0; buf.read_int64(master_role_id); Hero *hero = SCENE_PUBLIC->find_fight_hero(master_role_id); if (hero && !hero->validate_battle_scene()) { hero->refresh_hero_fighter_detail(detail); hero->load_status_info(buf); } else { int battle_id = hero ? hero->battle_scene_id() : -2; MSG_USER("cannot find fight_hero, master_role_id = %ld, b_id:%d", master_role_id, battle_id); return -1; } return 0; } int Scene_Server_Request::process_20400001_3(Block_Buffer &buf) { Fighter_Detail detail; detail.reset(); detail.deserialize(buf); role_id_t master_role_id = 0; buf.read_int64(master_role_id); // 跟随英雄 Hero *outer_hero = SCENE_PUBLIC->find_master_id_hero(master_role_id); if (outer_hero && !outer_hero->validate_battle_scene()) { outer_hero->refresh_hero_fighter_detail(detail); } else { MSG_USER("cannot find outer_hero, master_role_id = %ld", master_role_id); return -1; } // 战斗英雄 Hero *fight_hero = SCENE_PUBLIC->find_fight_hero(master_role_id); if (fight_hero && !fight_hero->validate_battle_scene()) { fight_hero->refresh_hero_fighter_detail(detail); } else { MSG_USER("cannot find fight_hero, master_role_id = %ld", master_role_id); return -1; } return 0; } int Scene_Server_Request::process_20400002(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); return 0; } int Scene_Server_Request::process_20400003(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20400003 msg; msg.deserialize(buf); Hero *hero = SCENE_PUBLIC->find_master_id_hero(role_id); if (! hero) { //MSG_USER("hero fight, can't find hero, master_id = %ld, is_out = %d", msg.master_role_id, msg.is_out); // 登陆时会到这里 return -1; } // 出战 if (msg.is_out) { if (player->is_in_battle()) { //player->hero_battle_birth(); } else if (player->move_scene()) { if (player->move_scene()->scene_type() == War_Scene_Type) { return 0; } const Coord &player_coord = player->mover_detail().grid_coord; if (0 != hero->birth(hero->hero_const_base_detail().hero_role_id, player->move_scene(), player_coord)) { hero->outer_hero_recycle(); return -1; } } // 收回 } else { hero->outer_hero_recycle(); } return 0; } int Scene_Server_Request::process_20400007(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20400007 msg; msg.deserialize(buf); Hero *hero = SCENE_PUBLIC->find_fight_hero(role_id); if (! hero) { return -1; } // 出战 if (msg.is_fight) { // 收回 } else { if (! hero->validate_battle_scene()) { // 战斗中,不能回收英雄 //MSG_DEBUG("hero battle id:%d", hero->battle_scene_id()); hero->fight_hero_recycle(); } } return 0; } int Scene_Server_Request::process_20410001(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_50200032 res_msg; res_msg.role_id = player->role_id(); res_msg.open_type = 1; player->fighter_detail().property_list(res_msg.prop_value); Hero *hero = SCENE_PUBLIC->find_fight_hero(player->role_id()); if (hero) { int hero_init_morale_type = hero->fighter_detail().init_morale.type; double hero_init_morale_val = hero->fighter_detail().init_morale.total(); for (uint16_t i = 0; i < res_msg.prop_value.size(); ++i) { if (res_msg.prop_value[i].type == hero_init_morale_type) { res_msg.prop_value[i].value += hero_init_morale_val; } } } res_msg.prop_value.push_back(Property(PT_CAREER, player->career())); res_msg.role_name = player->role_name();/*人物姓名*/ res_msg.gang_name = player->base_detail().gang_name;/*人物id*/ res_msg.gender = player->base_detail().gender;/*性别(1男,2女)*/ res_msg.gang_id = player->base_detail().gang_id;/*职业*/ res_msg.headship = player->ganger_detail().headship; res_msg.avatar_vec = player->base_detail().avatar_vec; OBJ_SEND_TO_CLIENT(res_msg, (*player)); return 0; } int Scene_Server_Request::process_20100200(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); role_id_t role_id_2 = 0; int8_t open_type = 0; buf.read_int64(role_id_2); buf.read_int8(open_type); MSG_50100032 res_msg; res_msg.role_id = role_id_2; res_msg.open_type = open_type; player->fighter_detail().property_list(res_msg.prop_value); Hero *hero = SCENE_PUBLIC->find_fight_hero(player->role_id()); if (hero) { int hero_init_morale_type = hero->fighter_detail().init_morale.type; double hero_init_morale_val = hero->fighter_detail().init_morale.total(); for (uint16_t i = 0; i < res_msg.prop_value.size(); ++i) { if (res_msg.prop_value[i].type == hero_init_morale_type) { res_msg.prop_value[i].value += hero_init_morale_val; } } } res_msg.prop_value.push_back(Property(PT_CAREER, player->career())); res_msg.prop_value.push_back(Property(PT_CHARM, player->base_detail().charm)); /*魅力值*/ res_msg.role_name = player->role_name();/*人物姓名*/ res_msg.gang_name = player->base_detail().gang_name;/*人物id*/ res_msg.gender = player->base_detail().gender;/*性别(1男,2女)*/ res_msg.gang_id = player->base_detail().gang_id;/*职业*/ res_msg.headship = player->ganger_detail().headship; res_msg.avatar_vec = player->base_detail().avatar_vec; res_msg.vip = player->vip(); // OBJ_SEND_TO_CLIENT(res_msg, (*player)); Block_Buffer inner_buf; inner_buf.make_message(INNER_REQ_OPEN_PANEL); res_msg.serialize(inner_buf); inner_buf.finish_message(); player->send_to_logic(inner_buf); return 0; } int Scene_Server_Request::process_20100028(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); std::string new_name = ""; if (0 != buf.read_string(new_name) || new_name.empty()) { return -1; } player->set_role_name(new_name); return 0; } int Scene_Server_Request::process_20100029(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); uint8_t gender = 0; buf.read_uint8(gender); player->modify_gender(gender); MSG_81000060 msg; msg.role_id = player->role_id(); Prop_Change change_info; change_info.prop_type = PT_GENDER; change_info.current_val = gender; msg.change_info.push_back(change_info); Block_Buffer active_buf; MAKE_MSG_BUF(msg, active_buf); // 广播给周围玩家 player->scene_broad_around(active_buf,Mover::SCENE_MOVE); return 0; } int Scene_Server_Request::process_20100031(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); uint16_t energy = 0; buf.read_uint16(energy); player->set_energy(energy); return 0; } int Scene_Server_Request::process_20100032(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int skill_id = 0; buf.read_int32(skill_id); player->set_life_skill(skill_id); return 0; } int Scene_Server_Request::process_20100030(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20100030 msg; msg.deserialize(buf); player->sync_phy_power_info(msg.phy_power_cur, msg.phy_power_recover_time, msg.phy_power_buy_times); return 0; } int Scene_Server_Request::process_20100303(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20100303 msg; player->syn_teamer_info(buf); return 0; } int Scene_Server_Request::process_20100304(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { SCENE_TEAM_MANAGER->add_team(buf); return 0; } int Scene_Server_Request::process_20100305(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20100305 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); player->use_drug_inner(msg.tp, msg.index, msg.val, msg.amount, buf); return 0; } int Scene_Server_Request::process_20100306(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { int8_t switch_ = 0; buf.read_int8(switch_); if (switch_ == 0) { TEAM_ARENA_CONTROLER->team_sports_test() = false; TEAM_ARENA_CONTROLER->close_sports_activity(); } else { TEAM_ARENA_CONTROLER->team_sports_test() = true; TEAM_ARENA_CONTROLER->open_sports_activity(); } return 0; } int Scene_Server_Request::process_20100400(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); player->restore_full_prop(buf); return 0; } int Scene_Server_Request::process_20100401(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); player->req_battle_status(buf); return 0; } int Scene_Server_Request::process_20100500(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); player->load_status_info(buf); return 0; } int Scene_Server_Request::process_20100501(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); player->inner_status_insert(buf); return 0; } int Scene_Server_Request::process_20100502(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int status_id = 0; buf.read_int32(status_id); if (0 == player->erase_status_type(status_id)) { MSG_81000071 msg_scene; msg_scene.type = SFT_SCENE; Status_Info_Msg msg_info; msg_info.status_id = status_id; msg_info.overlay = 0; msg_info.status_owner = player->role_id(); msg_scene.buff_detail.push_back(msg_info); if (!msg_scene.buff_detail.empty()) { OBJ_SEND_TO_CLIENT(msg_scene, (*player)); } } return 0; } int Scene_Server_Request::process_20100503(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int8_t type = 0; uint16_t len = 0; buf.read_int8(type); buf.read_uint16(len); if (len <= 0) { return 0; } // player Hero *hero = SCENE_PUBLIC->find_fight_hero(role_id); if (!hero) { return 0; } if (type == 1) { // add for (uint16_t i = 0; i < len; ++i) { hero->inner_status_insert(buf); } } else { Int_Hash_Set is; int status_id = 0; for (uint16_t i = 0; i < len; ++i) { buf.read_int32(status_id); is.insert(status_id); } hero->erase_status_in_set(is); } return 0; } int Scene_Server_Request::process_20300012(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20300012 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); player->gather_goods_result(msg.role_id, msg.result); return 0; } int Scene_Server_Request::process_20420000(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); role_id_t sender_role_id = 0; int bless_buf_id = 0; buf.read_int64(sender_role_id); buf.read_int32(bless_buf_id); player->inner_send_bless_buf(sender_role_id, bless_buf_id); return 0; } int Scene_Server_Request::process_20170000(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20170000 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); gang_id_t src_gang_id = player->gang_id(); player->set_gang_id(msg.gang_id); player->set_gang_name(msg.gang_name); player->ganger_detail().headship = msg.headship; player->listen_gang_info_sync(); WORLD_BOSS_MANAGER->listen_gang_info_sync(src_gang_id, player); GANG_BOSS_MANAGER->listen_gang_info_sync(src_gang_id, player); if (0 == msg.gang_id && Expedition_Type == get_scene_type(player->move_scene_id())) { int des_scene = 0; player->inner_transmit(des_scene, 0, 0); } return 0; } int Scene_Server_Request::process_20170001(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { SCENE_GANG_GLOBAL_MANAGER->gang_war_load_source_gangs_from_logic(buf); return 0; } int Scene_Server_Request::process_20170002(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { player->gang_load_detail(buf); return 0; } int Scene_Server_Request::process_20170004(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { player->ask_gang_war_rank_info(buf); return 0; } int Scene_Server_Request::process_20170006(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { SCENE_GANG_GLOBAL_MANAGER->set_activity_state(buf); return 0; } int Scene_Server_Request::process_20100309(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { TEAM_ARENA_CONTROLER->update_role_score(buf); return 0; } int Scene_Server_Request::process_20100310(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100310 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); Block_Buffer inner_buf; inner_buf.make_message(INNER_GET_TEAM_SCORE); TEAM_ARENA_CONTROLER->get_role_score_list(msg.role_id, msg.level, inner_buf); inner_buf.finish_message(); inner_buf.make_head(inner_buf.get_msg_id(), msg.role_id); monitor()->send_to_server_by_cid(cid, inner_buf); return 0; } int Scene_Server_Request::process_20300100(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { Monitor_Unique_ID logic_muid; role_id_t player_role_id = 0; int level = 0; int force = 0; role_id_t gang_id = 0; int8_t remain_income_num = 0; int16_t income_rate = 0; int total_merit = 0; int remain_time = 0; int act_time = 0; std::string server_name; logic_muid.deserialize(buf); buf.read_int64(player_role_id); buf.read_int32(level); buf.read_int32(force); buf.read_int64(gang_id); buf.read_int8(remain_income_num); buf.read_int16(income_rate); buf.read_int32(total_merit); buf.read_int32(remain_time); buf.read_int32(act_time); buf.read_string(server_name); SCENE_WAR_MANAGER->req_enter_war_scene(logic_muid, player_role_id, level, force, gang_id, remain_income_num, income_rate, total_merit, remain_time, act_time, server_name); return 0; } int Scene_Server_Request::process_20300101(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { int8_t sync_type = 0; buf.read_int8(sync_type); switch(sync_type){ case 3:{// 单人副本付费复活消耗钻石返回 if(player && player->move_scene() && player->move_scene()->scene_type() == FuBen_Scene_Type){ int8_t revive_result = 0; buf.read_int8(revive_result); if(revive_result == 1){ int param1 = 0; int param2 = 0; int param3 = 0; player->move_scene()->get_scene_param(param1, param2, param3); param1 = 0; player->move_scene()->set_scene_param(param1, param2, param3, true); player->reset_revive_info(); { MSG_81000026 msg; msg.role_id = player->role_id(); msg.state = 0; OBJ_SEND_TO_CLIENT(msg, (*player)); } { MSG_50200215 msg; msg.result = 1; OBJ_SEND_TO_CLIENT(msg, (*player)); } }else{ MSG_50200215 msg; msg.result = 0; OBJ_SEND_TO_CLIENT(msg, (*player)); } } break; } default:{ break; } } return 0; } int Scene_Server_Request::process_20100403(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int8_t type = 0; buf.read_int8(type); uint16_t vec_size = 0; if (buf.read_uint16(vec_size)) { return -1; } Int_Double_Map force_map; player->get_all_pre_force(force_map); int old_val = player->fighter_detail().force; Skill_Info skill_info; for (uint16_t i = 0; i < vec_size; ++i) { skill_info.reset(); skill_info.deserialize(buf); if (type == NPT_ADD) { player->add_skill_extra(skill_info.skill_id, skill_info.skill_lv); } else if (type == NPT_REMOVE) { player->remove_skill_extra(skill_info.skill_id, skill_info.skill_lv); } } if (vec_size > 0) { player->sync_force_to_client(); } int new_val = player->fighter_detail().force; player->print_all_part_force(100, new_val-old_val, force_map); return 0; } int Scene_Server_Request::process_20100026(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int32_t skill_point = 0; buf.read_int32(skill_point); if (skill_point > 0) { player->add_skill_pointer(skill_point); } return 0; } int Scene_Server_Request::process_20100040(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20100040 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); return player->sync_mount_ride(msg.ride, msg.model_id, msg.speed); } int Scene_Server_Request::process_20100600(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); int32_t title_id = 0; buf.read_int32(title_id); player->set_title(title_id); return 0; } int Scene_Server_Request::process_20600000(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600000 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_rob_dragon_vale_match(msg.uuid, msg.server_name, msg.role_id, msg.coin, msg.last_coin); return 0; } int Scene_Server_Request::process_20600002(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600002 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_rob_match(msg); return 0; } int Scene_Server_Request::process_20600004(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { SCENE_DRAGON_VALE_MANAGER->process_rob_fight(buf); return 0; } int Scene_Server_Request::process_20600007(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600007 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_rob_enter_dragon_vale(msg.to_uuid, msg.to_role_id, msg.uuid, msg.role_id, msg.limit_time); return 0; } int Scene_Server_Request::process_20600008(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600008 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_rob_enter_dragon_vale(msg); return 0; } int Scene_Server_Request::process_20600009(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600009 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_gain_rob_production(msg); return 0; } int Scene_Server_Request::process_20600010(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600010 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_gain_rob_production_res(msg); return 0; } int Scene_Server_Request::process_20600012(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { int64_t creater = 0; buf.read_int64(creater); SCENE_DRAGON_VALE_MANAGER->process_broadcast_dragon_vale_scene(creater, buf); return 0; } int Scene_Server_Request::process_20600014(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { SCENE_DRAGON_VALE_MANAGER->process_rob_match_fail(buf); return 0; } int Scene_Server_Request::process_20600015(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600015 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_refresh_dragon_vale_monster(msg.type, msg.role_id, msg.id, msg.quality); return 0; } int Scene_Server_Request::process_20600020(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600020 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_rob_match_fail_back_coin(msg.uuid, msg.role_id, msg.coin, msg.type); return 0; } int Scene_Server_Request::process_20600031(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20600031 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); SCENE_DRAGON_VALE_MANAGER->process_dragon_vale_rob(msg.to_uuid, msg.to_role_id, msg.to_server_name, msg.to_role_name, msg.uuid, msg.role_id, msg.server_name, msg.role_name, msg.coin, msg.flag); return 0; } int Scene_Server_Request::process_20300110(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //MSG_20300110 msg; //JUDGE_ERROR_RETURN(msg.deserialize(buf)); // CAMPFIRE_DATA_MANAGER->cmd_campfire_player_info_sync(buf); return 0; } int Scene_Server_Request::process_20300111(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //MSG_20300110 msg; //JUDGE_ERROR_RETURN(msg.deserialize(buf)); return CAMPFIRE_DATA_MANAGER->cmd_campfire_activate(buf); } int Scene_Server_Request::process_20300112(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //MSG_20300110 msg; //JUDGE_ERROR_RETURN(msg.deserialize(buf)); //CAMPFIRE_DATA_MANAGER-> return 0; } int Scene_Server_Request::process_20300114(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20300114 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); JUDGE_PLAYER_NULL(player, role_id); return player->get_campfire_award_result(msg); } int Scene_Server_Request::process_20300116(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { MSG_20300116 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); JUDGE_PLAYER_NULL(player, role_id); return player->load_campfire_player_info(msg); } int Scene_Server_Request::process_20300300(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //MSG_20300300 msg; //JUDGE_ERROR_RETURN(msg.deserialize(buf)); int act_icon_id = 0; buf.read_int32(act_icon_id); switch(act_icon_id){ case 16:{ WORLD_BOSS_MANAGER->inner_sync_info(player, buf); break; } case 19:{ GANG_BOSS_MANAGER->inner_sync_info(player, buf); break; } case 22:{ HONOR_ARENA_MANAGER->inner_sync_info(player, buf); break; } default:{ break; } } return 0; } int Scene_Server_Request::process_20300301(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //MSG_20300301 msg; //JUDGE_ERROR_RETURN(msg.deserialize(buf)); int act_icon_id = 0; int64_t gang_id = 0; buf.read_int32(act_icon_id); buf.read_int64(gang_id); switch(act_icon_id){ case 16:{ WORLD_BOSS_MANAGER->inner_player_enter(gang_id, buf); break; } case 19:{ GANG_BOSS_MANAGER->inner_player_enter(gang_id, buf); break; } case 22:{ HONOR_ARENA_MANAGER->inner_player_enter(gang_id, buf); break; } default:{ break; } } return 0; } int Scene_Server_Request::process_20300302(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //MSG_20300302 msg; //JUDGE_ERROR_RETURN(msg.deserialize(buf)); int act_icon_id = 0; role_id_t gang_id = 0; buf.read_int32(act_icon_id); buf.read_int64(gang_id); switch(act_icon_id){ case 16:{ WORLD_BOSS_MANAGER->inner_act_start(gang_id, buf); break; } case 19:{ GANG_BOSS_MANAGER->inner_act_start(gang_id, buf); break; } case 20:{ VALENTINE_MONSTER_MANAGER->inner_act_start(gang_id, buf); break; } case 22:{ HONOR_ARENA_MANAGER->inner_act_start(gang_id, buf); break; } default:{ break; } } return 0; } int Scene_Server_Request::process_20300303(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { //MSG_20300303 msg; //JUDGE_ERROR_RETURN(msg.deserialize(buf)); int act_icon_id = 0; role_id_t gang_id = 0; buf.read_int32(act_icon_id); buf.read_int64(gang_id); switch(act_icon_id){ case 16:{ WORLD_BOSS_MANAGER->inner_act_end(gang_id, buf); break; } case 19:{ GANG_BOSS_MANAGER->inner_act_end(gang_id, buf); break; } case 20:{ VALENTINE_MONSTER_MANAGER->inner_act_end(gang_id, buf); break; } case 22:{ HONOR_ARENA_MANAGER->inner_act_end(gang_id, buf); break; } default:{ break; } } return 0; } int Scene_Server_Request::process_20300400(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { return SCENE_OUTPOST_MANAGER->inner_sync_info(player, buf); } int Scene_Server_Request::process_20200020(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20200020 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); player->set_vip_info_change(msg.vip, msg.vip_over_time); return 0; } int Scene_Server_Request::process_20200023(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20200023 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); player->set_head_id(msg.head_id); return 0; } int Scene_Server_Request::process_20200022(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20200022 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); player->add_charm(msg.num); return 0; } int Scene_Server_Request::process_20300200(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { Monitor_Unique_ID muid; Coord coord; int shop_type = 0; muid.deserialize(buf); coord.deserialize(buf); buf.read_int32(shop_type); Create_Scene_Args cs_args; Move_Scene* scene = MAIN_SCENE_MANAGER->find_scene_simple(muid, 0, cs_args); if(scene){ Main_Scene* main_scene = dynamic_cast<Main_Scene*>(scene); if(main_scene){ if(shop_type == 0){ main_scene->close_secret_shop(); }else{ main_scene->open_secret_shop(coord, shop_type); } } } return 0; } int Scene_Server_Request::process_20100050(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &inner_buf) { JUDGE_PLAYER_NULL(player, role_id); uint16_t change_info_size = 0; inner_buf.read_uint16(change_info_size); if (change_info_size == 0) { return -1; } MSG_81000066 active_msg; active_msg.change_info.reserve(change_info_size); String_Info_Change string_info_change; for (uint16_t i = 0; i < change_info_size; ++i) { string_info_change.reset(); if (string_info_change.deserialize(inner_buf)) { return -1; } active_msg.change_info.push_back(string_info_change); } inner_buf.read_int64(active_msg.role_id); Block_Buffer active_buf; MAKE_MSG_BUF(active_msg, active_buf); player->scene_broad_around(active_buf,Mover::SCENE_MOVE); return 0; } int Scene_Server_Request::process_20100051(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &inner_buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_81000067 active_msg; inner_buf.read_int64(active_msg.role_id); inner_buf.read_int8(active_msg.int_type); switch (active_msg.int_type) { case 32: { uint16_t change_info_size = 0; inner_buf.read_uint16(change_info_size); if (change_info_size == 0) { return -1; } Int32_Info_Change int32_info_change; bool is_hero_awake = false; for (uint16_t i = 0; i < change_info_size; ++i) { int32_info_change.reset(); if (int32_info_change.deserialize(inner_buf)) { return -1; } if (int32_info_change.type == IICT_HERO_AWAKE_LVL) { is_hero_awake = true; } active_msg.vec_32_change_info.push_back(int32_info_change); } // 英雄觉醒等级更新 if (is_hero_awake) { Hero *hero = SCENE_PUBLIC->find_mover_hero(player->role_id()); if (hero) { active_msg.role_id = hero->role_id(); Block_Buffer active_buf; MAKE_MSG_BUF(active_msg, active_buf); hero->scene_broad_around(active_buf,Mover::SCENE_MOVE); } } break; } case 8: case 16: case 64: break; default: break; } return 0; } int Scene_Server_Request::process_20010061(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); player->sync_fighter_detail_to_logic(); return 0; } int Scene_Server_Request::process_20100060(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20100060 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); player->set_avatar(msg.avatar_vec); return 0; } int Scene_Server_Request::process_20610000(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { return SCENE_KNIGHT_TRIALS_MANAGER->scene_knight_trials_match_player(buf); } int Scene_Server_Request::process_20610001(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); MSG_20610001 msg; JUDGE_ERROR_RETURN(msg.deserialize(buf)); return SCENE_KNIGHT_TRIALS_MANAGER->scene_knight_trials_enter_fighter(player, buf); } int Scene_Server_Request::process_20610010(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { return EXPEDITION_GLOBAL_SCENE_MANAGER->data_channle(buf); } int Scene_Server_Request::process_20610012(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { JUDGE_PLAYER_NULL(player, role_id); return player->expedition_data_channel(buf); } int Scene_Server_Request::process_20610020(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { return ANSWER_SCENE_MANAGER->data_channle(buf); } int Scene_Server_Request::process_20020001(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { return SCENE_PUBLIC->sync_dispath(buf); } int Scene_Server_Request::process_20999999(int cid, role_id_t role_id, Scene_Player *player, Block_Buffer &buf) { return SCENE_PUBLIC->inner_check_info_on_center_server(buf); }
[ "zuti@avatarworks.com" ]
zuti@avatarworks.com
5d95f757186d1fc6eccc9a04136ae471d062edf7
a2793ecc10f3a683ab6fbe045b71c78b1cafb7b8
/external/bh_tsne/quadtree.h
fbbb26434a09ef6ac7f2fb2841d8a77b88ee3613
[ "BSD-2-Clause" ]
permissive
jeffrey-hokanson/FlowML
4e67cba1f1ade0485824aa702fa872f645791562
878f318bdde53365f1b2f75725376bdbd4485f7e
refs/heads/master
2021-01-22T13:42:54.142314
2015-01-29T00:31:36
2015-01-29T00:31:36
21,365,669
3
1
null
null
null
null
UTF-8
C++
false
false
4,223
h
/* * * Copyright (c) 2013, Laurens van der Maaten (Delft University of Technology) * All rights reserved. * * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN 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 QUADTREE_H #define QUADTREE_H using namespace std; static inline double min(double x, double y) { return (x <= y ? x : y); } static inline double max(double x, double y) { return (x <= y ? y : x); } static inline double abs(double x) { return (x < .0 ? -x : x); } class Cell { public: double x; double y; double hw; double hh; bool containsPoint(double point[]); }; class QuadTree { // Fixed constants static const int QT_NO_DIMS = 2; static const int QT_NODE_CAPACITY = 1; // A buffer we use when doing force computations double buff[QT_NO_DIMS]; // Properties of this node in the tree QuadTree* parent; bool is_leaf; int size; int cum_size; // Axis-aligned bounding box stored as a center with half-dimensions to represent the boundaries of this quad tree Cell boundary; // Indices in this quad tree node, corresponding center-of-mass, and list of all children double* data; double center_of_mass[QT_NO_DIMS]; int index[QT_NODE_CAPACITY]; // Children QuadTree* northWest; QuadTree* northEast; QuadTree* southWest; QuadTree* southEast; public: QuadTree(double* inp_data, int N); QuadTree(double* inp_data, double inp_x, double inp_y, double inp_hw, double inp_hh); QuadTree(double* inp_data, int N, double inp_x, double inp_y, double inp_hw, double inp_hh); QuadTree(QuadTree* inp_parent, double* inp_data, int N, double inp_x, double inp_y, double inp_hw, double inp_hh); QuadTree(QuadTree* inp_parent, double* inp_data, double inp_x, double inp_y, double inp_hw, double inp_hh); ~QuadTree(); void setData(double* inp_data); QuadTree* getParent(); void construct(Cell boundary); bool insert(int new_index); void subdivide(); bool isCorrect(); void rebuildTree(); void getAllIndices(int* indices); int getDepth(); void computeNonEdgeForces(int point_index, double theta, double neg_f[], double* sum_Q); void computeEdgeForces(int* row_P, int* col_P, double* val_P, int N, double* pos_f); void print(); private: void init(QuadTree* inp_parent, double* inp_data, double inp_x, double inp_y, double inp_hw, double inp_hh); void fill(int N); int getAllIndices(int* indices, int loc); bool isChild(int test_index, int start, int end); }; #endif
[ "jeffrey@hokanson.us" ]
jeffrey@hokanson.us
4ae614d39f9cbbd59fc9e4099eacad70cc9b4512
de2d9eb403f3ab84a61789d3a928ce6ae5c3badd
/OpenGL_5/Common/CChecker.h
4d413deef0971a5a81666ea444c2993091db3a0c
[]
no_license
peiyunlee/opengl-3dgame
a8caf87392a31656f2560e8434ba9d53324c0705
9df8611facc19cf586cef7248fb9f036c7e21ea4
refs/heads/master
2023-06-16T15:14:22.030091
2021-07-14T08:22:10
2021-07-14T08:22:10
233,113,711
1
0
null
null
null
null
BIG5
C++
false
false
981
h
#ifndef CCHECKER_H #define CCHECKER_H #include "TypeDefine.h" #include "CQuad.h" // 以 (0,0) 為中心 劃出一個 nXn 的棋盤方格 // n 在宣告時給定 class CChecker { private: CQuad *m_pSquares; int m_iGridSize; float *m_pfSquaresT; GLuint m_uiShaderHandle; float m_fYPos; int m_iMode; public: CChecker(int iSize = 6, float fYPos = 0.0f); // 預設為 6 X 6 方格, 每一個方格邊長都是 1 ~CChecker(); void SetShader(); void SetShaderName(const char vxShader[], const char fsShader[]); void SetProjectionMatrix(mat4 &mat); void SetViewMatrix(mat4 &mat); void SetTRSMatrix(mat4 &mat); void SetShadingMode(int iMode) {m_iMode = iMode;} void SetTextureLayer(int texlayer); void Update(float dt, const LightSource &lights); void Draw(); // For setting materials void SetMaterials(color4 ambient, color4 diffuse, color4 specular); void SetKaKdKsShini(float ka, float kd, float ks, float shininess); // ka kd ks shininess }; #endif
[ "may1092200258@gmail.com" ]
may1092200258@gmail.com
66f13dee9d5a19f5000213c7254fc566823584c7
9103f127a400f94ef17d77835935327a1afcdc1f
/solutions/valid_palindrome_easy.cpp
b4cf7275259c8c6368de63080cc140655feac29b
[]
no_license
gurus158/codingPractice
610eca8948006f7288afc74ea36e0b29551f4572
473a17815bc845a586fae7a22c194911e45ee923
refs/heads/master
2022-10-01T00:32:11.489969
2022-08-31T07:42:56
2022-08-31T07:42:56
238,144,580
0
0
null
null
null
null
UTF-8
C++
false
false
540
cpp
#include<bits/stdc++.h> using namespace std; class Solution{ public: bool isPalindrome(string s){ int end=s.size()-1; int start=0; while(start<end){ while(!isalnum(s.at(start))&&start<s.size()-1 ) start++; while(!isalnum(s.at(end))&&end>0) end--; if(start<end){ if(tolower(s.at(start))!=tolower(s.at(end))) return false; start++; end--; } } return true; } }; int main(){ string s="0P"; Solution sol; (sol.isPalindrome(s))?cout<<"YES":cout<<"NO"; }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
bed50c898faf09ec58c9c8590e9a5c0dfb882cc8
08948ee7b7239bfc09b274082f52db4f832433cb
/src/Collision/SAT.cpp
1c6ed65c977de66aaff6a0f373ce79bd144cb363
[ "MIT" ]
permissive
Tobaloidee/rainbow
4d738953403c40046055409ea6df722456bfd050
7bbac9405ae9e519c6496f2a5fa957a073cce563
refs/heads/master
2020-05-02T16:51:13.265175
2019-03-27T22:09:40
2019-03-27T22:09:40
178,011,578
0
0
MIT
2019-03-27T14:29:51
2019-03-27T14:29:51
null
UTF-8
C++
false
false
2,213
cpp
// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #include "Collision/SAT.h" #include <algorithm> #include "Graphics/Sprite.h" using rainbow::SpriteRef; using rainbow::SpriteVertex; using rainbow::Vec2f; namespace { struct Quad { Vec2f v0, v1, v2, v3; explicit Quad(const SpriteRef& sprite) : Quad(sprite->vertex_array()) {} explicit Quad(const SpriteVertex* vertices) : v0(vertices[0].position), v1(vertices[1].position), v2(vertices[2].position), v3(vertices[3].position) { } }; template <typename T> bool overlaps(const std::pair<T, T>& a, const std::pair<T, T>& b) { return *a.first < *b.first ? *a.second >= *b.first : *a.first <= *b.second; } bool overlaps(const Quad& a, float ar, const Quad& b, float br) { int count = 4; Vec2f axes[8]{(a.v1 - a.v0).normal().normalize(), (a.v2 - a.v1).normal().normalize(), (a.v3 - a.v2).normal().normalize(), (a.v0 - a.v3).normal().normalize()}; if (!rainbow::are_equal(ar, br)) { count = 8; axes[4] = (b.v1 - b.v0).normal().normalize(); axes[5] = (b.v2 - b.v1).normal().normalize(); axes[6] = (b.v3 - b.v2).normal().normalize(); axes[7] = (b.v0 - b.v3).normal().normalize(); } return std::all_of(axes, axes + count, [&a, &b](const Vec2f& axis) { const float a_dots[]{ axis * a.v0, axis * a.v1, axis * a.v2, axis * a.v3}; const float b_dots[]{ axis * b.v0, axis * b.v1, axis * b.v2, axis * b.v3}; return overlaps( std::minmax_element(std::begin(a_dots), std::end(a_dots)), std::minmax_element(std::begin(b_dots), std::end(b_dots))); }); } } // namespace bool rainbow::overlaps(const SpriteRef& a, const SpriteRef& b) { return ::overlaps(Quad{a}, a->angle(), Quad{b}, b->angle()); }
[ "tn0502@gmail.com" ]
tn0502@gmail.com
ea45f741b53798fc334e6441ebaedf39a777098f
9b40d8a0171989b145e8895be30979767f655111
/ATLASDAN/RTPBuit/include/SequenceSettingsState.h
336f5bebe32d379e79c1ec93c5a063f88010ad55
[]
no_license
Nasker/RTPPIO
f25ec02f041b70faf517973b724a3b6c69487930
3c9f2f982360c7f3f31aa7c189a2667ee6eb35c5
refs/heads/master
2023-02-21T10:43:07.522565
2022-06-30T09:43:33
2022-06-30T09:43:33
211,109,662
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
#include "BuitStateMachine.h" class SequenceSettingsState : public BuitState{ BuitStateMachine* _buitMachine; public: SequenceSettingsState (BuitStateMachine* buitMachine); void singleClick(); void doubleClick(); void longClick(); void rotaryTurned(ControlCommand command); void threeAxisChanged(ControlCommand command); void trellisPressed(ControlCommand command); void trellisReleased(ControlCommand command); };
[ "xamps23@gmail.com" ]
xamps23@gmail.com
41b1b794f5fd3bcb14fd8c930b3e3cf4dafab4ea
b307f5be8a1782745fb6fc3cd45b33b41dfe83cc
/IFileDB.hpp
1385f626cdfb54e6d5a04476cd423353296bf349
[]
no_license
gamelook/core
59b2557c64622e52f41654d573e7ff98181437b6
dec8df7a8b07af4c10bdaac73447d2337828323a
refs/heads/master
2021-01-01T16:35:31.328277
2013-08-09T05:58:34
2013-08-09T05:58:34
11,994,147
1
0
null
null
null
null
UTF-8
C++
false
false
527
hpp
#ifndef CORE_CORE_IFILEDB_H__ #define CORE_CORE_IFILEDB_H__ #include <string> namespace core{ class IFileDB { public: IFileDB(){} virtual ~IFileDB(){} virtual int GetData(const char* pszTable, ID id, const char* pszField) = 0; virtual String GetStr(const char* pszTable, ID id, const char* pszField) = 0; virtual int GetData(const char* pszTable, const char* id, const char* pszField) = 0; virtual String GetStr(const char* pszTable, const char* id, const char* pszField) = 0; }; } #endif //CORE_CORE_IFILEDB_H__
[ "gamehouse@163.com" ]
gamehouse@163.com
9cd7ebb610b77cb8930f1fb9e9ec7e1a82e4c682
00501b0e29384abafe908f96b93fa3ac619ee3f4
/common/common.h
540b5019d9fa6ff2c1b447ff96f294c01c605a09
[]
no_license
Kokaku/operation-matterhorn-public-
beaa7a3131ae996e4fc5e13059fd52b8fb2e4e2d
1378f1d9af44cefff02b784f7f4de66b13a7f888
refs/heads/master
2020-04-05T20:16:01.403175
2014-11-19T13:21:44
2014-11-19T13:21:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
966
h
// Copyright (C) 2014 - LGG EPFL // Copyright (C) 2014 - Andrea Tagliasacchi #pragma once ///--- LOAD THE OPENGL LIBRARIES HERE (IN CROSS PLATFORM) #include <GL/glew.h> ///< must be before glfw #include <GL/glfw.h> /// We use a modified (to support OpenGL3) version of the Eigen OpenGL module /// @see http://eigen.tuxfamily.org/dox/unsupported/group__OpenGLSUpport__Module.html #include <OpenGP/GL/EigenOpenGLSupport3.h> // #include <Eigen/OpenGL3Support> /// We use Eigen for linear algebra typedef Eigen::Vector2f vec2; typedef Eigen::Vector3f vec3; typedef Eigen::Matrix4f mat4; typedef Eigen::Matrix3f mat3; /// On some OSs the exit flags are not defined #ifndef EXIT_SUCCESS #define EXIT_SUCCESS 0 #endif #ifndef EXIT_FAILURE #define EXIT_FAILURE 1 #endif /// For mesh I/O we use OpenGP #include <OpenGP/Surface_mesh.h> #include <OpenGP/GL/glfw_trackball.h> /// These namespaces assumed by default using namespace std; using namespace opengp;
[ "Kokaku@tsf-428-wpa-1-200.epfl.ch" ]
Kokaku@tsf-428-wpa-1-200.epfl.ch
898ba3650418decffc4351d036756d1ee0a91647
1bfcb7db9770614dc33c6bf7a0a62377b6bf8e82
/test5.cc
b9f45ba0c64012a90cba113fda379cc0d2b6b8e3
[]
no_license
szymczykk/OpenMP_cwiczenia
ca07c4f3eb84808080258f971e47169cc66baa69
015423de691e31553162bccdff5d6b4b67e1ed43
refs/heads/master
2020-05-22T13:26:53.731599
2019-05-13T06:36:56
2019-05-13T06:36:56
186,359,967
0
0
null
null
null
null
UTF-8
C++
false
false
509
cc
#include <omp.h> #include <iostream> #include <thread> #include <chrono> using namespace std; void fun( int t ) { this_thread::sleep_for(chrono::seconds(t)); } int main () { // Wykonaj petle na czterech rownoleglych watkach // oraz tak dobierz opcje optymalizujaca wysylanie // kolejnych iteracji do watkow, zeby liczylo sie to // istotnie szybciej, niz w przypadku domyslnej strategii #pragma omp parallel for schedule(static,1) num_threads(4) for (int i=0; i<16; ++i) fun(i); }
[ "szymczyk.k@gmail.com" ]
szymczyk.k@gmail.com
3c788bfa5191cf3d3e6a6459be79446cfb3c9a8d
54e13f0f3296414e20a0644610b9e56244ce3a38
/tests/test_knights_tour.cpp
e09ec1b51aace91700b21bb80c0fc2e9178f01b6
[]
no_license
kevinludwig/knights-tour
143ecfebf335868db74ed4116c31349cddf77c2d
0cc9367b4d45147496502b7f8a7ecfb9a4da8763
refs/heads/master
2020-03-23T03:02:18.581252
2018-07-16T23:49:15
2018-07-16T23:49:15
141,005,881
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
#define BOOST_TEST_MODULE TestKT #include <boost/test/included/unit_test.hpp> #include "../src/utils.h" #include "../src/game_state.h" #include "../src/unvisited_degree.h" #include "../src/squares.h" BOOST_AUTO_TEST_CASE(test_bit_num) { BOOST_CHECK_EQUAL(bit_num(1), 0); BOOST_CHECK_EQUAL(bit_num(2), 1); BOOST_CHECK_EQUAL(bit_num(4), 2); BOOST_CHECK_EQUAL(bit_num(1UL << 52), 52); } BOOST_AUTO_TEST_CASE(test_unvisited_degree) { const game_state gs = game_state(A1); BOOST_CHECK_EQUAL(unvisited_degree(gs)(A1, C1), true); BOOST_CHECK_EQUAL(unvisited_degree(gs)(E4, E1), false); } BOOST_AUTO_TEST_CASE(test_game_state_generate_moves) { BOOST_CHECK_EQUAL(game_state(E4).generate_moves().size(), 8); BOOST_CHECK_EQUAL(game_state(A1).generate_moves().size(), 2); }
[ "kevin.ludwig@gmail.com" ]
kevin.ludwig@gmail.com
1a29dfaf9550d23d22c118e1b696004d296714ee
c8e0a03408ff2b92b91020e2e3ea34784740f565
/Rng.h
d86dcb6426f05ab63eff61888265928cd894aa03
[]
no_license
Mequam/wakyrace
644c1497508941151e8408af184a56a7a8bed4eb
3b7fcbd4c3f7a082e62cccfd960fe4be805e1fbb
refs/heads/master
2020-05-14T21:25:33.850782
2019-04-17T20:24:13
2019-04-17T20:24:13
181,962,895
0
0
null
null
null
null
UTF-8
C++
false
false
747
h
#include <cstdlib> #include <ctime> //#include <iostream> using namespace std; class Rng { private: long StartTime = time(0); public: Rng(); //returns a random number between str and end, INCLUDING str and end int Range(int str=1, int end=6) { if((end-str) >= 1) { this -> StartTime += 1; srand(StartTime); return ((rand() % ((end-str) + 1)) + str); } else { return -1; } } //returns true Perc percent of the times it is called bool Percent(int Perc) { if (Perc >= 100) { return true; } else if (Perc <= 0) { return false; } else if (Range(0,100) <= Perc) { return true; } else { //if you manage to get down here, you rolled an i :P return false; } } }; Rng::Rng() {}
[ "blue9ja@gmail.com" ]
blue9ja@gmail.com
b8b81dcf6b79c4d32cd0ff71d12846f55fc736cc
3d55a6e42b656fff6b1e41148d195983e18d1aea
/Data Structure practice/Heaps and Priority Queue/Merge k sorted arrays.cpp
f3bd61bfe6380556d6bffca41a6392621f7f67d3
[]
no_license
sunny2028/DS-IN-CPP
9d5aacc645fa60055d73072f5b1f4109e42c1244
7f888d119531cc0e5a75a2601772c12c66c51ea8
refs/heads/master
2020-04-18T14:26:38.373085
2019-01-25T17:57:48
2019-01-25T17:57:48
167,588,839
0
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
#include<bits/stdc++.h> using namespace std; struct person { int arr; int nextindex; int value; }; struct check { bool operator()(person &p1,person &p2) { return p1.value>=p2.value; } }; #define n 4 vector<int> mergeksortedarray( vector<vector<int> > arr) { priority_queue<person,vector<person>,check>p; person obj; for(int i=0;i<arr.size();i++) { obj.arr=i; obj.nextindex=1; obj.value=arr[i][0]; p.push(obj); } vector<int>arr1; int index=0; while(!p.empty()) { obj=p.top(); arr1.push_back(obj.value); int a=obj.arr; int j=obj.nextindex; p.pop(); if(j<arr[a].size()) { obj.arr=a; obj.nextindex=j+1; obj.value=arr[a][j]; p.push(obj); } } return arr1; } void printArray(vector<int>a) { for(int i=0;i<a.size();i++) { cout<<a[i]<<" "; } } int main() { vector<vector<int> >arr; int a[]= { 2, 6, 12 }; int b[]={ 1, 9 }; int c[]={ 23, 34, 90, 2000 }; vector<int>a1(a,a+3); vector<int>a2(b,b+2); vector<int>a3(c,c+4); arr.push_back(a1); arr.push_back(a2); arr.push_back(a3); vector<int>output = mergeksortedarray(arr); cout << "Merged array is " << endl; printArray(output); return 0; }
[ "rajatrock722@gmail.com" ]
rajatrock722@gmail.com
34d34b72eb24790545e31d899dc5acf0deee0dff
ce4392b47128e9f17f9da8912ae273d604438c26
/ModeC/ModeC.cpp
b412f4244c60e942953e1da8ffdb00363cafa7f1
[]
no_license
jakesjacob/1620_Project_car_dashboard
a6a804ae5f2f2be3d6846df083a1c52d3eb987c1
01327d2413e9098b42639ebd854d0b0a518c3de0
refs/heads/master
2023-03-15T10:37:44.557329
2021-03-16T10:58:55
2021-03-16T10:58:55
348,313,136
0
0
null
null
null
null
UTF-8
C++
false
false
1,927
cpp
#include "ModeC.h" #include "mbed.h" #include "Tone.h" Tone dac(p18); void mode_C() { lcd.clear(); lcd.printString("Mode C",0,0); lcd.refresh(); wait_ms(250); // small delay to prevent previous press being detected again dac.init(); while (button_c.read() == 0) { lcd.clear(); lcd.printString("Mode C",0,0); lcd.drawRect(0,24,60,6,FILL_TRANSPARENT); // Drawing the empty rectangles for bar levels float pot0_val = pot_0.read(); // returns a float in the range 0.0 to 1.0 int width0 = int(pot0_val*60.0f); // convert to an int in the range 0.0 to 60.0 lcd.drawRect(1,24,width0,6,FILL_BLACK); // draws a filled in rectangle with variabkle width relative to pot values float distance = int(pot0_val*200.0f); // converts pot value into a value between 0 - 200 printf("Distance (cm) = %.2f %\n",distance); // sends values to coolterm lcd.printString("Distance",0,2); // prints strings above bar graphs on lcd int sprite_dist[8][12] = { { 0,0,0,0,0,0,0,0,0,0,1,1 }, { 0,0,0,0,1,1,0,0,0,0,1,1 }, { 1,1,1,1,1,1,1,0,0,0,1,1 }, { 1,1,1,1,1,1,1,1,0,0,1,1 }, { 1,1,1,1,1,1,1,1,0,0,1,1 }, { 1,1,1,1,1,1,1,0,0,0,1,1 }, { 0,0,0,0,1,1,0,0,0,0,1,1 }, { 0,0,0,0,0,0,0,0,0,0,1,1 }, }; lcd.drawSprite(68,23,8,12,(int *)sprite_dist); //warning lights if (distance < 20.0f) { red_led.write(0); } else if (distance > 20.0f) { red_led.write(1); } dac.play(1000.f,0.1f); wait(pot0_val*0.5f); // update the LCD lcd.refresh(); // small delay between readings //wait(0.2); } }
[ "33692879+jakesjacob@users.noreply.github.com" ]
33692879+jakesjacob@users.noreply.github.com
fd0557f5b7a3ed07fc3c06619025ada93fbe793d
bb9b83b2526d3ff8a932a1992885a3fac7ee064d
/src/modules/osg/generated_code/Texture1D.pypp.cpp
0bd61b18a824b27728487bea67baadc7dfb1bc8e
[]
no_license
JaneliaSciComp/osgpyplusplus
4ceb65237772fe6686ddc0805b8c77d7b4b61b40
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
refs/heads/master
2021-01-10T19:12:31.756663
2015-09-09T19:10:16
2015-09-09T19:10:16
23,578,052
20
7
null
null
null
null
UTF-8
C++
false
false
37,227
cpp
// This file has been generated by Py++. #include "boost/python.hpp" #include "wrap_osg.h" #include "wrap_referenced.h" #include "texture1d.pypp.hpp" namespace bp = boost::python; struct Texture1D_wrapper : osg::Texture1D, bp::wrapper< osg::Texture1D > { struct SubloadCallback_wrapper : osg::Texture1D::SubloadCallback, bp::wrapper< osg::Texture1D::SubloadCallback > { SubloadCallback_wrapper() : osg::Texture1D::SubloadCallback() , bp::wrapper< osg::Texture1D::SubloadCallback >(){ // null constructor } virtual void setThreadSafeRefUnref( bool threadSafe ) { if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) ) func_setThreadSafeRefUnref( threadSafe ); else{ this->osg::Referenced::setThreadSafeRefUnref( threadSafe ); } } void default_setThreadSafeRefUnref( bool threadSafe ) { osg::Referenced::setThreadSafeRefUnref( threadSafe ); } }; Texture1D_wrapper( ) : osg::Texture1D( ) , bp::wrapper< osg::Texture1D >(){ // null constructor } Texture1D_wrapper(::osg::Image * image ) : osg::Texture1D( boost::python::ptr(image) ) , bp::wrapper< osg::Texture1D >(){ // constructor } virtual void apply( ::osg::State & state ) const { if( bp::override func_apply = this->get_override( "apply" ) ) func_apply( boost::ref(state) ); else{ this->osg::Texture1D::apply( boost::ref(state) ); } } void default_apply( ::osg::State & state ) const { osg::Texture1D::apply( boost::ref(state) ); } virtual char const * className( ) const { if( bp::override func_className = this->get_override( "className" ) ) return func_className( ); else{ return this->osg::Texture1D::className( ); } } char const * default_className( ) const { return osg::Texture1D::className( ); } virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const { if( bp::override func_clone = this->get_override( "clone" ) ) return func_clone( boost::ref(copyop) ); else{ return this->osg::Texture1D::clone( boost::ref(copyop) ); } } ::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const { return osg::Texture1D::clone( boost::ref(copyop) ); } virtual ::osg::Object * cloneType( ) const { if( bp::override func_cloneType = this->get_override( "cloneType" ) ) return func_cloneType( ); else{ return this->osg::Texture1D::cloneType( ); } } ::osg::Object * default_cloneType( ) const { return osg::Texture1D::cloneType( ); } virtual ::osg::Image * getImage( unsigned int arg0 ) { if( bp::override func_getImage = this->get_override( "getImage" ) ) return func_getImage( arg0 ); else{ return this->osg::Texture1D::getImage( arg0 ); } } ::osg::Image * default_getImage( unsigned int arg0 ) { return osg::Texture1D::getImage( arg0 ); } virtual ::osg::Image const * getImage( unsigned int arg0 ) const { if( bp::override func_getImage = this->get_override( "getImage" ) ) return func_getImage( arg0 ); else{ return this->osg::Texture1D::getImage( arg0 ); } } ::osg::Image const * default_getImage( unsigned int arg0 ) const { return osg::Texture1D::getImage( arg0 ); } virtual unsigned int getNumImages( ) const { if( bp::override func_getNumImages = this->get_override( "getNumImages" ) ) return func_getNumImages( ); else{ return this->osg::Texture1D::getNumImages( ); } } unsigned int default_getNumImages( ) const { return osg::Texture1D::getNumImages( ); } virtual int getTextureDepth( ) const { if( bp::override func_getTextureDepth = this->get_override( "getTextureDepth" ) ) return func_getTextureDepth( ); else{ return this->osg::Texture1D::getTextureDepth( ); } } int default_getTextureDepth( ) const { return osg::Texture1D::getTextureDepth( ); } virtual int getTextureHeight( ) const { if( bp::override func_getTextureHeight = this->get_override( "getTextureHeight" ) ) return func_getTextureHeight( ); else{ return this->osg::Texture1D::getTextureHeight( ); } } int default_getTextureHeight( ) const { return osg::Texture1D::getTextureHeight( ); } virtual ::GLenum getTextureTarget( ) const { if( bp::override func_getTextureTarget = this->get_override( "getTextureTarget" ) ) return func_getTextureTarget( ); else{ return this->osg::Texture1D::getTextureTarget( ); } } ::GLenum default_getTextureTarget( ) const { return osg::Texture1D::getTextureTarget( ); } virtual int getTextureWidth( ) const { if( bp::override func_getTextureWidth = this->get_override( "getTextureWidth" ) ) return func_getTextureWidth( ); else{ return this->osg::Texture1D::getTextureWidth( ); } } int default_getTextureWidth( ) const { return osg::Texture1D::getTextureWidth( ); } virtual ::osg::StateAttribute::Type getType( ) const { if( bp::override func_getType = this->get_override( "getType" ) ) return func_getType( ); else{ return this->osg::Texture1D::getType( ); } } ::osg::StateAttribute::Type default_getType( ) const { return osg::Texture1D::getType( ); } virtual bool isSameKindAs( ::osg::Object const * obj ) const { if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) ) return func_isSameKindAs( boost::python::ptr(obj) ); else{ return this->osg::Texture1D::isSameKindAs( boost::python::ptr(obj) ); } } bool default_isSameKindAs( ::osg::Object const * obj ) const { return osg::Texture1D::isSameKindAs( boost::python::ptr(obj) ); } virtual char const * libraryName( ) const { if( bp::override func_libraryName = this->get_override( "libraryName" ) ) return func_libraryName( ); else{ return this->osg::Texture1D::libraryName( ); } } char const * default_libraryName( ) const { return osg::Texture1D::libraryName( ); } virtual void setImage( unsigned int arg0, ::osg::Image * image ) { if( bp::override func_setImage = this->get_override( "setImage" ) ) func_setImage( arg0, boost::python::ptr(image) ); else{ this->osg::Texture1D::setImage( arg0, boost::python::ptr(image) ); } } void default_setImage( unsigned int arg0, ::osg::Image * image ) { osg::Texture1D::setImage( arg0, boost::python::ptr(image) ); } virtual ::osg::Texture * asTexture( ) { if( bp::override func_asTexture = this->get_override( "asTexture" ) ) return func_asTexture( ); else{ return this->osg::Texture::asTexture( ); } } ::osg::Texture * default_asTexture( ) { return osg::Texture::asTexture( ); } virtual ::osg::Texture const * asTexture( ) const { if( bp::override func_asTexture = this->get_override( "asTexture" ) ) return func_asTexture( ); else{ return this->osg::Texture::asTexture( ); } } ::osg::Texture const * default_asTexture( ) const { return osg::Texture::asTexture( ); } virtual bool checkValidityOfAssociatedModes( ::osg::State & arg0 ) const { if( bp::override func_checkValidityOfAssociatedModes = this->get_override( "checkValidityOfAssociatedModes" ) ) return func_checkValidityOfAssociatedModes( boost::ref(arg0) ); else{ return this->osg::StateAttribute::checkValidityOfAssociatedModes( boost::ref(arg0) ); } } bool default_checkValidityOfAssociatedModes( ::osg::State & arg0 ) const { return osg::StateAttribute::checkValidityOfAssociatedModes( boost::ref(arg0) ); } virtual void compileGLObjects( ::osg::State & state ) const { if( bp::override func_compileGLObjects = this->get_override( "compileGLObjects" ) ) func_compileGLObjects( boost::ref(state) ); else{ this->osg::Texture::compileGLObjects( boost::ref(state) ); } } void default_compileGLObjects( ::osg::State & state ) const { osg::Texture::compileGLObjects( boost::ref(state) ); } virtual void computeDataVariance( ) { if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) ) func_computeDataVariance( ); else{ this->osg::Object::computeDataVariance( ); } } void default_computeDataVariance( ) { osg::Object::computeDataVariance( ); } virtual unsigned int getMember( ) const { if( bp::override func_getMember = this->get_override( "getMember" ) ) return func_getMember( ); else{ return this->osg::StateAttribute::getMember( ); } } unsigned int default_getMember( ) const { return osg::StateAttribute::getMember( ); } virtual bool getModeUsage( ::osg::StateAttribute::ModeUsage & usage ) const { if( bp::override func_getModeUsage = this->get_override( "getModeUsage" ) ) return func_getModeUsage( boost::ref(usage) ); else{ return this->osg::Texture::getModeUsage( boost::ref(usage) ); } } bool default_getModeUsage( ::osg::StateAttribute::ModeUsage & usage ) const { return osg::Texture::getModeUsage( boost::ref(usage) ); } virtual ::osg::Referenced * getUserData( ) { if( bp::override func_getUserData = this->get_override( "getUserData" ) ) return func_getUserData( ); else{ return this->osg::Object::getUserData( ); } } ::osg::Referenced * default_getUserData( ) { return osg::Object::getUserData( ); } virtual ::osg::Referenced const * getUserData( ) const { if( bp::override func_getUserData = this->get_override( "getUserData" ) ) return func_getUserData( ); else{ return this->osg::Object::getUserData( ); } } ::osg::Referenced const * default_getUserData( ) const { return osg::Object::getUserData( ); } virtual bool isTextureAttribute( ) const { if( bp::override func_isTextureAttribute = this->get_override( "isTextureAttribute" ) ) return func_isTextureAttribute( ); else{ return this->osg::Texture::isTextureAttribute( ); } } bool default_isTextureAttribute( ) const { return osg::Texture::isTextureAttribute( ); } virtual void resizeGLObjectBuffers( unsigned int maxSize ) { if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) ) func_resizeGLObjectBuffers( maxSize ); else{ this->osg::Texture::resizeGLObjectBuffers( maxSize ); } } void default_resizeGLObjectBuffers( unsigned int maxSize ) { osg::Texture::resizeGLObjectBuffers( maxSize ); } virtual void setName( ::std::string const & name ) { if( bp::override func_setName = this->get_override( "setName" ) ) func_setName( name ); else{ this->osg::Object::setName( name ); } } void default_setName( ::std::string const & name ) { osg::Object::setName( name ); } virtual void setThreadSafeRefUnref( bool threadSafe ) { if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) ) func_setThreadSafeRefUnref( threadSafe ); else{ this->osg::Object::setThreadSafeRefUnref( threadSafe ); } } void default_setThreadSafeRefUnref( bool threadSafe ) { osg::Object::setThreadSafeRefUnref( threadSafe ); } virtual void setUserData( ::osg::Referenced * obj ) { if( bp::override func_setUserData = this->get_override( "setUserData" ) ) func_setUserData( boost::python::ptr(obj) ); else{ this->osg::Object::setUserData( boost::python::ptr(obj) ); } } void default_setUserData( ::osg::Referenced * obj ) { osg::Object::setUserData( boost::python::ptr(obj) ); } }; void register_Texture1D_class(){ { //::osg::Texture1D typedef bp::class_< Texture1D_wrapper, bp::bases< osg::Texture >, osg::ref_ptr< ::osg::Texture1D >, boost::noncopyable > Texture1D_exposer_t; Texture1D_exposer_t Texture1D_exposer = Texture1D_exposer_t( "Texture1D", "\n Encapsulates OpenGL 1D texture functionality. Doesnt support cube maps,\n so ignore C{face} parameters.\n", bp::no_init ); bp::scope Texture1D_scope( Texture1D_exposer ); bp::class_< Texture1D_wrapper::SubloadCallback_wrapper, bp::bases< osg::Referenced >, osg::ref_ptr< Texture1D_wrapper::SubloadCallback_wrapper >, boost::noncopyable >( "SubloadCallback", bp::no_init ) .def( "setThreadSafeRefUnref" , (void ( ::osg::Referenced::* )( bool ))(&::osg::Referenced::setThreadSafeRefUnref) , (void ( Texture1D_wrapper::SubloadCallback_wrapper::* )( bool ))(&Texture1D_wrapper::SubloadCallback_wrapper::default_setThreadSafeRefUnref) , ( bp::arg("threadSafe") ) ); Texture1D_exposer.def( bp::init< >("\n Encapsulates OpenGL 1D texture functionality. Doesnt support cube maps,\n so ignore C{face} parameters.\n") ); Texture1D_exposer.def( bp::init< osg::Image * >(( bp::arg("image") )) ); bp::implicitly_convertible< osg::Image *, osg::Texture1D >(); { //::osg::Texture1D::apply typedef void ( ::osg::Texture1D::*apply_function_type)( ::osg::State & ) const; typedef void ( Texture1D_wrapper::*default_apply_function_type)( ::osg::State & ) const; Texture1D_exposer.def( "apply" , apply_function_type(&::osg::Texture1D::apply) , default_apply_function_type(&Texture1D_wrapper::default_apply) , ( bp::arg("state") ) ); } { //::osg::Texture1D::className typedef char const * ( ::osg::Texture1D::*className_function_type)( ) const; typedef char const * ( Texture1D_wrapper::*default_className_function_type)( ) const; Texture1D_exposer.def( "className" , className_function_type(&::osg::Texture1D::className) , default_className_function_type(&Texture1D_wrapper::default_className) ); } { //::osg::Texture1D::clone typedef ::osg::Object * ( ::osg::Texture1D::*clone_function_type)( ::osg::CopyOp const & ) const; typedef ::osg::Object * ( Texture1D_wrapper::*default_clone_function_type)( ::osg::CopyOp const & ) const; Texture1D_exposer.def( "clone" , clone_function_type(&::osg::Texture1D::clone) , default_clone_function_type(&Texture1D_wrapper::default_clone) , ( bp::arg("copyop") ) , bp::return_value_policy< bp::reference_existing_object >() ); } { //::osg::Texture1D::cloneType typedef ::osg::Object * ( ::osg::Texture1D::*cloneType_function_type)( ) const; typedef ::osg::Object * ( Texture1D_wrapper::*default_cloneType_function_type)( ) const; Texture1D_exposer.def( "cloneType" , cloneType_function_type(&::osg::Texture1D::cloneType) , default_cloneType_function_type(&Texture1D_wrapper::default_cloneType) , bp::return_value_policy< bp::reference_existing_object >() ); } { //::osg::Texture1D::copyTexImage1D typedef void ( ::osg::Texture1D::*copyTexImage1D_function_type)( ::osg::State &,int,int,int ) ; Texture1D_exposer.def( "copyTexImage1D" , copyTexImage1D_function_type( &::osg::Texture1D::copyTexImage1D ) , ( bp::arg("state"), bp::arg("x"), bp::arg("y"), bp::arg("width") ) , " Copies pixels into a 1D texture image, as per glCopyTexImage1D.\n Creates an OpenGL texture object from the current OpenGL background\n framebuffer contents at position C{x,} C{y} with width C{width.}\n C{width} must be a power of two." ); } { //::osg::Texture1D::copyTexSubImage1D typedef void ( ::osg::Texture1D::*copyTexSubImage1D_function_type)( ::osg::State &,int,int,int,int ) ; Texture1D_exposer.def( "copyTexSubImage1D" , copyTexSubImage1D_function_type( &::osg::Texture1D::copyTexSubImage1D ) , ( bp::arg("state"), bp::arg("xoffset"), bp::arg("x"), bp::arg("y"), bp::arg("width") ) , " Copies a one-dimensional texture subimage, as per\n glCopyTexSubImage1D. Updates a portion of an existing OpenGL\n texture object from the current OpenGL background framebuffer\n contents at position C{x,} C{y} with width C{width.}" ); } { //::osg::Texture1D::getImage typedef ::osg::Image * ( ::osg::Texture1D::*getImage_function_type)( ) ; Texture1D_exposer.def( "getImage" , getImage_function_type( &::osg::Texture1D::getImage ) , bp::return_internal_reference< >() , " Gets the texture image." ); } { //::osg::Texture1D::getImage typedef ::osg::Image const * ( ::osg::Texture1D::*getImage_function_type)( ) const; Texture1D_exposer.def( "getImage" , getImage_function_type( &::osg::Texture1D::getImage ) , bp::return_internal_reference< >() , " Gets the const texture image." ); } { //::osg::Texture1D::getImage typedef ::osg::Image * ( ::osg::Texture1D::*getImage_function_type)( unsigned int ) ; typedef ::osg::Image * ( Texture1D_wrapper::*default_getImage_function_type)( unsigned int ) ; Texture1D_exposer.def( "getImage" , getImage_function_type(&::osg::Texture1D::getImage) , default_getImage_function_type(&Texture1D_wrapper::default_getImage) , ( bp::arg("arg0") ) , bp::return_internal_reference< >() ); } { //::osg::Texture1D::getImage typedef ::osg::Image const * ( ::osg::Texture1D::*getImage_function_type)( unsigned int ) const; typedef ::osg::Image const * ( Texture1D_wrapper::*default_getImage_function_type)( unsigned int ) const; Texture1D_exposer.def( "getImage" , getImage_function_type(&::osg::Texture1D::getImage) , default_getImage_function_type(&Texture1D_wrapper::default_getImage) , ( bp::arg("arg0") ) , bp::return_internal_reference< >() ); } { //::osg::Texture1D::getModifiedCount typedef unsigned int & ( ::osg::Texture1D::*getModifiedCount_function_type)( unsigned int ) const; Texture1D_exposer.def( "getModifiedCount" , getModifiedCount_function_type( &::osg::Texture1D::getModifiedCount ) , ( bp::arg("contextID") ) , bp::return_value_policy< bp::copy_non_const_reference >() ); } { //::osg::Texture1D::getNumImages typedef unsigned int ( ::osg::Texture1D::*getNumImages_function_type)( ) const; typedef unsigned int ( Texture1D_wrapper::*default_getNumImages_function_type)( ) const; Texture1D_exposer.def( "getNumImages" , getNumImages_function_type(&::osg::Texture1D::getNumImages) , default_getNumImages_function_type(&Texture1D_wrapper::default_getNumImages) ); } { //::osg::Texture1D::getNumMipmapLevels typedef unsigned int ( ::osg::Texture1D::*getNumMipmapLevels_function_type)( ) const; Texture1D_exposer.def( "getNumMipmapLevels" , getNumMipmapLevels_function_type( &::osg::Texture1D::getNumMipmapLevels ) , " Gets the number of mipmap levels created." ); } { //::osg::Texture1D::getSubloadCallback typedef ::osg::Texture1D::SubloadCallback * ( ::osg::Texture1D::*getSubloadCallback_function_type)( ) ; Texture1D_exposer.def( "getSubloadCallback" , getSubloadCallback_function_type( &::osg::Texture1D::getSubloadCallback ) , bp::return_internal_reference< >() ); } { //::osg::Texture1D::getSubloadCallback typedef ::osg::Texture1D::SubloadCallback const * ( ::osg::Texture1D::*getSubloadCallback_function_type)( ) const; Texture1D_exposer.def( "getSubloadCallback" , getSubloadCallback_function_type( &::osg::Texture1D::getSubloadCallback ) , bp::return_internal_reference< >() ); } { //::osg::Texture1D::getTextureDepth typedef int ( ::osg::Texture1D::*getTextureDepth_function_type)( ) const; typedef int ( Texture1D_wrapper::*default_getTextureDepth_function_type)( ) const; Texture1D_exposer.def( "getTextureDepth" , getTextureDepth_function_type(&::osg::Texture1D::getTextureDepth) , default_getTextureDepth_function_type(&Texture1D_wrapper::default_getTextureDepth) ); } { //::osg::Texture1D::getTextureHeight typedef int ( ::osg::Texture1D::*getTextureHeight_function_type)( ) const; typedef int ( Texture1D_wrapper::*default_getTextureHeight_function_type)( ) const; Texture1D_exposer.def( "getTextureHeight" , getTextureHeight_function_type(&::osg::Texture1D::getTextureHeight) , default_getTextureHeight_function_type(&Texture1D_wrapper::default_getTextureHeight) ); } { //::osg::Texture1D::getTextureTarget typedef ::GLenum ( ::osg::Texture1D::*getTextureTarget_function_type)( ) const; typedef ::GLenum ( Texture1D_wrapper::*default_getTextureTarget_function_type)( ) const; Texture1D_exposer.def( "getTextureTarget" , getTextureTarget_function_type(&::osg::Texture1D::getTextureTarget) , default_getTextureTarget_function_type(&Texture1D_wrapper::default_getTextureTarget) ); } { //::osg::Texture1D::getTextureWidth typedef int ( ::osg::Texture1D::*getTextureWidth_function_type)( ) const; typedef int ( Texture1D_wrapper::*default_getTextureWidth_function_type)( ) const; Texture1D_exposer.def( "getTextureWidth" , getTextureWidth_function_type(&::osg::Texture1D::getTextureWidth) , default_getTextureWidth_function_type(&Texture1D_wrapper::default_getTextureWidth) ); } { //::osg::Texture1D::getType typedef ::osg::StateAttribute::Type ( ::osg::Texture1D::*getType_function_type)( ) const; typedef ::osg::StateAttribute::Type ( Texture1D_wrapper::*default_getType_function_type)( ) const; Texture1D_exposer.def( "getType" , getType_function_type(&::osg::Texture1D::getType) , default_getType_function_type(&Texture1D_wrapper::default_getType) ); } { //::osg::Texture1D::isSameKindAs typedef bool ( ::osg::Texture1D::*isSameKindAs_function_type)( ::osg::Object const * ) const; typedef bool ( Texture1D_wrapper::*default_isSameKindAs_function_type)( ::osg::Object const * ) const; Texture1D_exposer.def( "isSameKindAs" , isSameKindAs_function_type(&::osg::Texture1D::isSameKindAs) , default_isSameKindAs_function_type(&Texture1D_wrapper::default_isSameKindAs) , ( bp::arg("obj") ) ); } { //::osg::Texture1D::libraryName typedef char const * ( ::osg::Texture1D::*libraryName_function_type)( ) const; typedef char const * ( Texture1D_wrapper::*default_libraryName_function_type)( ) const; Texture1D_exposer.def( "libraryName" , libraryName_function_type(&::osg::Texture1D::libraryName) , default_libraryName_function_type(&Texture1D_wrapper::default_libraryName) ); } { //::osg::Texture1D::setImage typedef void ( ::osg::Texture1D::*setImage_function_type)( ::osg::Image * ) ; Texture1D_exposer.def( "setImage" , setImage_function_type( &::osg::Texture1D::setImage ) , ( bp::arg("image") ) , " Sets the texture image." ); } { //::osg::Texture1D::setImage typedef void ( ::osg::Texture1D::*setImage_function_type)( unsigned int,::osg::Image * ) ; typedef void ( Texture1D_wrapper::*default_setImage_function_type)( unsigned int,::osg::Image * ) ; Texture1D_exposer.def( "setImage" , setImage_function_type(&::osg::Texture1D::setImage) , default_setImage_function_type(&Texture1D_wrapper::default_setImage) , ( bp::arg("arg0"), bp::arg("image") ) ); } { //::osg::Texture1D::setNumMipmapLevels typedef void ( ::osg::Texture1D::*setNumMipmapLevels_function_type)( unsigned int ) const; Texture1D_exposer.def( "setNumMipmapLevels" , setNumMipmapLevels_function_type( &::osg::Texture1D::setNumMipmapLevels ) , ( bp::arg("num") ) , " Helper function. Sets the number of mipmap levels created for this\n texture. Should only be called within an osg::Texture::apply(), or\n during a custom OpenGL texture load." ); } { //::osg::Texture1D::setSubloadCallback typedef void ( ::osg::Texture1D::*setSubloadCallback_function_type)( ::osg::Texture1D::SubloadCallback * ) ; Texture1D_exposer.def( "setSubloadCallback" , setSubloadCallback_function_type( &::osg::Texture1D::setSubloadCallback ) , ( bp::arg("cb") ) ); } { //::osg::Texture1D::setTextureWidth typedef void ( ::osg::Texture1D::*setTextureWidth_function_type)( int ) ; Texture1D_exposer.def( "setTextureWidth" , setTextureWidth_function_type( &::osg::Texture1D::setTextureWidth ) , ( bp::arg("width") ) , " Sets the texture width. If width is zero, calculate the value\n from the source image width." ); } { //::osg::Texture::asTexture typedef ::osg::Texture * ( ::osg::Texture::*asTexture_function_type)( ) ; typedef ::osg::Texture * ( Texture1D_wrapper::*default_asTexture_function_type)( ) ; Texture1D_exposer.def( "asTexture" , asTexture_function_type(&::osg::Texture::asTexture) , default_asTexture_function_type(&Texture1D_wrapper::default_asTexture) , bp::return_internal_reference< >() ); } { //::osg::Texture::asTexture typedef ::osg::Texture const * ( ::osg::Texture::*asTexture_function_type)( ) const; typedef ::osg::Texture const * ( Texture1D_wrapper::*default_asTexture_function_type)( ) const; Texture1D_exposer.def( "asTexture" , asTexture_function_type(&::osg::Texture::asTexture) , default_asTexture_function_type(&Texture1D_wrapper::default_asTexture) , bp::return_internal_reference< >() ); } { //::osg::StateAttribute::checkValidityOfAssociatedModes typedef bool ( ::osg::StateAttribute::*checkValidityOfAssociatedModes_function_type)( ::osg::State & ) const; typedef bool ( Texture1D_wrapper::*default_checkValidityOfAssociatedModes_function_type)( ::osg::State & ) const; Texture1D_exposer.def( "checkValidityOfAssociatedModes" , checkValidityOfAssociatedModes_function_type(&::osg::StateAttribute::checkValidityOfAssociatedModes) , default_checkValidityOfAssociatedModes_function_type(&Texture1D_wrapper::default_checkValidityOfAssociatedModes) , ( bp::arg("arg0") ) ); } { //::osg::Texture::compileGLObjects typedef void ( ::osg::Texture::*compileGLObjects_function_type)( ::osg::State & ) const; typedef void ( Texture1D_wrapper::*default_compileGLObjects_function_type)( ::osg::State & ) const; Texture1D_exposer.def( "compileGLObjects" , compileGLObjects_function_type(&::osg::Texture::compileGLObjects) , default_compileGLObjects_function_type(&Texture1D_wrapper::default_compileGLObjects) , ( bp::arg("state") ) ); } { //::osg::Object::computeDataVariance typedef void ( ::osg::Object::*computeDataVariance_function_type)( ) ; typedef void ( Texture1D_wrapper::*default_computeDataVariance_function_type)( ) ; Texture1D_exposer.def( "computeDataVariance" , computeDataVariance_function_type(&::osg::Object::computeDataVariance) , default_computeDataVariance_function_type(&Texture1D_wrapper::default_computeDataVariance) ); } { //::osg::StateAttribute::getMember typedef unsigned int ( ::osg::StateAttribute::*getMember_function_type)( ) const; typedef unsigned int ( Texture1D_wrapper::*default_getMember_function_type)( ) const; Texture1D_exposer.def( "getMember" , getMember_function_type(&::osg::StateAttribute::getMember) , default_getMember_function_type(&Texture1D_wrapper::default_getMember) ); } { //::osg::Texture::getModeUsage typedef bool ( ::osg::Texture::*getModeUsage_function_type)( ::osg::StateAttribute::ModeUsage & ) const; typedef bool ( Texture1D_wrapper::*default_getModeUsage_function_type)( ::osg::StateAttribute::ModeUsage & ) const; Texture1D_exposer.def( "getModeUsage" , getModeUsage_function_type(&::osg::Texture::getModeUsage) , default_getModeUsage_function_type(&Texture1D_wrapper::default_getModeUsage) , ( bp::arg("usage") ) ); } { //::osg::Object::getUserData typedef ::osg::Referenced * ( ::osg::Object::*getUserData_function_type)( ) ; typedef ::osg::Referenced * ( Texture1D_wrapper::*default_getUserData_function_type)( ) ; Texture1D_exposer.def( "getUserData" , getUserData_function_type(&::osg::Object::getUserData) , default_getUserData_function_type(&Texture1D_wrapper::default_getUserData) , bp::return_internal_reference< >() ); } { //::osg::Object::getUserData typedef ::osg::Referenced const * ( ::osg::Object::*getUserData_function_type)( ) const; typedef ::osg::Referenced const * ( Texture1D_wrapper::*default_getUserData_function_type)( ) const; Texture1D_exposer.def( "getUserData" , getUserData_function_type(&::osg::Object::getUserData) , default_getUserData_function_type(&Texture1D_wrapper::default_getUserData) , bp::return_internal_reference< >() ); } { //::osg::Texture::isTextureAttribute typedef bool ( ::osg::Texture::*isTextureAttribute_function_type)( ) const; typedef bool ( Texture1D_wrapper::*default_isTextureAttribute_function_type)( ) const; Texture1D_exposer.def( "isTextureAttribute" , isTextureAttribute_function_type(&::osg::Texture::isTextureAttribute) , default_isTextureAttribute_function_type(&Texture1D_wrapper::default_isTextureAttribute) ); } { //::osg::Texture::resizeGLObjectBuffers typedef void ( ::osg::Texture::*resizeGLObjectBuffers_function_type)( unsigned int ) ; typedef void ( Texture1D_wrapper::*default_resizeGLObjectBuffers_function_type)( unsigned int ) ; Texture1D_exposer.def( "resizeGLObjectBuffers" , resizeGLObjectBuffers_function_type(&::osg::Texture::resizeGLObjectBuffers) , default_resizeGLObjectBuffers_function_type(&Texture1D_wrapper::default_resizeGLObjectBuffers) , ( bp::arg("maxSize") ) ); } { //::osg::Object::setName typedef void ( ::osg::Object::*setName_function_type)( ::std::string const & ) ; typedef void ( Texture1D_wrapper::*default_setName_function_type)( ::std::string const & ) ; Texture1D_exposer.def( "setName" , setName_function_type(&::osg::Object::setName) , default_setName_function_type(&Texture1D_wrapper::default_setName) , ( bp::arg("name") ) ); } { //::osg::Object::setName typedef void ( ::osg::Object::*setName_function_type)( char const * ) ; Texture1D_exposer.def( "setName" , setName_function_type( &::osg::Object::setName ) , ( bp::arg("name") ) , " Set the name of object using a C style string." ); } { //::osg::Object::setThreadSafeRefUnref typedef void ( ::osg::Object::*setThreadSafeRefUnref_function_type)( bool ) ; typedef void ( Texture1D_wrapper::*default_setThreadSafeRefUnref_function_type)( bool ) ; Texture1D_exposer.def( "setThreadSafeRefUnref" , setThreadSafeRefUnref_function_type(&::osg::Object::setThreadSafeRefUnref) , default_setThreadSafeRefUnref_function_type(&Texture1D_wrapper::default_setThreadSafeRefUnref) , ( bp::arg("threadSafe") ) ); } { //::osg::Object::setUserData typedef void ( ::osg::Object::*setUserData_function_type)( ::osg::Referenced * ) ; typedef void ( Texture1D_wrapper::*default_setUserData_function_type)( ::osg::Referenced * ) ; Texture1D_exposer.def( "setUserData" , setUserData_function_type(&::osg::Object::setUserData) , default_setUserData_function_type(&Texture1D_wrapper::default_setUserData) , ( bp::arg("obj") ) ); } } }
[ "brunsc@janelia.hhmi.org" ]
brunsc@janelia.hhmi.org
d2bc296732ba2d89f021a1d0523d6ba89107de6e
674f62b6f8a3540424c48fdc560a1902b94e7a5c
/src/FunctionDefs.h
8f6440005661e1c4c72f4c2b9cc85cc2fa715c26
[]
no_license
RichardOtt/Malleus
2574733247bac3d68019fc6e539cb58e34279d30
62e3b977eadb4bac932ba610066ad882e54c82ca
refs/heads/master
2016-09-06T11:20:43.013865
2012-07-25T22:39:59
2012-07-25T22:39:59
2,144,906
0
0
null
null
null
null
UTF-8
C++
false
false
2,198
h
/****** This contains the derived classes that define the functions used for Sys. They're all be inline, so no need for a .cxx file, but I put an empty one to be safe. The user will most likely need to alter this file at some point. Unfortunately, there's no error checking here, other than the usual compiler stuff - this is actual code. Ideally, one day I'll get away from this and handle it in a more user-friendly way. The couple of places you can trip up here are: 1. Forgetting to give the class (i.e. your function) a unique name 2. Forgetting to change the constructor name to that class name 3. Not updating nPars to match the actual number of parameters in Eval 4. Skipping values in the parameters array - i.e. having a function that looks like parameters[1] + parameters[3], which is missing both parameters[0] and parameters[2]. While technically OK (as long as nPars is 4), this can get you in trouble if you *think* you're only using 2 or 3 parameters, and don't call the right number of MCMCParameterValue and MCBranchValue in the config file (it should complain at run time). The ones named "AddConst", "MultiplyConst", "Linear" and "Resolution" come with the system, and work correctly. Use them as models if you're not sure. ******/ #include "RealFunction.h" #include "TMath.h" #include "TRandom3.h" #ifndef _FUNCTIONDEFS_H_ #define _FUNCTIONDEFS_H_ class AddConst : public RealFunction { public: AddConst() { nPars = 1; parameters = new Double_t[nPars]; } Double_t Eval() { return (parameters[0]); } }; class MultiplyConst : public RealFunction { public: MultiplyConst() { nPars = 2; parameters = new Double_t[nPars]; } Double_t Eval() { return (parameters[0]*parameters[1]); } }; class Linear : public RealFunction { public: Linear() { nPars = 3; parameters = new Double_t[nPars]; } Double_t Eval() { return (parameters[0] + parameters[1]*parameters[2]); } }; class Resolution : public RealFunction { public: Resolution() { nPars = 3; parameters = new Double_t[nPars]; } Double_t Eval() { return parameters[0]*(parameters[1] - parameters[2]); } }; #endif
[ "ott.richard@gmail.com" ]
ott.richard@gmail.com
9b0b82bb234dffb409dafe606182d764b66db485
380f7100ffbfd0d28dc2a6ebdeeeb085f36e1c9b
/vs2010/PSmile/PSmile/smile.h
2b2d83f55956d861cc63f787af024776bc7b34fb
[]
no_license
wenyachen/PSmile
fe81658c004e3fa41941e1620247f531f21faebc
133fddab16688158949d929ba2c999decfa0be8d
refs/heads/master
2021-01-18T00:26:41.739242
2012-09-22T16:16:39
2012-09-22T16:16:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,271
h
/* * smile detector. * * Original:Ian Fasel, Bret Fortenberry * Author:Kazuki Aisaka * Fixes: * * Copyright (c) 2005 Machine Perception Laboratory * University of California San Diego. * * 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 __SMILE_H__ #define __SMILE_H__ // // Define for Include // #define SMD_COMPILE_MAC (0) #define SMD_USE_VIMAGE (0) //// To use this, use "bjam debug" //#define SMD_USE_IMAGEMAGICK (1) #define SMD_USE_BLAS (0) // // Define for RUBI // #define SMD_USE_RUBI (0) #if SMD_USE_RUBI extern int vision_save_faceDetect_req; #endif // // Include // #include "eyefinderBinary.h" #include "interpolate.h" //#include "cluster.h" #if SMD_COMPILE_MAC #include <Carbon/Carbon.h> #endif #if SMD_USE_VIMAGE #include <Accelerate/Accelerate.h> #include </System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vImage.framework/Versions/A/Headers/Geometry.h> #endif #ifdef SMD_USE_IMAGEMAGICK #include <Magick++.h> using namespace std; using namespace Magick; #endif #if SMD_USE_BLAS #include <vecLib/vBLAS.h> #endif // // Define // // Err #define SMD_NO_ERR (0) #define SMD_ERR (1) #define SMD_NOT_SUPPORT (2) // CONSTANT VALUE #define SMD_GRAY_PIXEL_SIZE (1) #define SMD_GRAY_FLOAT_PIXEL_SIZE (4) #define SMD_RGB_PIXEL_SIZE (3) #define SMD_ARGB_PIXEL_SIZE (4) #define SMD_MAX_PIXEL_VALUE (255) #define SMD_FACE_SIZE (24) #define SMD_FACE_AREA_SIZE (576) // create facebox by eye position //#define SMD_PI (3.141592) #define SMD_PI ((double)3.14159265358979323846264338327950288419716939937510) #define SMD_360_DEGREE (360) #define SMD_EYE_LEN_RATE (0.50) #define SMD_EYE_LEFT_RATE (0.25) #define SMD_EYE_RIGHT_RATE (0.25) #define SMD_EYE_TOP_RATE (0.20) // Macro #define SMD_MAX(x,y) ( (x > y) ? (x) : (y) ) // Debug #define SMD_DO_PRINT (0) #define SMD_DO_TIME (0) #ifdef SMD_USE_IMAGEMAGICK #define SMD_DO_DUMP (0) #define SMD_DO_DUMP_FACE (0) #else #define SMD_DO_DUMP (0) #define SMD_DO_DUMP_FACE (0) #endif #define SMD_DO_DISPLAY (0) #define SMD_DO_LOG (0) #if SMD_DO_TIME #include <sys/time.h> double dSMDdifftv(timeval t1, timeval t0) { double s; double secs = t1.tv_sec - t0.tv_sec; double usecs = ((double)t1.tv_usec) - ((double)t0.tv_usec); usecs *= 1e-6; s = secs+usecs; return s; } #endif // // Struct // //struct SmileValue{ // int smileMax; // int smileTotal; // float smileMean; //}; // // Class, Smile Detector // class MPSmile : public MPISearchFaceDetector { public: MPSmile(); virtual ~MPSmile(); // // Find Smiles with EyeFinder & FaceDetector // // pixels: original image // faces: face information // WINSHIFT: window shift size for mpisearch // mode: mode for mpisearch // Return: error code (SMD_***) // int findSmiles( const RImage<float> &pixels, VisualObject &faces, float WINSHIFT=1, combine_mode mode=none ); // // Find Smiles with specified Eye Position // // pixels: original image // faces: face information // WINSHIFT: window shift size for mpisearch // mode: mode for mpisearch // fxleye: X Left Eye // fyleye: Y Left Eye // fxreye: X Right Eye // fyreye: Y Right Eye // Return: error code (SMD_***) // int findSmiles( const RImage<float> &pixels, VisualObject &faces, float fxleye, float fyleye, float fxreye, float fyreye, float WINSHIFT=1, combine_mode mode=none ); // // Find Smiles from Patch // // pixels: face image // faces: face information // WINSHIFT: window shift size for mpisearch // mode: mode for mpisearch // Return: error code (SMD_***) // int findSmilesFromPatch( const RImage<float> &pixels, VisualObject &faces, float WINSHIFT=1, combine_mode mode=none ); #ifdef SMD_USE_IMAGEMAGICK // // Find Smiles using ImageMagick // // pimage: ImageMagick image pointer // pVOFace: face information // WINSHIFT: window shift size for mpisearch // mode: mode for mpisearch // Return: error code (SMD_***) // int findSmiles( Image* pimage, VisualObject* pVOFaces, float WINSHIFT=1, combine_mode mode=none ); #endif // Overload the initStream and resetStream to do the eye detector virtual void initStream(const int width, const int height, double WINSHIFT=1.0); virtual void resetStream(const int width, const int height, double WINSHIFT=1.0); virtual void releaseStream(); protected: // // GetSmiles // int iGetSmiles( const RImage<float> &pixels, VisualObject &faces ); // // Search Smile // // pixels -- the image to be scanned // faces -- structure to store the detected objects (faces) // flags -- an array with a value corresponding to each window at all scales // output_values -- Stick the output of the classifier up to this point here // box -- flag to return the found face boxes. Set to 0 to get activation only. // Note: flags and output_values are being used during learning, only used from Matlab right now int iSearchSmile( const RImage<float> &pixels, FaceBoxList &face, int USE_BLOCK_FLAGS = 1, float WINSHIFT = 1.25, double* index_flags = NULL, double* output_values = NULL, int box = 1 ); #ifdef SMD_USE_IMAGEMAGICK // // Get Smiles using ImageMagick // int iGetSmiles( Image* pimage, const RImage<float> &pixels, VisualObject &faces ); // // Adjust FaceBox by using Eye Position // int iGetFaceFromEye( Image* pimage, float fxleye, float fyleye, float fxreye, float fyreye ); // ImageMagick Grayscale int iGrayscale_ImageMagick( Image* pimage ); // ImageMagick Crop int iCrop_ImageMagick( Image* pimage, int iWidth, int Height, int iXOffset, int iYOffset ); // ImageMagick Resize int iResize_ImageMagick( Image* pimage, int iWidth, int iHeight ); // ImageMagick Rotate int iRotate_ImageMagick( Image* pimage, double dAngle ); // ImageMagick Write Face Image to Buffer int iWrite_ImageMagick( Image* pimage, const RImage<float>* prPixels ); #endif // SMD_USE_IMAGEMAGICK #if SMD_DO_DUMP_FACE void vDumpFace( void ); #endif #if SMD_DO_DUMP void vDumpPixels( const RImage<float>* prPixels ); #endif private: // EyeFinder MPEyeFinder* m_pCEyeFinder; RImage<float>* m_prPixels; int m_iLastImgWidth; int m_iLastImgHeight; // SmileDetector RImage<float>* m_prFacePixels; //SmileValue m_rSmileVal; //double m_dActivation; // Interpolate CIntegralInterpolate<float>* m_pfCIntegInter; // Debug int m_iCount; }; #endif // __SMILE_H__ /* * * 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. * */
[ "chungbwc@gmail.com" ]
chungbwc@gmail.com
b0091ee15e180efeec55c3c5d2fcfeb3d61b9346
1990b25fee681bb022861bfd09ee718645338492
/AFS1200/QMain/app/frmmessagebox.h
8e4c048424c683dec5ee40ff8a7180f8bedea4ef
[]
no_license
waaaly/try-loveGit
e2db35db4b98df350480b87dd60589dff28cc771
d2e89fe695a2301237e0a32353d9acbd14b94fa3
refs/heads/master
2020-04-23T01:33:06.948645
2019-04-17T15:05:13
2019-04-17T15:05:13
170,816,307
9
2
null
null
null
null
UTF-8
C++
false
false
806
h
#ifndef FRMMESSAGEBOX_H #define FRMMESSAGEBOX_H #include <QDialog> #include <QMouseEvent> namespace Ui { class frmMessageBox; } class frmMessageBox : public QDialog { Q_OBJECT public: explicit frmMessageBox(QWidget *parent = 0); ~frmMessageBox(); void SetMessage(const QString &msg, int type); protected: //void mouseMoveEvent(QMouseEvent *e); //void mousePressEvent(QMouseEvent *e); //void mouseReleaseEvent(QMouseEvent *); private slots: void on_btnOk_clicked(); private: Ui::frmMessageBox *ui; QPoint mousePoint; //鼠标拖动自定义标题栏时的坐标 bool mousePressed; //鼠标是否按下 int isEN;//中文为 0 ,英文为 1 添加时间2018/09/18 signals: void beep() ; }; #endif // FRMMESSAGEBOX_H
[ "825887013@qq.com" ]
825887013@qq.com
33b3e490586b4b5b1e5d262e0222db9345945098
76e8272fc023f5a4977f839b62fbb8fbb3444fc8
/text_buffer.hpp
690813bc2eba9b416f16f771fd1c9a5c04656cbb
[]
no_license
Mateuszd6/theeditor
9c638695fdd61dbda4e931778e78e0ab5ecda278
9bc08eb4c27a5b5840829678d852fb54a9a244d8
refs/heads/master
2022-11-16T05:27:20.472503
2022-10-30T12:53:00
2022-10-30T12:53:00
162,849,060
1
0
null
null
null
null
UTF-8
C++
false
false
3,157
hpp
#ifndef TEXT_BUFFER_HPP #define TEXT_BUFFER_HPP #include "gap_buffer.hpp" #include "undo.hpp" #include "utf.hpp" #define TEXT_BUF_INITIAL_CAPACITY (256) struct text_buffer { gap_buffer* lines; mm capacity; mm gap_start; mm gap_end; undo_buffer undo_buf; void initialize(); void move_gap_to_point(mm point); void move_gap_to_buffer_end(); void grow_gap(); // _impl fucntions do the same as fucntions without the suffix, but does not // record undo state. Thus should only be used in the internal API. Regular // fucntions call these, and then if it succeeded, store info about the // operation in the undo buffer. std::tuple<bool, mm, mm> insert_character_impl(mm line, mm point, u32 character); std::tuple<bool, mm, mm> insert_range_impl(mm line, mm point, u32* begin, u32* end); std::tuple<bool, mm, mm> insert_newline_impl(mm line, mm point); // These fucntions are called by del_forward/del_backward and return the // deleted character. They assume very special scenarios so never call them. u32 del_forward_char_impl(mm line, mm point); u32 del_forward_newline_impl(mm line, mm point); u32 del_backward_char_impl(mm line, mm point); u32 del_backward_newline_impl(mm line, mm point); // All contents of the current line goes to the previous line. Current line // is removed. void delete_line_impl(mm line); std::tuple<bool, mm, mm> insert(mm line, mm point, u32* begin, u32* end); std::tuple<bool, mm, mm> del_forward(mm line, mm point); std::tuple<bool, mm, mm> del_backward(mm line, mm point); mm size() const; mm gap_size() const; gap_buffer* get_line(mm line) const; std::tuple<mm, mm> apply_insert(u32* data, mm len, mm line, mm index); std::tuple<mm, mm> apply_remove(u32* data, mm len, mm line, mm index); void DEBUG_print_state() const; }; // TODO: Error code on fail. static text_buffer* create_buffer_from_file(char const* file_path); // TODO: Error code on fail. static void save_buffer(text_buffer* buf, char const* file_path, encoding enc); struct buffer_point { text_buffer* buffer_ptr; mm first_line; mm curr_line; mm curr_idx; /// If the line is switched to the much shorter one, and the current /// index is truncated to the end, ths value holds the previous index /// until the cursor is moved left / right, something is inserted etc. /// After moving to the larger one, this index is tried to be restored. /// This value is ignored when it is equal to -1. mm last_line_idx; mm visible_lines; bool starting_from_top; bool insert(u32 character); bool insert(u32* begin, u32* end); bool del_backward(); bool del_forward(); bool character_right(); bool character_left(); bool line_up(); bool line_down(); bool jump_up(mm number_of_lines); bool jump_down(mm number_of_lines); bool line_start(); bool line_end(); bool buffer_start(); bool buffer_end(); bool point_is_valid(); }; static buffer_point create_buffer_point(text_buffer* buffer_ptr); #endif // TEXT_BUFFER_HPP
[ "mateuszpd7@gmail.com" ]
mateuszpd7@gmail.com
1e6f90de4bd764ea18ff07ce907959c335d29984
714c20b91835e6469fcc0d8815413567bccef7ab
/Reconstruction/MarchingCubes.cc
5aa3073b527e6c30c1e485572b5b5a7c2fea8a20
[]
no_license
horsewin/ARDIORAMA
ae23a8358a4ad1a4ec36764b6c951a383a210d4f
3dd114f5b31d8ef2d73f8dd879c29cb0cfbcb54e
refs/heads/master
2021-01-23T20:07:25.457221
2012-03-01T10:30:06
2012-03-01T10:30:06
3,590,930
0
0
null
null
null
null
UTF-8
C++
false
false
31,002
cc
/* * MarchingCubes.cc * * Created on: 2010/12/27 * Author: umakatsu */ #include "Reconstruction/MarchingCubes.h" #include <GL/gl.h> #include <GL/glu.h> #include <cmath> #include <float.h> #include <iostream> #include <fstream> #include <sstream> #include "Reconstruction/Tables.h" #include "Image/BmpFileIO.h" #include <boost/foreach.hpp> #include "Model/Model.h" #include "myVector.h" namespace PTAMM{ #define MAPMETHOD 2 const int VERTICESLIMIT = 60000; // 65536 is right number //namespace definition using namespace std; namespace{ TooN::Vector< 2 > projectionFromWorldToImage(const TooN::Vector< 3 > & point , const TooN::SE3<> & se3CFromW , ATANCamera & camera){ TooN::Vector< 3 > v3Cam = se3CFromW * point; TooN::Vector< 2 > v2ImPlane = project(v3Cam); TooN::Vector< 2 > v2Image = camera.Project(v2ImPlane); return v2Image; } } /* * constructor * @param size : cube size * @param isolevel : threshold value */ //MarchingCubes::MarchingCubes(int size, double isolevel) //: SIZE(size) , mIsoLevel(isolevel) //{ // mGridCells = NULL; // mGridPoints = NULL; // allocateTables(); // texture.clear(); //} MarchingCubes::MarchingCubes(int size, double isolevel , const ATANCamera & acam) : SIZE(size) , mIsoLevel(isolevel) , mpCamera(acam) { mGridCells = NULL; mGridPoints = NULL; mTriangles = NULL; gravity = Zeros; allocateTables(); texture.clear(); } MarchingCubes::~MarchingCubes(void) { deallocateTables(); } int MarchingCubes::run() { //テクスチャデータがないと処理を行わない if( texture.size() > 0){ //領域がない場合は確保のみ行う texSize = static_cast< int >(texture.size()); if(mTriangles == NULL){ mTriangles = new deque<Triangle>[ ( texSize + 1 ) ]; #if MAPMETHOD == 2 mTriangles_damy = new deque<Triangle>[ ( texSize + 1 ) ]; #endif } //領域解放後、再度領域確保 else{ delete[] mTriangles; mTriangles = new deque<Triangle>[ ( texSize + 1 ) ]; #if MAPMETHOD == 2 delete[] mTriangles_damy; mTriangles_damy = new deque<Triangle>[ ( texSize + 1 ) ]; #endif } // mTriangles.clear(); int triCount = 0; for (int i = 0; i < SIZE; i += OFFSET) { for (int j = 0; j < SIZE; j += OFFSET) { for (int k = 0; k < SIZE; k += OFFSET) { triCount += polygoniseAndInsert(&mGridCells[i][j][k], mIsoLevel); } } } #if MAPMETHOD == 2 gravity /= triCount; // 各カメラの単位球体における自己位置を算出 BOOST_FOREACH(TextureInfo *t , texture){ TooN::Vector<3> cam = t->camerapose.inverse().get_translation(); double dist = norm3( cam - gravity); t->camera_ref =( cam + ( dist - 1.0 )*gravity ) / dist; // cout << t->camera_ref << endl; // cout << gravity << endl; //// cout << t->camera_ref-gravity << endl; // cout << "t:" << t->texture_number << "=" << norm3(t->camera_ref - gravity) << endl; } // 各メッシュにマッピングするテクスチャを決める REP(tnum,texSize+1){ deque<Triangle>::iterator i; for (i = mTriangles_damy[tnum].begin(); i != mTriangles_damy[tnum].end(); i++) { calculateTexture(*i); if( (*i).texture_number >= 0) mTriangles[(*i).texture_number].push_back((*i)); else mTriangles[texSize].push_back((*i)); } } #endif triangleSize = triCount; return triCount; }else{ return 0; } } void MarchingCubes::reset( void ){ } /* * 生成したデータの保存 */ void MarchingCubes::save(const char * filename){ // Creation of the reserved directory ostringstream directoryName; ostringstream com; directoryName << "~/NewARDiorama/ARDiorama/ARData/Models/ReconstructedObjects/" << filename; com << "mkdir " << directoryName.str().c_str(); if( system( com.str().c_str() ) ); // Creation of a 3DS file Lib3dsFile * sModel = lib3ds_file_new(); strcpy( sModel->name , filename); // Reserve the material setting sModel->nmaterials = texSize; sModel->materials = new Lib3dsMaterial*[texSize]; REP(m,texSize){ ostringstream textureFilename; textureFilename << "texture" << m; sModel->materials[m] = lib3ds_material_new(textureFilename.str().c_str() ); textureFilename << ".bmp"; strcpy( sModel->materials[m]->texture1_map.name , textureFilename.str().c_str() ); if(m < texSize){ // Create BMP File uchar *buf = new uchar[WIDTH * HEIGHT * 3 ]; // read color image myReadRawimage( texture.at(m)->imRGB , buf); // 上下反転 REP(i , HEIGHT/2){ REP(j,WIDTH){ REP(k,3){ swap(buf[(i*WIDTH + j)*3 + k] , buf[( ((HEIGHT-1) - i ) * WIDTH + j ) * 3 + k]); } } } BmpFileIO b; b.WriteRGB( textureFilename.str().c_str(), WIDTH , HEIGHT , buf); delete[] buf; } } // Reserve the mesh // First, the number of meshes are calculated // int meshParts = floor( static_cast< double >( triangleSize) / VERTICESLIMIT ); sModel->nmeshes = texSize; sModel->meshes = new Lib3dsMesh*[texSize]; REP(tnum,texSize){ ostringstream meshFilename; meshFilename << "mesh" << tnum; // cout << meshFilename.str().c_str() << endl; sModel->meshes[tnum] = lib3ds_mesh_new( meshFilename.str().c_str() ); // Creating temporary memory for data of face int faceSum = mTriangles[tnum].size(); sModel->meshes[tnum]->faces = new Lib3dsFace[faceSum]; sModel->meshes[tnum]->vertices = new float[faceSum*3][3]; sModel->meshes[tnum]->texcos = new float[faceSum*3][2]; // Reserve the vertices information deque<Triangle>::iterator i; int face_number = 0; for (i = mTriangles[tnum].begin(); i != mTriangles[tnum].end(); i++){ // Reserve the face setting sModel->meshes[tnum]->faces[face_number].material = tnum; REP(id,3){ int index = face_number * 3 + id; sModel->meshes[tnum]->faces[face_number].index[id] = index; REP(vertexid,3){ sModel->meshes[tnum]->vertices[index][vertexid] = (*i).point[id].coord[vertexid]; } sModel->meshes[tnum]->texcos[index][0] = (*i).point[id].tex[0]; sModel->meshes[tnum]->texcos[index][1] = (*i).point[id].tex[1]; } face_number++; } sModel->meshes[tnum]->nfaces = face_number; sModel->meshes[tnum]->nvertices = face_number * 3; // cout << "mesh" << tnum << ":" << face_number << endl; } SaveXMLFile( filename ); ostringstream saveName; saveName << filename << ".3ds"; lib3ds_file_save( sModel , saveName.str().c_str()); com.str(""); com.clear(stringstream::goodbit); com << "mv *.bmp *.3ds " << directoryName.str().c_str() << "/"; if( system(com.str().c_str() ) ); } void MarchingCubes::SaveXMLFile( const char * filename ) { string ostr = "/home/umakatsu/NewARDiorama/ARDiorama/ARData/Models/modelsTextCopy"; string istr = "/home/umakatsu/NewARDiorama/ARDiorama/ARData/Models/modelsText"; ofstream ofs( ostr.c_str() ); ifstream ifs( istr.c_str() ); // <!--R Objects End -->というコメントがくるまでmodelsText.txtの内容をコピーする // コメントが現れたら保存するモデルのタグを書き込む // タグ書き込み後,内容のコピーを再開する string buf; while(ifs && getline(ifs, buf)) { // 対応する文字が見つかった場合はそのままコピー if( strstr( buf.c_str() , "Objects End") == NULL){ ofs << buf << endl; } // 違う場合はタグ付けをした後にコピー else{ cout << "hello" << endl; stringstream tag; tag << " <Model name=" << "\"R_Model\"" << " image=\"Testset.png\"" << " " << "dir=\"ReconstructedObjects/" << filename << "\" file=\"" << filename << ".3ds\" roll=\"0\" pitch=\"0\" yaw=\"0\" />"; ofs << tag.str().c_str() << endl; ofs << buf << endl; } } ofs.close(); ifs.close(); // Update XML file string com = "cp " + ostr + " " + "/home/umakatsu/NewARDiorama/ARDiorama/ARData/Models/models.xml"; cout << com << endl; if( system( com.c_str() ) >= 0 ); com = "mv " + ostr + " " + istr; cout << com << endl; if( system( com.c_str() ) >= 0 ); // Creation of the icon file com = "cp ~/NewARDiorama/ARDiorama/ARData/Models/Cat_D/Testset/Testset.png ~/NewARDiorama/ARDiorama/ARData/Models/ReconstructedObjects/" + static_cast<string>(filename)+ "/"; cout << com << endl; if( system( com.c_str() ) >= 0 ); } /* * 生成したデータの保存(The format of OBJ and MTL) */ void MarchingCubes::saveOBJ(const char * filename){ std::ostringstream file_output; ofstream fout(filename , ios::out); uint vertex_number = 1; ostringstream fv; ostringstream fmtl; fv << filename << "vertex"; file_output << "cat " << fv.str().c_str() << " " << " " << filename << " > " << filename << "Dat.obj"; fmtl << filename << ".mtl"; ofstream fvout(fv.str().c_str(), ios::out); ofstream fmtlout(fmtl.str().c_str(), ios::out); fvout << "mtllib " << filename << ".mtl" << endl; double wratio = (double)512 / WIDTH; double hratio = (double)256 / HEIGHT; REP(tnum,texSize+1){ // fout << "#" << tnum << endl; //メッシュの書き込み if( tnum < texSize) { fout << "g obj"<< tnum + 1 << endl; fout << "usemtl mat" << tnum << endl; } std::deque<Triangle>::iterator i; for (i = mTriangles[tnum].begin(); i != mTriangles[tnum].end(); i++) { fout << "f "; fvout << "vn "; REP(id,3) fvout << (*i).normal.coord[id] * (-1) << " "; fvout << endl; for (int j = 0; j < 3; j++) { //メッシュの3次元座標値を書き込み fvout << "v "; REP(id,3) fvout << (*i).point[j].coord[id] << " "; fvout << endl; //メッシュのテクスチャに対応する2次元座標を書き込み fvout << "vt "; fvout << (*i).point[j].tex[0] / static_cast< double >( WIDTH * wratio ) << " "; fvout << (*i).point[j].tex[1] / static_cast< double >( HEIGHT * hratio ) << " "; fvout << endl; // fout << (vertex_number - 1) * 3 + (j + 1) << "/" << (vertex_number - 1) * 3 + ( j + 1 ) << "/" << vertex_number << " "; fout << (vertex_number - 1) * 3 + (j + 1) << "/" << (vertex_number - 1) * 3 + ( j + 1 ) << " "; } fout << endl; vertex_number++; } // Create BMP and MTL File if(tnum < texSize){ // Create BMP File uchar *buf = new uchar[WIDTH * HEIGHT * 3 ]; // read color image myReadRawimage( texture.at(tnum)->imRGB , buf); // 上下反転 REP(i , HEIGHT/2){ REP(j,WIDTH){ REP(k,3){ swap(buf[(i*WIDTH + j)*3 + k] , buf[( ((HEIGHT-1) - i ) * WIDTH + j ) * 3 + k]); } } } std::ostringstream ss; // ss << filename; ss << "tex" << tnum << ".bmp"; BmpFileIO b; b.WriteRGB( ss.str().c_str(), WIDTH , HEIGHT , buf); delete[] buf; // Create MTL File fmtlout << "newmtl mat" << tnum << endl; fmtlout << "Ka 1.0 1.0 1.0 " << endl; fmtlout << "Kd 0.5 0.5 0.5 " << endl; fmtlout << "Ks 1.0 1.0 1.0 " << endl; fmtlout << "Ns 0.0000" << endl; fmtlout << "Tr 1.0000" << endl; fmtlout << "illnum 2" << endl; fmtlout << "map_Kd " << ss.str().c_str() << endl << endl; } fvout << "# Number " << tnum << "vertices" << endl; } cout << "Finished reserved Data" << endl; fout.close(); fvout.close(); fmtlout.close(); if( system(file_output.str().c_str() ) ); else; } /* * Map上にオブジェクトを表示する * modeによって表示するオブジェクトのタイプが変わる * 0 : 各視点からはりつけるテクスチャを色で分けて表示 * 1 : 法線ベクトル、位置ベクトルを表示 * 2 : 各視点からのテクスチャマッピング結果を表示 */ #if 0 void MarchingCubes::draw( const int & mode ) { if( texture.size() < 1 ){ cerr << "No Texture are set" << endl; return; } // //テクスチャ番号を保持する int previous_tex_number = static_cast<int>(texture.size() - 1 ); int tex_number = previous_tex_number; //テクスチャバインドの初期化 if( mode != 1){ if(mode == 2){ texture.at(tex_number)->tex->bind( ); } } std::deque<Triangle>::iterator i; //三角形メッシュがなくなるまで繰り返す for (i = mTriangles.begin(); i != mTriangles.end(); i++) { //貼り付けるテクスチャ番号の設定 tex_number = (*i).texture_number; if( tex_number >= static_cast< int >( texture.size() )){ cerr << "Tex Number = " << tex_number << "(MAX=" << texture.size() << endl; assert( tex_number < static_cast< int >( texture.size() )); } if(mode == 0){ assert(tex_number < 30); if( tex_number >= 0) glColor3dv(ColorMap[tex_number]); else glColor3dv(ColorMap[29]); } //テクスチャ番号が前と変わらない or 貼り付けるテクスチャが存在しない場合 //バインドするテクスチャを変更しない if( mode != 1){ if( tex_number >= 0 && tex_number != previous_tex_number ){ assert(previous_tex_number >= 0); assert(tex_number >= 0); if( mode == 2){ // texture.at(previous_tex_number)->tex->unbind(); texture.at(tex_number)->tex->bind( ); } } if( mode != 1) glBegin(GL_TRIANGLES); for (int j = 0; j < 3; j++) { const double * tex = (double*)&(*i).point[j].tex; //テクスチャが見つかった場合は適切な座標値を割り当てる if(tex_number >= 0){ if(mode == 2){ glTexCoord2d( tex[ 0 ], tex[ 1 ] ); } } //テクスチャが見つからなかった場合は背景領域の座標値を割り当てる else{ if(mode == 2){ glTexCoord2d( WIDTH-1 , HEIGHT-1 ); } } glVertex3dv((double*)&(*i).point[j]); } if(tex_number >= 0) previous_tex_number = tex_number; if( mode != 1) glEnd(); } } if(mode == 2){ texture.back()->tex->unbind(); } } #else void MarchingCubes::draw( const int & mode ) { if( texture.size() < 1 ){ cerr << "No Texture are set" << endl; return; } //三角形メッシュがなくなるまで繰り返す REP(tnum,texSize+1){ std::deque<Triangle>::iterator i; //テクスチャバインド if(mode == 2) if( tnum < texSize ) texture.at(tnum)->tex->bind( ); for (i = mTriangles[tnum].begin(); i != mTriangles[tnum].end(); i++) { if(mode == 0){ if(tnum < texSize) glColor3dv(ColorMap[tnum]); else glColor3dv(ColorMap[29]); } //テクスチャ番号が前と変わらない or 貼り付けるテクスチャが存在しない場合 //バインドするテクスチャを変更しない if( mode != 1) glBegin(GL_TRIANGLES); for (int j = 0; j < 3; j++) { const double * tex = (double*)&(*i).point[j].tex; //テクスチャが見つかった場合は適切な座標値を割り当てる if( tnum < texSize){ if(mode == 2){ glTexCoord2d( tex[ 0 ], tex[ 1 ] ); } } //テクスチャが見つからなかった場合は背景領域の座標値を割り当てる else{ if(mode == 2){ glTexCoord2d( WIDTH-1 , HEIGHT-1 ); } } // glVertex3dv((double*)&(*i).point[j]); glVertexVector((*i).point[j].coord); } if( mode != 1) glEnd(); } } if(mode == 2) texture.back()->tex->unbind( ); glColor3f(0,1,1); glPointSize(10); glBegin(GL_POINTS); glVertexVector(gravity); glEnd(); } #endif /* * draw object for authoring mode * Drawing phantom object 2011.5.9 */ void MarchingCubes::drawObject( void ) { if( texture.size() < 1 ){ cerr << "No Texture are set" << endl; return; } REP(tnum,texSize+1){ std::deque<Triangle>::iterator i; // if( tnum < texsize ) texture.at(tnum)->tex->bind( ); for (i = mTriangles[tnum].begin(); i != mTriangles[tnum].end(); i++) { glBegin(GL_TRIANGLES); Triangle tri = (*i); for (int j = 0; j < 3; j++) { // const double * tex = (double*)&(*i).point[j].tex; //テクスチャが見つかった場合は適切な座標値を割り当てる // if( tnum < texsize){ // glTexCoord2d( tex[ 0 ], tex[ 1 ] ); // //テクスチャが見つからなかった場合は背景領域の座標値を割り当てる // }else{ // glTexCoord2d( WIDTH-1 , HEIGHT-1 ); // } glVertexVector(tri.point[j].coord); } glEnd(); } } // texture.back()->tex->unbind( ); } void MarchingCubes::createTexture(const ImageType & imRGB , const TooN::SE3<> & se3CFromW){ if( texture.size() > MAX_TEXTURE){ cout << "Texture are full! " << endl; TextureInfo * buf = texture.front(); delete buf; texture.pop_front(); } TextureInfo *tmp_texture = new TextureInfo(); tmp_texture->silhouette = NULL; tmp_texture->tex = new Texture(imRGB); tmp_texture->camerapose = se3CFromW; tmp_texture->imRGB = imRGB; tmp_texture->texture_number = texture.size(); texture.push_back(tmp_texture); cout << "Texture Create : size=" << texture.size( ) << endl; } void MarchingCubes::createTexture(const ImageType & imRGB , const TooN::SE3<> & se3CFromW , uchar * silhouette){ if( texture.size() > MAX_TEXTURE){ cerr << "Texture are full! " << endl; // TextureInfo * buf = texture.front(); // delete buf; // texture.pop_front(); }else{ TextureInfo *tmp_texture = new TextureInfo(); tmp_texture->tex = new Texture(imRGB); tmp_texture->silhouette = silhouette; tmp_texture->camerapose = se3CFromW; tmp_texture->imRGB = imRGB; tmp_texture->texture_number = texture.size(); texture.push_back(tmp_texture); } } /* * キューブごとの座標値を格納するメソッド * @param v3pos : ボクセルの世界座標系に置ける3次元座標値 */ void MarchingCubes::initGridPoints( GridPoint ***grid ) { // if (!mGridPoints || !mGridCells) { // return; // } // for (int i = 0; i < SIZE + OFFSET; i += OFFSET) { // for (int j = 0; j < SIZE + OFFSET; j += OFFSET) { // for (int k = 0; k < SIZE + OFFSET; k += OFFSET) { // GridPoint* gridPoint = &mGridPoints[i][j][k]; // REP(id,3) gridPoint->coord[id] = grid[i][j][k].coord[id]; // gridPoint->val = grid[i][j][k].val; // } // } // } mGridPoints = grid; } void MarchingCubes::initGridCells( void ){ if (!mGridPoints || !mGridCells) { return; } /* * (i,j,k)にある座標のキューブ情報を生成 */ for (int i = 0; i < SIZE; i += OFFSET) { for (int j = 0; j < SIZE; j += OFFSET) { for (int k = 0; k < SIZE; k += OFFSET) { GridCell* gridCell = &mGridCells[i][j][k]; gridCell->point[0] = &mGridPoints[i ][j ][k ]; gridCell->point[1] = &mGridPoints[i+OFFSET][j ][k ]; gridCell->point[2] = &mGridPoints[i+OFFSET][j ][k+OFFSET]; gridCell->point[3] = &mGridPoints[i ][j ][k+OFFSET]; gridCell->point[4] = &mGridPoints[i ][j+OFFSET][k ]; gridCell->point[5] = &mGridPoints[i+OFFSET][j+OFFSET][k ]; gridCell->point[6] = &mGridPoints[i+OFFSET][j+OFFSET][k+OFFSET]; gridCell->point[7] = &mGridPoints[i ][j+OFFSET][k+OFFSET]; } } } } unsigned int MarchingCubes::getSizeTexture( void ) const{ return texture.size(); } ImageType MarchingCubes::checkImageRGB( int num ) const{ return texture.at(num)->imRGB; } TooN::SE3<> MarchingCubes::getCamemraPoseFromTexture( int num )const{ if( num == -1 ) return (texture.back())->camerapose; else{ assert( num < static_cast< int >(texture.size())); return (texture.at(num))->camerapose; } } uchar * MarchingCubes::getSilhouetteFromTexture( int num ) const{ if( num == -1 ) return (texture.back())->silhouette; else{ assert( num < static_cast< int >(texture.size())); return (texture.at(num))->silhouette; } } /* * モデル生成 * モデルを破棄する場合は別箇所でdeleteが必要となる */ Model * MarchingCubes::modelCreate( void ){ Model * model = Model::create( texSize ); model->copy(mTriangles , texture , texSize); return model; } /*-------------------- below function is private ----------------------*/ int MarchingCubes::polygoniseAndInsert(const GridCell* grid, double isoLevel) { /* 8bitのテーブルの初期化 */ int cubeIndex = 0; /* 点の存在判定 */ if (grid->point[0]->val > isoLevel) cubeIndex |= 1; if (grid->point[1]->val > isoLevel) cubeIndex |= 2; if (grid->point[2]->val > isoLevel) cubeIndex |= 4; if (grid->point[3]->val > isoLevel) cubeIndex |= 8; if (grid->point[4]->val > isoLevel) cubeIndex |= 16; if (grid->point[5]->val > isoLevel) cubeIndex |= 32; if (grid->point[6]->val > isoLevel) cubeIndex |= 64; if (grid->point[7]->val > isoLevel) cubeIndex |= 128; /* 空領域の場合は終了 */ if (EdgeTable[cubeIndex] == 0) { return 0; } /* 補間点の算出 */ Point vertices[12]; if (EdgeTable[cubeIndex] & 1) { vertices[0] = interpolate(isoLevel, grid->point[0], grid->point[1]); } if (EdgeTable[cubeIndex] & 2) { vertices[1] = interpolate(isoLevel, grid->point[1], grid->point[2]); } if (EdgeTable[cubeIndex] & 4) { vertices[2] = interpolate(isoLevel, grid->point[2], grid->point[3]); } if (EdgeTable[cubeIndex] & 8) { vertices[3] = interpolate(isoLevel, grid->point[3], grid->point[0]); } if (EdgeTable[cubeIndex] & 16) { vertices[4] = interpolate(isoLevel, grid->point[4], grid->point[5]); } if (EdgeTable[cubeIndex] & 32) { vertices[5] = interpolate(isoLevel, grid->point[5], grid->point[6]); } if (EdgeTable[cubeIndex] & 64) { vertices[6] = interpolate(isoLevel, grid->point[6], grid->point[7]); } if (EdgeTable[cubeIndex] & 128) { vertices[7] = interpolate(isoLevel, grid->point[7], grid->point[4]); } if (EdgeTable[cubeIndex] & 256) { vertices[8] = interpolate(isoLevel, grid->point[0], grid->point[4]); } if (EdgeTable[cubeIndex] & 512) { vertices[9] = interpolate(isoLevel, grid->point[1], grid->point[5]); } if (EdgeTable[cubeIndex] & 1024) { vertices[10] = interpolate(isoLevel, grid->point[2], grid->point[6]); } if (EdgeTable[cubeIndex] & 2048) { vertices[11] = interpolate(isoLevel, grid->point[3], grid->point[7]); } int triCount = 0; for (int i = 0; TriTable[cubeIndex][i] != -1; i+=3) { Triangle tri; //補間点の座標値の決定 tri.point[0] = vertices[TriTable[cubeIndex][i ]]; tri.point[1] = vertices[TriTable[cubeIndex][i+1]]; tri.point[2] = vertices[TriTable[cubeIndex][i+2]]; //補間点の法線ベクトルの設定 calculateNormal(tri); //重心座標の設定 REP(j,3) tri.g[j] = (tri.point[0].coord[j] + tri.point[1].coord[j] + tri.point[2].coord[j]) / 3; gravity += tri.g; #if MAPMETHOD == 2 //メッシュの追加 mTriangles_damy[0].push_back(tri); #elif MAPMETHOD == 1 // メッシュに貼り付けるテクスチャとの対応座標を決定 calculateTexture(tri); if( tri.texture_number >= 0) mTriangles[tri.texture_number].push_back(tri); else mTriangles[texSize].push_back(tri); #endif triCount++; } return triCount; } Point MarchingCubes::interpolate(double isoLevel, const GridPoint* gp1, const GridPoint* gp2) { double mu; Point p; // mu = (isoLevel - gp1->val) / (gp2->val - gp1->val); mu = 0.5; //ちょうど真ん中の点に補間する //補間点の座標値の決定 p.coord[0] = gp1->coord[0] + mu * (gp2->coord[0] - gp1->coord[0]); p.coord[1] = gp1->coord[1] + mu * (gp2->coord[1] - gp1->coord[1]); p.coord[2] = gp1->coord[2] + mu * (gp2->coord[2] - gp1->coord[2]); return p; } /* * 領域の生成 */ void MarchingCubes::allocateTables(void) { if (mGridPoints || mGridCells) { deallocateTables(); } // mGridPoints = new GridPoint**[SIZE + OFFSET]; // for (int i = 0; i < SIZE + OFFSET; i++) { // mGridPoints[i] = new GridPoint*[SIZE + OFFSET]; // for (int j = 0; j < SIZE + OFFSET; j++) { // mGridPoints[i][j] = new GridPoint[SIZE + OFFSET]; // } // } mGridCells = new GridCell**[SIZE]; for (int i = 0; i < SIZE; i++) { mGridCells[i] = new GridCell*[SIZE]; for (int j = 0; j < SIZE; j++) { mGridCells[i][j] = new GridCell[SIZE]; } } } /* * 領域の解放 */ void MarchingCubes::deallocateTables(void) { if (mGridPoints) { for (int i = 0; i < SIZE + 1; i++) { for (int j = 0; j < SIZE + 1; j++) { delete [] mGridPoints[i][j]; } delete [] mGridPoints[i]; } delete [] mGridPoints; mGridPoints = NULL; } if (mGridCells) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { delete [] mGridCells[i][j]; } delete [] mGridCells[i]; } delete [] mGridCells; mGridCells = NULL; } } void MarchingCubes::calculateNormal(Triangle& tri) { double a[3], b[3]; double length; // //内側を向く // a[0] = tri.point[0].coord[0] - tri.point[1].coord[0]; // a[1] = tri.point[0].coord[1] - tri.point[1].coord[1]; // a[2] = tri.point[0].coord[2] - tri.point[1].coord[2]; // b[0] = tri.point[0].coord[0] - tri.point[2].coord[0]; // b[1] = tri.point[0].coord[1] - tri.point[2].coord[1]; // b[2] = tri.point[0].coord[2] - tri.point[2].coord[2]; // //外側を向く a[0] = tri.point[2].coord[0] - tri.point[0].coord[0]; a[1] = tri.point[2].coord[1] - tri.point[0].coord[1]; a[2] = tri.point[2].coord[2] - tri.point[0].coord[2]; b[0] = tri.point[1].coord[0] - tri.point[0].coord[0]; b[1] = tri.point[1].coord[1] - tri.point[0].coord[1]; b[2] = tri.point[1].coord[2] - tri.point[0].coord[2]; tri.normal.coord[0] = a[1] * b[2] - b[1] * a[2]; tri.normal.coord[1] = b[0] * a[2] - a[0] * b[2]; tri.normal.coord[2] = a[0] * b[1] - b[0] * a[1]; length = sqrt(tri.normal.coord[0]*tri.normal.coord[0] + tri.normal.coord[1]*tri.normal.coord[1] + tri.normal.coord[2]*tri.normal.coord[2]); tri.normal.coord[0] /= length; tri.normal.coord[1] /= length; tri.normal.coord[2] /= length; } /* * 補間点ごとのテクスチャをマッピングする * メンバ変数のテクスチャベクターから読み込み */ void MarchingCubes::calculateTexture(Triangle & tri) { //二次元座標値の退避用変数 double w[3][2]; REP(id1,3) REP(id2,2) w[id1][id2] = 0.0; //三角形メッシュに貼り付けるテクスチャ番号、境界値を初期化 tri.texture_number = -1; #if MAPMETHOD == 1 tri.check_value = 0.0; // 面積比較を用いたテクスチャ決定手法で用いる #elif MAPMETHOD == 2 tri.check_value = DBL_MAX; // 距離比較を用いたテクスチャ決定手法で用いる #endif //適切なテクスチャを探索する int max_texture_number = static_cast< int >( texture.size() ); BOOST_FOREACH(TextureInfo *t , texture){ const int texture_number = t->texture_number; assert( texture_number >= 0); assert( texture_number <= max_texture_number); bool frag[3]; REP(id,3) frag[id] = false; REP(id,3){ TooN::Vector< 3 > ver; REP(id1,3) ver[id1] = tri.point[id].coord[id1]; //3次元位置を2次元座標系に落とす TooN::Vector< 2 > back = projectionFromWorldToImage(ver , t->camerapose , mpCamera); double address[2]; address[0] = (double)back[0]; //width address[1] = (double)back[1]; //height //Check if the projected pixel is in the Image Plane if(address[0] >= 0.0 && address[0] < WIDTH && address[1] >= 0.0 && address[1] < HEIGHT ){ //2次元位置を格納する //同時に現時点における二次元位置を退避させる REP(id1,2){ w[id][id1] = tri.point[id].tex[id1]; tri.point[id].tex[id1] = address[id1]; } frag[id] = true; }else break; //1点でも画面内に収まっていない場合はテクスチャをはらない } //3点すべてが画面上に収まっている場合は適切なテクスチャかどうか調べる if( frag[0] && frag[1] && frag[2]){ //テクスチャ切り替えが発生 if(checkOptimalTextureNumber(tri , texture_number) ); //テクスチャ番号に変更はない else REP(id1,3) REP(id2,2) tri.point[id1].tex[id2] = w[id1][id2]; } //テクスチャ座標値が切り替えられた頂点を書き戻す else REP(id1,3) if(frag[id1]) REP(id2,2) tri.point[id1].tex[id2] = w[id1][id2]; } } /* * メッシュに貼り付ける適切なテクスチャを選ぶメソッド * @param tri : テクスチャ貼り付けの対象となっている三角形メッシュ */ //int MarchingCubes::checkOptimalTexture( Triangle & tri , const int & mode){ // int tex_number = -1; // double check_val = DBL_MIN; //// ofstream fout("TextureData.txt" , ios::out | ios::app); // REP(t,texture.size()){ // // Definition of a coordinate of camera // TooN::Vector< 3 > cam = texture.at(t)->camerapose.inverse().get_translation(); // // Definition of an triangle vector // TooN::Vector< 3 > patch = tri.point[0].coord; // // Definition of a directional vector for camera // TooN::Vector< 3 > v = cam - patch; // // Definition of a normal vector aim for object outside // TooN::Vector< 3 > n_vector = tri.normal.coord; // // double ip = n_vector * v; // // if( mode == 1){ // glLineWidth( 5.0 ); // glBegin(GL_LINES); // glColor3d(1.0 , 1.0 , 0.0); // glVertexVector(patch); // glVertex3d(0.0 , 0.0 , 0.0); // glColor3d(1.0 , 0.0 , 0.0); // glVertexVector(patch); // glVertexVector(patch+n_vector); // glEnd(); // glFlush(); // } //// Texture mapping // if( ip > EPSILON ){ // //もっとも適切と思われるテクスチャを選ぶ // double cosTheta = ip / ( norm3(v) ); // double val = acos(cosTheta); // if( val < check_val ){ // check_val = val; // tex_number = t; // } // } // } //// fout.close(); // return tex_number; //} /* * メッシュに貼り付ける適切なテクスチャを選ぶメソッド * @param tri : テクスチャ貼り付けの対象となっている三角形メッシュ */ bool MarchingCubes::checkOptimalTextureNumber( Triangle & tri , const int & texture_num) { #if MAPMETHOD == 1 // Definition of a coordinate of camera TooN::Vector< 3 > cam = texture.at(texture_num)->camerapose.inverse().get_translation(); // Definition of an triangle vector TooN::Vector< 3 > patch = tri.point[0].coord; // Definition of a directional vector for camera TooN::Vector< 3 > v = cam - patch; // Definition of a normal vector aim for object outside TooN::Vector< 3 > n_vector = tri.normal.coord; // Calculate inner product double ip = n_vector * v; #elif MAPMETHOD == 2 double val = norm3( texture.at(texture_num)->camera_ref - tri.g ); #endif // Texture mapping // if inner product between normal vector and directional vector is sharp angel #if MAPMETHOD == 1 if( ip > 0.0 ){ //もっとも適切と思われるテクスチャを選ぶ double val = calculateTriangleArea(tri); if( val > tri.check_value ){ assert( texture_num >= 0); tri.check_value = val; tri.texture_number = texture_num; return true; } } #elif MAPMETHOD == 2 if( val < tri.check_value ){ assert( texture_num >= 0); tri.check_value = val; tri.texture_number = texture_num; return true; } #endif return false; } void MarchingCubes::checkTexturePose(){ BOOST_FOREACH(TextureInfo *t , texture){ cout << "No." << t->texture_number << endl << t->camerapose << endl; } } double MarchingCubes::calculateTriangleArea(const Triangle & tri ){ double p1[2]; double p2[2]; REP(id,2){ p1[id] = tri.point[2].tex[id] - tri.point[0].tex[id]; p2[id] = tri.point[2].tex[id] - tri.point[1].tex[id]; } return (0.5 * fabs( p1[0]*p2[1] - p1[1]*p2[0] ) ); } }
[ "mamamatz@gmail.com" ]
mamamatz@gmail.com
5545364df1be273bd3514aa3aca195bfcef33f49
c8c767177ad96c04c9c04366c5ac3b6392fd3302
/DeltaPackageExtractorHandler.cpp
d253fc89b2bd33e917f0d529c7c5380a13a77c72
[]
no_license
puckipedia/HaikuDeltaPKG
50e4ef52d6b319698126d643336f403bafca48c8
6257c97cd5cae95106561267e0f893595031a803
refs/heads/master
2021-01-06T20:46:25.450869
2014-03-06T22:06:04
2014-03-06T22:06:04
17,451,139
1
0
null
null
null
null
UTF-8
C++
false
false
2,401
cpp
#include "DeltaPackageExtractorHandler.h" #include <os/support/ByteOrder.h> #include <string.h> #include <stdlib.h> #include <stdio.h> map<uint32, DeltaPackageExtractor*> DeltaPackageExtractorHandler::gDeltaFileHandlers; DeltaPackageExtractorHandler::DeltaPackageExtractorHandler() { fPath.SetTo("/"); } void* DeltaPackageExtractorHandler::GetData(BPackageData& data) { void* dat = malloc(data.Size()); if(data.IsEncodedInline()) { memcpy(dat, static_cast<const void*>(data.InlineData()), data.Size()); return dat; } else { fHeapReader->ReadData(data.Offset(), dat, data.Size()); return dat; } free(dat); return NULL; } status_t DeltaPackageExtractorHandler::HandleEntry(BPackageEntry* entry) { this->fPath.Append(entry->Name()); DeltaPackageEntryInfo* info = new DeltaPackageEntryInfo(); info->fHandlerID = 'UNKN'; info->fExtractedSize = entry->Data().Size(); info->fStringPath = this->fPath.Path(); info->fDataSize = entry->Data().Size(); info->fDataEncodedInline = entry->Data().IsEncodedInline(); if (info->fDataEncodedInline) { memcpy(info->fInlineData, entry->Data().InlineData(), B_HPKG_MAX_INLINE_DATA_SIZE); } else { info->fDataOffset = entry->Data().Offset(); } entry->SetUserToken(info); return B_OK; } status_t DeltaPackageExtractorHandler::HandleEntryAttribute(BPackageEntry* entry, BPackageEntryAttribute* attribute) { DeltaPackageEntryInfo* info = static_cast<DeltaPackageEntryInfo*>(entry->UserToken()); BString name = attribute->Name(); if (name == "DPKG:HANDLER") { void* data = GetData(attribute->Data()); if (data != NULL) { info->fHandlerID = *static_cast<int32*>(data); free(data); } } if (name == "DPKG:EXTRSIZE") { void* data = GetData(attribute->Data()); if (data != NULL) { info->fExtractedSize = *static_cast<uint64*>(data); free(data); } } return B_OK; } status_t DeltaPackageExtractorHandler::HandleEntryDone(BPackageEntry* entry) { DeltaPackageEntryInfo* info = static_cast<DeltaPackageEntryInfo*>(entry->UserToken()); int32 what = B_BENDIAN_TO_HOST_INT32(info->fHandlerID); this->fPath.GetParent(&this->fPath); fPackageEntries[info->fStringPath.String()] = info; return B_OK; } status_t DeltaPackageExtractorHandler::HandlePackageAttribute(const BPackageInfoAttributeValue& value) { return B_OK; } void DeltaPackageExtractorHandler::HandleErrorOccurred() { }
[ "puck@puckipedia.nl" ]
puck@puckipedia.nl
6ef40195f215b40dc266430e3dc0d9f1ef0bdfa3
a55f07cabf8a0bc1b138ba52674f390de0f0c2f9
/ConsoleApplication1.h
a33c195f4a54160e5ebf4b3d455fb2d84ee431b0
[]
no_license
irynayudina/wordRepeater
f990e52437cd8d63d82abe23e2ffd86b777c0f6d
7092841b23b360ac72787d17d84a6c9b22f7833c
refs/heads/master
2023-01-23T18:03:40.090888
2020-11-26T16:05:16
2020-11-26T16:05:16
316,278,763
0
0
null
null
null
null
UTF-8
C++
false
false
148
h
#pragma once void erassssor(int& inputSize, char* input, std::string& inp, int sSize); void length(int maxBufferSize, int& sSize, char s[1000]);
[ "yudinaira4444@gmail.com" ]
yudinaira4444@gmail.com
eacee80a5c8d30efefb68c6d396c46bed7fcde73
b4e2870e505b3a576115fa9318aabfb971535aef
/zParserExtender/ZenGin/Gothic_UserAPI/oCVob.inl
dfc77d3f23a78350717cd442efcca283051aa6f4
[]
no_license
Gratt-5r2/zParserExtender
4289ba2e71748bbac0c929dd1941d151cdde46ff
ecf51966e4d8b4dc27e3bfaff06848fab69ec9f1
refs/heads/master
2023-01-07T07:35:15.720162
2022-10-08T15:58:41
2022-10-08T15:58:41
208,900,373
6
1
null
2023-01-02T21:53:03
2019-09-16T21:21:28
C++
UTF-8
C++
false
false
93
inl
// Supported with union (c) 2020 Union team // User API for oCVob // Add your methods here
[ "amax96@yandex.ru" ]
amax96@yandex.ru
8f0e0747e655226623d83a8a3a8a85bd5bf6ad58
793c8848753f530aab28076a4077deac815af5ac
/src/dskphone/uilogic/idleuilogic/src/hotdeskidlehandle.h
d250589f69eb67dc574c39d074ee1eb1a199b34c
[]
no_license
Parantido/sipphone
4c1b9b18a7a6e478514fe0aadb79335e734bc016
f402efb088bb42900867608cc9ccf15d9b946d7d
refs/heads/master
2021-09-10T20:12:36.553640
2018-03-30T12:44:13
2018-03-30T12:44:13
263,628,242
1
0
null
2020-05-13T12:49:19
2020-05-13T12:49:18
null
UTF-8
C++
false
false
480
h
#ifndef _HOTDESK_IDLE_HANDLE_H_ #define _HOTDESK_IDLE_HANDLE_H_ #include "baseidlehandle.h" class CHotdesktHandle : public CBaseIdleHandle { public: CHotdesktHandle(int nType = PS_STATE_NOTE_HOTDESK); virtual ~CHotdesktHandle(); public: // 获取弹框信息 virtual bool GetPopupBoxInfo(PopupBoxData & popData); // 按键处理 virtual bool HandleKeyProcess(SoftKey_TYPE eSoftkey, PHONE_KEY_CODE eKeyCode); }; #endif //end of _HOTDESK_IDLE_HANDLE_H_
[ "rongxx@yealink.com" ]
rongxx@yealink.com
6b074cde8e40d34ecf677d910dcd861740c8fe57
24004e1c3b8005af26d5890091d3c207427a799e
/Win32/NXOPEN/NXOpen/CAE_ResponseSimulation_PrlResultsEvaluationSetting.hxx
bfa8c28b091be0fbeb6c8839ba6fe0ec15d052f7
[]
no_license
15831944/PHStart
068ca6f86b736a9cc857d7db391b2f20d2f52ba9
f79280bca2ec7e5f344067ead05f98b7d592ae39
refs/heads/master
2022-02-20T04:07:46.994182
2019-09-29T06:15:37
2019-09-29T06:15:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,373
hxx
#ifndef NXOpen_CAE_RESPONSESIMULATION_PRLRESULTSEVALUATIONSETTING_HXX_INCLUDED #define NXOpen_CAE_RESPONSESIMULATION_PRLRESULTSEVALUATIONSETTING_HXX_INCLUDED //-------------------------------------------------------------------------- // Header for C++ interface to JA API //-------------------------------------------------------------------------- // // Source File: // CAE_ResponseSimulation_PrlResultsEvaluationSetting.ja // // Generated by: // apiwrap // // WARNING: // This file is automatically generated - do not edit by hand // #ifdef _MSC_VER #pragma once #endif #include <NXOpen/NXDeprecation.hxx> #include <vector> #include <NXOpen/NXString.hxx> #include <NXOpen/Callback.hxx> #include <NXOpen/CAE_ResponseSimulation_DynamicResultEvaluationSetting.hxx> #include <NXOpen/libnxopencpp_cae_exports.hxx> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif namespace NXOpen { namespace CAE { namespace ResponseSimulation { class PrlResultsEvaluationSetting; } } namespace CAE { namespace ResponseSimulation { class DynamicResultEvaluationSetting; } } namespace CAE { namespace ResponseSimulation { class _PrlResultsEvaluationSettingBuilder; class PrlResultsEvaluationSettingImpl; /** Represents the abstract class of evaluation setting for peak value, RMS results and LCR results. <br> This is an abstract class, and cannot be created. <br> <br> Created in NX5.0.0. <br> */ class NXOPENCPP_CAEEXPORT PrlResultsEvaluationSetting : public CAE::ResponseSimulation::DynamicResultEvaluationSetting { private: PrlResultsEvaluationSettingImpl * m_prlresultsevaluationsetting_impl; private: friend class _PrlResultsEvaluationSettingBuilder; protected: PrlResultsEvaluationSetting(); public: ~PrlResultsEvaluationSetting(); }; } } } #ifdef _MSC_VER #pragma warning(pop) #endif #ifdef __GNUC__ #ifndef NX_NO_GCC_DEPRECATION_WARNINGS #pragma GCC diagnostic warning "-Wdeprecated-declarations" #endif #endif #undef EXPORTLIBRARY #endif
[ "1075087594@qq.com" ]
1075087594@qq.com
7fd58f4223170c3e246c62197c5bbafb5faf3f65
0ef4f71c8ff2f233945ee4effdba893fed3b8fad
/misc_microsoft_gamedev_source_code/misc_microsoft_gamedev_source_code/extlib/havok/Source/Physics/Collide/Query/CastUtil/hkpWorldLinearCaster.h
b7acbd73b8faa249b72cba2eff02bf7e1357e2aa
[]
no_license
sgzwiz/misc_microsoft_gamedev_source_code
1f482b2259f413241392832effcbc64c4c3d79ca
39c200a1642102b484736b51892033cc575b341a
refs/heads/master
2022-12-22T11:03:53.930024
2020-09-28T20:39:56
2020-09-28T20:39:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,568
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2007 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_WORLD_LINEAR_CASTER #define HK_WORLD_LINEAR_CASTER #include <Physics/Internal/Collide/BroadPhase/hkpBroadPhaseCastCollector.h> #include <Physics/Collide/Agent/Query/hkpLinearCastCollisionInput.h> struct hkpCollisionInput; struct hkpLinearCastInput; struct hkpCollisionAgentConfig; class hkpCdPointCollector; class hkpCollisionFilter; class hkpCollidableCollidableFilter; class hkpBroadPhase; typedef char hkpBroadPhaseAabbCache; /// This is a utility class you can use to perform a linear cast with a collidable against all other collidables in the broad /// phase. It has one function, linear cast. /// It effectively connects hkpBroadPhase::castAabb with hkpCollisionAgent::linearCast /// This is called by hkpWorld::linearCast(). Usually you should call hkpWorld::linearCast instead of /// using this class directly. class hkpWorldLinearCaster : public hkpBroadPhaseCastCollector { public: hkpWorldLinearCaster(){} ~hkpWorldLinearCaster(){} /// Inputs are: /// - a reference to the broad phase /// - the collidable to linear cast /// - the linear cast input /// - the collidable-collidable filter /// - the hkpCollisionInput (for the narrow phase linear casts) /// - collectors for start points and cast points /// - an optional an hkpBroadPhaseAabbCache: See hkpBroadPhase for Details or HK_NULL if you don't want to use it /// For each narrow phase linear cast hit, the collectors will receive a callback. void linearCast( const hkpBroadPhase& broadphase, const hkpCollidable* collA, const hkpLinearCastInput& input, const hkpCollidableCollidableFilter* filter, const hkpCollisionInput& collInput, hkpCollisionAgentConfig* config, hkpBroadPhaseAabbCache* m_broadPhaseCache, hkpCdPointCollector& castCollector, hkpCdPointCollector* startPointCollector ); protected: virtual hkReal addBroadPhaseHandle( const hkpBroadPhaseHandle* broadPhaseHandle, int castIndex ); protected: const hkpLinearCastInput* m_input; const hkpCollidableCollidableFilter* m_filter; hkpCdPointCollector* m_castCollector; hkpCdPointCollector* m_startPointCollector; const hkpCollidable* m_collidableA; hkpShapeType m_typeA; // used as a temporary storage hkpLinearCastCollisionInput m_shapeInput; }; #endif //HK_BROAD_PHASE_LINEAR_CASTER /* * Havok SDK - PUBLIC RELEASE, BUILD(#20070919) * * Confidential Information of Havok. (C) Copyright 1999-2007 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from salesteam@havok.com. * */
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
bbf310a5cc4f35a48036cae909d3a0eb158740a7
ff668c6cf3f5f0c9b7ca0440a28e43eec548f69b
/vn.archive/vn.lts_old/pyscript/lts_md_process.cpp
6c4621c571d5fda39c9998e1cb60726df2768184
[ "MIT" ]
permissive
uniwin/vnpy
7b8cf303562b70c950b29cc78aca9c30e20979ff
a00cee7c437383e715072cb5f0931930f2bd988e
refs/heads/master
2020-12-24T09:53:06.734239
2017-04-04T10:52:19
2017-04-04T10:52:19
51,852,988
0
0
MIT
2019-02-24T13:26:44
2016-02-16T17:02:28
C++
UTF-8
C++
false
false
5,198
cpp
void MdApi::processFrontConnected(Task task) { PyLock lock; this->onFrontConnected(); }; void MdApi::processFrontDisconnected(Task task) { PyLock lock; this->onFrontDisconnected(task.task_id); }; void MdApi::processHeartBeatWarning(Task task) { PyLock lock; this->onHeartBeatWarning(task.task_id); }; void MdApi::processRspError(Task task) { PyLock lock; CSecurityFtdcRspInfoField task_error = any_cast<CSecurityFtdcRspInfoField>(task.task_error); dict error; error["ErrorMsg"] = task_error.ErrorMsg; error["ErrorID"] = task_error.ErrorID; this->onRspError(error, task.task_id, task.task_last); }; void MdApi::processRspUserLogin(Task task) { PyLock lock; CSecurityFtdcRspUserLoginField task_data = any_cast<CSecurityFtdcRspUserLoginField>(task.task_data); dict data; data["MaxOrderRef"] = task_data.MaxOrderRef; data["UserID"] = task_data.UserID; data["TradingDay"] = task_data.TradingDay; data["SessionID"] = task_data.SessionID; data["SystemName"] = task_data.SystemName; data["FrontID"] = task_data.FrontID; data["BrokerID"] = task_data.BrokerID; data["LoginTime"] = task_data.LoginTime; CSecurityFtdcRspInfoField task_error = any_cast<CSecurityFtdcRspInfoField>(task.task_error); dict error; error["ErrorMsg"] = task_error.ErrorMsg; error["ErrorID"] = task_error.ErrorID; this->onRspUserLogin(data, error, task.task_id, task.task_last); }; void MdApi::processRspUserLogout(Task task) { PyLock lock; CSecurityFtdcUserLogoutField task_data = any_cast<CSecurityFtdcUserLogoutField>(task.task_data); dict data; data["UserID"] = task_data.UserID; data["BrokerID"] = task_data.BrokerID; CSecurityFtdcRspInfoField task_error = any_cast<CSecurityFtdcRspInfoField>(task.task_error); dict error; error["ErrorMsg"] = task_error.ErrorMsg; error["ErrorID"] = task_error.ErrorID; this->onRspUserLogout(data, error, task.task_id, task.task_last); }; void MdApi::processRspSubMarketData(Task task) { PyLock lock; CSecurityFtdcSpecificInstrumentField task_data = any_cast<CSecurityFtdcSpecificInstrumentField>(task.task_data); dict data; data["InstrumentID"] = task_data.InstrumentID; data["ExchangeID"] = task_data.ExchangeID; CSecurityFtdcRspInfoField task_error = any_cast<CSecurityFtdcRspInfoField>(task.task_error); dict error; error["ErrorMsg"] = task_error.ErrorMsg; error["ErrorID"] = task_error.ErrorID; this->onRspSubMarketData(data, error, task.task_id, task.task_last); }; void MdApi::processRspUnSubMarketData(Task task) { PyLock lock; CSecurityFtdcSpecificInstrumentField task_data = any_cast<CSecurityFtdcSpecificInstrumentField>(task.task_data); dict data; data["InstrumentID"] = task_data.InstrumentID; data["ExchangeID"] = task_data.ExchangeID; CSecurityFtdcRspInfoField task_error = any_cast<CSecurityFtdcRspInfoField>(task.task_error); dict error; error["ErrorMsg"] = task_error.ErrorMsg; error["ErrorID"] = task_error.ErrorID; this->onRspUnSubMarketData(data, error, task.task_id, task.task_last); }; void MdApi::processRtnDepthMarketData(Task task) { PyLock lock; CSecurityFtdcDepthMarketDataField task_data = any_cast<CSecurityFtdcDepthMarketDataField>(task.task_data); dict data; data["HighestPrice"] = task_data.HighestPrice; data["BidPrice5"] = task_data.BidPrice5; data["BidPrice4"] = task_data.BidPrice4; data["BidPrice1"] = task_data.BidPrice1; data["BidPrice3"] = task_data.BidPrice3; data["BidPrice2"] = task_data.BidPrice2; data["LowerLimitPrice"] = task_data.LowerLimitPrice; data["OpenPrice"] = task_data.OpenPrice; data["AskPrice5"] = task_data.AskPrice5; data["AskPrice4"] = task_data.AskPrice4; data["AskPrice3"] = task_data.AskPrice3; data["PreClosePrice"] = task_data.PreClosePrice; data["AskPrice1"] = task_data.AskPrice1; data["PreSettlementPrice"] = task_data.PreSettlementPrice; data["AskVolume1"] = task_data.AskVolume1; data["UpdateTime"] = task_data.UpdateTime; data["UpdateMillisec"] = task_data.UpdateMillisec; data["AveragePrice"] = task_data.AveragePrice; data["BidVolume5"] = task_data.BidVolume5; data["BidVolume4"] = task_data.BidVolume4; data["BidVolume3"] = task_data.BidVolume3; data["BidVolume2"] = task_data.BidVolume2; data["PreOpenInterest"] = task_data.PreOpenInterest; data["AskPrice2"] = task_data.AskPrice2; data["Volume"] = task_data.Volume; data["AskVolume3"] = task_data.AskVolume3; data["AskVolume2"] = task_data.AskVolume2; data["AskVolume5"] = task_data.AskVolume5; data["AskVolume4"] = task_data.AskVolume4; data["UpperLimitPrice"] = task_data.UpperLimitPrice; data["BidVolume1"] = task_data.BidVolume1; data["InstrumentID"] = task_data.InstrumentID; data["ClosePrice"] = task_data.ClosePrice; data["ExchangeID"] = task_data.ExchangeID; data["TradingDay"] = task_data.TradingDay; data["PreDelta"] = task_data.PreDelta; data["OpenInterest"] = task_data.OpenInterest; data["CurrDelta"] = task_data.CurrDelta; data["Turnover"] = task_data.Turnover; data["LastPrice"] = task_data.LastPrice; data["SettlementPrice"] = task_data.SettlementPrice; data["ExchangeInstID"] = task_data.ExchangeInstID; data["LowestPrice"] = task_data.LowestPrice; data["ActionDay"] = task_data.ActionDay; this->onRtnDepthMarketData(data); };
[ "xiaoyou.chen@hotmail.com" ]
xiaoyou.chen@hotmail.com
4f36bf07dd9e140981dc71e830771647f379b8bb
c094d381422c2788d67a3402cff047b464bf207b
/Algorithms in C/Algorithms in C/p011连通性问题的快速合并解决方案.cpp
d78b29377987906daa873ec6e0ef8aa10f39d45b
[]
no_license
liuxuanhai/C-code
cba822c099fd4541f31001f73ccda0f75c6d9734
8bfeab60ee2f8133593e6aabfeefaf048357a897
refs/heads/master
2020-04-18T04:26:33.246444
2016-09-05T08:32:33
2016-09-05T08:32:33
67,192,848
1
0
null
null
null
null
GB18030
C++
false
false
1,009
cpp
// 合并 - 查找算法 之 快速合并(较慢查找) // 实现思路是把每棵树的树根合并; // 为了实现合并, 只需要将指向的两个对象进行连接而不用遍历数组, 因此命名为快速合并; #include <stdio.h> #define N 1000 int main(void) { int i, j, p, q, id[N]; for (i = 0; i < N; i++) id[i] = i; while(scanf("%d %d\n", &p, &q) == 2) { // 较慢查找操作, 一直循环到两个操作数各自的树根 for (i = p; i!= id[i]; i = id[i]); // 循环的结果是: i = (p所在树对应的树根) for (j = q; j!= id[j]; j = id[j]); // 循环的结果是: j = (q所在树对应的树根) if (i == j) // 如果两个数的树根相同, 说明在同一个树上, 连通的对不用输出 continue; // 快速合并操作, 直接合并指向的项目, 不用遍历 // 合并的结果是: p中包含了指向q所在树的树根的id("指针") id[i] = j; // 输出没有实现连通的对; printf("\t\t%d %d\n", p, q); } return 0; }
[ "heabking@gmail.com" ]
heabking@gmail.com
88c1e27cbbe2b0a1a7c3114bd2b0ed710a62d3b1
81024c4396f19152dce8a490967bac44c0dba99c
/cing/libraries/mac/xcode/OgreSDK/Samples/Compositor/src/CompositorDemo_FrameListener.cpp
01b03306b1fdcb321eaaa779034c7a995c7045ee
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CingProject/Cing
ca8c44377705d1f3b744141809ae486a8cc640aa
1e4f83fe76e69bad57e07b48d2c54813e9a3a1c2
refs/heads/master
2020-04-05T23:41:10.838562
2014-05-05T17:30:46
2014-05-05T17:30:46
1,756,756
7
7
null
2014-05-05T17:30:33
2011-05-16T18:11:33
C++
UTF-8
C++
false
false
21,505
cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ #include <Ogre.h> #include <OgreTimer.h> #include <CEGUI/CEGUIPropertyHelper.h> #include "CompositorDemo_FrameListener.h" #include "Compositor.h" inline Ogre::String operator +(const Ogre::String& l,const CEGUI::String& o) { return l+o.c_str(); } /* inline CEGUI::String operator +(const CEGUI::String& l,const Ogre::String& o) { return l+o.c_str(); } */ /************************************************************************* CompositorDemo_FrameListener methods that handle all input for this Compositor demo. *************************************************************************/ CompositorDemo_FrameListener::CompositorDemo_FrameListener(CompositorDemo* main) : mMain(main) , mTranslateVector(Ogre::Vector3::ZERO) , mStatsOn(true) , mNumScreenShots(0) , mWriteToFile(false) , mSkipCount(0) , mUpdateFreq(50) , mSceneDetailIndex(0) , mFiltering(Ogre::TFO_BILINEAR) , mAniso(1) , mQuit(false) , mMoveScale(0.0f) , mRotScale(0.0f) , mSpeed(MINSPEED) , mAvgFrameTime(0.1) , mMoveSpeed(100) , mRotateSpeed(0) , mLastMousePositionSet(false) , mTimeUntilNextToggle(0) , mRotX(0) , mRotY(0) , mProcessMovement(false) , mUpdateMovement(false) , mLMBDown(false) , mRMBDown(false) , mMoveFwd(false) , mMoveBck(false) , mMoveLeft(false) , mMoveRight(false) , mSpinny(0) , mCompositorSelectorViewManager(0) , mMouse(0) , mKeyboard(0) { Ogre::Root::getSingleton().addFrameListener(this); // using buffered input OIS::ParamList pl; size_t windowHnd = 0; std::ostringstream windowHndStr; mMain->getRenderWindow()->getCustomAttribute("WINDOW", &windowHnd); windowHndStr << windowHnd; pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str())); mInputManager = OIS::InputManager::createInputSystem( pl ); //Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse) mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true )); mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true )); unsigned int width, height, depth; int left, top; mMain->getRenderWindow()->getMetrics(width, height, depth, left, top); //Set Mouse Region.. if window resizes, we should alter this to reflect as well const OIS::MouseState &ms = mMouse->getMouseState(); ms.width = width; ms.height = height; mMouse->setEventCallback(this); mKeyboard->setEventCallback(this); mGuiRenderer = CEGUI::System::getSingleton().getRenderer(); mGuiAvg = CEGUI::WindowManager::getSingleton().getWindow("OPAverageFPS"); mGuiCurr = CEGUI::WindowManager::getSingleton().getWindow("OPCurrentFPS"); mGuiBest = CEGUI::WindowManager::getSingleton().getWindow("OPBestFPS"); mGuiWorst = CEGUI::WindowManager::getSingleton().getWindow("OPWorstFPS"); mGuiTris = CEGUI::WindowManager::getSingleton().getWindow("OPTriCount"); mGuiDbg = CEGUI::WindowManager::getSingleton().getWindow("OPDebugMsg"); mRoot = CEGUI::WindowManager::getSingleton().getWindow("root"); registerCompositors(); initDebugRTTWindow(); connectEventHandlers(); } //-------------------------------------------------------------------------- CompositorDemo_FrameListener::~CompositorDemo_FrameListener() { if(mInputManager) { mInputManager->destroyInputObject(mKeyboard); mInputManager->destroyInputObject(mMouse); OIS::InputManager::destroyInputSystem(mInputManager); mInputManager = 0; } delete mCompositorSelectorViewManager; } //-------------------------------------------------------------------------- void CompositorDemo_FrameListener::connectEventHandlers(void) { CEGUI::Window* wndw = CEGUI::WindowManager::getSingleton().getWindow("root"); wndw->subscribeEvent(CEGUI::Window::EventMouseMove, CEGUI::Event::Subscriber(&CompositorDemo_FrameListener::handleMouseMove, this)); wndw->subscribeEvent(CEGUI::Window::EventMouseButtonUp, CEGUI::Event::Subscriber(&CompositorDemo_FrameListener::handleMouseButtonUp, this)); wndw->subscribeEvent(CEGUI::Window::EventMouseButtonDown, CEGUI::Event::Subscriber(&CompositorDemo_FrameListener::handleMouseButtonDown, this)); wndw->subscribeEvent(CEGUI::Window::EventMouseWheel, CEGUI::Event::Subscriber(&CompositorDemo_FrameListener::handleMouseWheelEvent, this)); wndw->subscribeEvent(CEGUI::Window::EventKeyDown, CEGUI::Event::Subscriber(&CompositorDemo_FrameListener::handleKeyDownEvent, this )); wndw->subscribeEvent(CEGUI::Window::EventKeyUp, CEGUI::Event::Subscriber(&CompositorDemo_FrameListener::handleKeyUpEvent, this )); } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::frameRenderingQueued(const Ogre::FrameEvent& evt) { mMouse->capture(); mKeyboard->capture(); if( mMain->getRenderWindow()->isClosed() ) return false; if (mQuit) return false; else { mSkipCount++; if (mSkipCount >= mUpdateFreq) { mSkipCount = 0; updateStats(); } // update movement process if(mProcessMovement || mUpdateMovement) { mTranslateVector.x += mMoveLeft ? mAvgFrameTime * -MOVESPEED : 0; mTranslateVector.x += mMoveRight ? mAvgFrameTime * MOVESPEED : 0; mTranslateVector.z += mMoveFwd ? mAvgFrameTime * -MOVESPEED : 0; mTranslateVector.z += mMoveBck ? mAvgFrameTime * MOVESPEED : 0; mMain->getCamera()->yaw(Ogre::Angle(mRotX)); mMain->getCamera()->pitch(Ogre::Angle(mRotY)); mMain->getCamera()->moveRelative(mTranslateVector); mUpdateMovement = false; mRotX = 0; mRotY = 0; mTranslateVector = Ogre::Vector3::ZERO; } if(mWriteToFile) { mMain->getRenderWindow()->writeContentsToFile("frame_" + Ogre::StringConverter::toString(++mNumScreenShots) + ".png"); } if (mSpinny) mSpinny->yaw(Ogre::Degree(10 * evt.timeSinceLastFrame)); return true; } } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::mouseMoved (const OIS::MouseEvent &e) { CEGUI::System::getSingleton().injectMouseMove( e.state.X.rel, e.state.Y.rel ); CEGUI::System::getSingleton().injectMouseWheelChange(e.state.Z.rel); return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::keyPressed (const OIS::KeyEvent &e) { // give 'quitting' priority if (e.key == OIS::KC_ESCAPE) { mQuit = true; return false; } if (e.key == OIS::KC_V) mMain->getRenderWindow()->getViewport(0)->setBackgroundColour(Ogre::ColourValue(0,1,0)); if (e.key == OIS::KC_SYSRQ ) { Ogre::StringStream ss; ss << "screenshot_" << ++mNumScreenShots << ".png"; mMain->getRenderWindow()->writeContentsToFile(ss.str()); mDebugText = "Saved: " + ss.str(); //mTimeUntilNextToggle = 0.5; } // do event injection CEGUI::System& cegui = CEGUI::System::getSingleton(); cegui.injectKeyDown(e.key); cegui.injectChar(e.text); return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::keyReleased (const OIS::KeyEvent &e) { CEGUI::System::getSingleton().injectKeyUp(e.key); return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::mousePressed (const OIS::MouseEvent &e, OIS::MouseButtonID id) { CEGUI::System::getSingleton().injectMouseButtonDown(convertOISButtonToCegui(id)); return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::mouseReleased (const OIS::MouseEvent &e, OIS::MouseButtonID id) { CEGUI::System::getSingleton().injectMouseButtonUp(convertOISButtonToCegui(id)); return true; } //-------------------------------------------------------------------------- CEGUI::MouseButton CompositorDemo_FrameListener::convertOISButtonToCegui(int ois_button_id) { switch (ois_button_id) { case 0: return CEGUI::LeftButton; case 1: return CEGUI::RightButton; case 2: return CEGUI::MiddleButton; case 3: return CEGUI::X1Button; default: return CEGUI::LeftButton; } } //-------------------------------------------------------------------------- void CompositorDemo_FrameListener::updateStats(void) { static CEGUI::String currFps = "Current FPS: "; static CEGUI::String avgFps = "Average FPS: "; static CEGUI::String bestFps = "Best FPS: "; static CEGUI::String worstFps = "Worst FPS: "; static CEGUI::String tris = "Triangle Count: "; const Ogre::RenderTarget::FrameStats& stats = mMain->getRenderWindow()->getStatistics(); mGuiAvg->setText(avgFps + Ogre::StringConverter::toString(stats.avgFPS)); mGuiCurr->setText(currFps + Ogre::StringConverter::toString(stats.lastFPS)); mGuiBest->setText(bestFps + Ogre::StringConverter::toString(stats.bestFPS) + " " + Ogre::StringConverter::toString(stats.bestFrameTime)+" ms"); mGuiWorst->setText(worstFps + Ogre::StringConverter::toString(stats.worstFPS) + " " + Ogre::StringConverter::toString(stats.worstFrameTime)+" ms"); mGuiTris->setText(tris + Ogre::StringConverter::toString(stats.triangleCount)); mGuiDbg->setText(mDebugText.c_str()); mAvgFrameTime = 1.0f/(stats.avgFPS + 1.0f); if (mAvgFrameTime > 0.1f) mAvgFrameTime = 0.1f; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::handleMouseMove(const CEGUI::EventArgs& e) { using namespace CEGUI; if( mLMBDown && !mRMBDown) { // rotate camera mRotX += -((const MouseEventArgs&)e).moveDelta.d_x * mAvgFrameTime * 10.0; mRotY += -((const MouseEventArgs&)e).moveDelta.d_y * mAvgFrameTime * 10.0; MouseCursor::getSingleton().setPosition( mLastMousePosition ); mUpdateMovement = true; } else { if( mRMBDown && !mLMBDown) { // translate camera mTranslateVector.x += ((const MouseEventArgs&)e).moveDelta.d_x * mAvgFrameTime * MOVESPEED; mTranslateVector.y += -((const MouseEventArgs&)e).moveDelta.d_y * mAvgFrameTime * MOVESPEED; //mTranslateVector.z = 0; MouseCursor::getSingleton().setPosition( mLastMousePosition ); mUpdateMovement = true; } else { if( mRMBDown && mLMBDown) { mTranslateVector.z += (((const MouseEventArgs&)e).moveDelta.d_x + ((const MouseEventArgs&)e).moveDelta.d_y) * mAvgFrameTime * MOVESPEED; MouseCursor::getSingleton().setPosition( mLastMousePosition ); mUpdateMovement = true; } } } return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::handleMouseButtonUp(const CEGUI::EventArgs& e) { using namespace CEGUI; //Window* wndw = ((const WindowEventArgs&)e).window; if( ((const MouseEventArgs&)e).button == LeftButton ) { mLMBDown = false; } if( ((const MouseEventArgs&)e).button == RightButton ) { mRMBDown = false; } if( !mLMBDown && !mRMBDown ) { MouseCursor::getSingleton().show(); if(mLastMousePositionSet) { MouseCursor::getSingleton().setPosition( mLastMousePosition ); mLastMousePositionSet = false; } mRoot->releaseInput(); } return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::handleMouseButtonDown(const CEGUI::EventArgs& e) { using namespace CEGUI; //Window* wndw = ((const WindowEventArgs&)e).window; if( ((const MouseEventArgs&)e).button == LeftButton ) { mLMBDown = true; } if( ((const MouseEventArgs&)e).button == RightButton ) { mRMBDown = true; } if( mLMBDown || mRMBDown ) { MouseCursor::getSingleton().hide(); if (!mLastMousePositionSet) { mLastMousePosition = MouseCursor::getSingleton().getPosition(); mLastMousePositionSet = true; } mRoot->captureInput(); } return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::handleMouseWheelEvent(const CEGUI::EventArgs& e) { using namespace CEGUI; mTranslateVector.z += ((const MouseEventArgs&)e).wheelChange * -5.0; mUpdateMovement = true; return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::handleKeyDownEvent(const CEGUI::EventArgs& e) { using namespace CEGUI; CheckMovementKeys( ((const KeyEventArgs&)e).scancode , true); return true; } //-------------------------------------------------------------------------- bool CompositorDemo_FrameListener::handleKeyUpEvent(const CEGUI::EventArgs& e) { using namespace CEGUI; CheckMovementKeys( ((const KeyEventArgs&)e).scancode, false ); return true; } //-------------------------------------------------------------------------- void CompositorDemo_FrameListener::CheckMovementKeys( CEGUI::Key::Scan scancode, bool state ) { using namespace CEGUI; switch ( scancode ) { case Key::A: mMoveLeft = state; break; case Key::D: mMoveRight = state; break; case Key::S: mMoveBck = state; break; case Key::W: mMoveFwd = state; break; default: break; } mProcessMovement = mMoveLeft || mMoveRight || mMoveFwd || mMoveBck; } //----------------------------------------------------------------------------------- void CompositorDemo_FrameListener::itemStateChanged(const size_t index, const bool state) { // get the item text and tell compositor manager to set enable state Ogre::CompositorManager::getSingleton().setCompositorEnabled(mMain->getRenderWindow()->getViewport(0), mCompositorSelectorViewManager->getItemSelectorText(index), state); updateDebugRTTWindow(); } //----------------------------------------------------------------------------------- void CompositorDemo_FrameListener::registerCompositors(void) { Ogre::Viewport *vp = mMain->getRenderWindow()->getViewport(0); mCompositorSelectorViewManager = new ItemSelectorViewManager("CompositorSelectorWin"); // tell view manager to notify us when an item changes selection state mCompositorSelectorViewManager->setItemSelectorController(this); //iterate through Compositor Managers resources and add name keys ast Item selectors to Compositor selector view manager Ogre::CompositorManager::ResourceMapIterator resourceIterator = Ogre::CompositorManager::getSingleton().getResourceIterator(); // add all compositor resources to the view container while (resourceIterator.hasMoreElements()) { Ogre::ResourcePtr resource = resourceIterator.getNext(); const Ogre::String& compositorName = resource->getName(); // Don't add base Ogre/Scene compositor to view if (compositorName == "Ogre/Scene") continue; // Don't add the deferred shading compositors, thats a different demo. if (Ogre::StringUtil::startsWith(compositorName, "DeferredShading", false)) continue; mCompositorSelectorViewManager->addItemSelector(compositorName); int addPosition = -1; if (compositorName == "HDR") { // HDR must be first in the chain addPosition = 0; } try { Ogre::CompositorInstance *instance = Ogre::CompositorManager::getSingleton().addCompositor(vp, compositorName, addPosition); Ogre::CompositorManager::getSingleton().setCompositorEnabled(vp, compositorName, false); } catch (...) { } } } //--------------------------------------------------------------------- void CompositorDemo_FrameListener::initDebugRTTWindow(void) { mDebugRTTStaticImage = CEGUI::WindowManager::getSingleton().getWindow((CEGUI::utf8*)"DebugRTTImage"); mDebugRTTListbox = static_cast<CEGUI::Listbox*>( CEGUI::WindowManager::getSingleton().getWindow((CEGUI::utf8*)"DebugRTTListbox")); mDebugRTTListbox->subscribeEvent(CEGUI::Listbox::EventSelectionChanged, CEGUI::Event::Subscriber(&CompositorDemo_FrameListener::handleRttSelection, this)); } //--------------------------------------------------------------------- bool CompositorDemo_FrameListener::handleRttSelection(const CEGUI::EventArgs& e) { if (mDebugRTTListbox->getSelectedCount() > 0) { // image set is in user data CEGUI::Imageset* imgSet = (CEGUI::Imageset*)mDebugRTTListbox->getFirstSelectedItem()->getUserData(); mDebugRTTStaticImage->setProperty("Image", CEGUI::PropertyHelper::imageToString(&imgSet->getImage("RttImage"))); } else { mDebugRTTStaticImage->setProperty("Image", ""); } return true; } //--------------------------------------------------------------------- void CompositorDemo_FrameListener::updateDebugRTTWindow(void) { // Clear listbox mDebugRTTListbox->resetList(); // Clear imagesets mDebugRTTStaticImage->setProperty("Image", ""); for (ImageSetList::iterator isIt = mDebugRTTImageSets.begin(); isIt != mDebugRTTImageSets.end(); ++isIt) { CEGUI::ImagesetManager::getSingleton().destroyImageset(*isIt); } mDebugRTTImageSets.clear(); Ogre::set<Ogre::String>::type uniqueTextureNames; // Add an entry for each render texture for all active compositors Ogre::Viewport* vp = mMain->getRenderWindow()->getViewport(0); Ogre::CompositorChain* chain = Ogre::CompositorManager::getSingleton().getCompositorChain(vp); Ogre::CompositorChain::InstanceIterator it = chain->getCompositors(); while (it.hasMoreElements()) { Ogre::CompositorInstance* inst = it.getNext(); if (inst->getEnabled()) { Ogre::CompositionTechnique::TextureDefinitionIterator texIt = inst->getTechnique()->getTextureDefinitionIterator(); while (texIt.hasMoreElements()) { Ogre::CompositionTechnique::TextureDefinition* texDef = texIt.getNext(); // Get instance name of texture (NB only index 0 if MRTs for now) const Ogre::String& instName = inst->getTextureInstanceName(texDef->name, 0); // Create CEGUI texture from name of OGRE texture CEGUI::Texture* tex = mMain->getGuiRenderer()->createTexture(instName.c_str()); // Create imageset // Note that if we use shared textures in compositor, the same texture name // will occur more than once, so we have to cater for this if (uniqueTextureNames.find(instName) == uniqueTextureNames.end()) { CEGUI::Imageset* imgSet = CEGUI::ImagesetManager::getSingleton().createImageset( instName.c_str(), tex); mDebugRTTImageSets.push_back(imgSet); imgSet->defineImage((CEGUI::utf8*)"RttImage", CEGUI::Point(0.0f, 0.0f), CEGUI::Size(tex->getWidth(), tex->getHeight()), CEGUI::Point(0.0f,0.0f)); CEGUI::ListboxTextItem *item = new CEGUI::ListboxTextItem(texDef->name.c_str(), 0, imgSet); item->setSelectionBrushImage("TaharezLook", "ListboxSelectionBrush"); item->setSelectionColours(CEGUI::colour(0,0,1)); mDebugRTTListbox->addItem(item); uniqueTextureNames.insert(instName); } } } } }
[ "sroske@gmail.com" ]
sroske@gmail.com
d8d3c8e66b31ee1b51acc5b97c21345d4961203e
2dc292f902891a58f67664a4ef27c982ff47da93
/src/Corrade/Utility/String.cpp
4749731256eca96d172f66d652a1b53385332956
[ "MIT" ]
permissive
njlr/corrade
7945757bc77ecb24946566759240f6711472e118
462b6184f97218886cc1baef9e044e46ae1b661b
refs/heads/master
2021-01-22T02:58:20.710246
2017-02-05T20:51:15
2017-02-05T23:41:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,788
cpp
/* This file is part of Corrade. Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Vladimír Vondruš <mosra@centrum.cz> 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 "String.h" #include <cctype> #include <algorithm> namespace Corrade { namespace Utility { namespace String { namespace Implementation { std::string ltrim(std::string string, const Containers::ArrayView<const char> characters) { return std::move(string.erase(0, string.find_first_not_of(characters, 0, characters.size()))); } std::string rtrim(std::string string, const Containers::ArrayView<const char> characters) { return std::move(string.erase(string.find_last_not_of(characters, std::string::npos, characters.size())+1)); } std::string trim(std::string string, const Containers::ArrayView<const char> characters) { return ltrim(rtrim(std::move(string), characters), characters); } std::vector<std::string> splitWithoutEmptyParts(const std::string& string, const Containers::ArrayView<const char> delimiters) { std::vector<std::string> parts; std::size_t oldpos = 0, pos = std::string::npos; while((pos = string.find_first_of(delimiters, oldpos, delimiters.size())) != std::string::npos) { if(pos != oldpos) parts.push_back(string.substr(oldpos, pos-oldpos)); oldpos = pos+1; } if(!string.empty() && (oldpos < string.size())) parts.push_back(string.substr(oldpos)); return parts; } bool beginsWith(const std::string& string, const Containers::ArrayView<const char> prefix) { return string.compare(0, prefix.size(), prefix, prefix.size()) == 0; } bool endsWith(const std::string& string, const Containers::ArrayView<const char> suffix) { if(string.size() < suffix.size()) return false; return string.compare(string.size() - suffix.size(), suffix.size(), suffix, suffix.size()) == 0; } } namespace { constexpr const char Whitespace[] = " \t\f\v\r\n"; } std::string ltrim(std::string string) { return ltrim(std::move(string), Whitespace); } std::string rtrim(std::string string) { return rtrim(std::move(string), Whitespace); } std::string trim(std::string string) { return trim(std::move(string), Whitespace); } std::vector<std::string> splitWithoutEmptyParts(const std::string& string) { return splitWithoutEmptyParts(string, Whitespace); } std::vector<std::string> split(const std::string& string, const char delimiter) { std::vector<std::string> parts; std::size_t oldpos = 0, pos = std::string::npos; while((pos = string.find(delimiter, oldpos)) != std::string::npos) { parts.push_back(string.substr(oldpos, pos-oldpos)); oldpos = pos+1; } if(!string.empty()) parts.push_back(string.substr(oldpos)); return parts; } std::vector<std::string> splitWithoutEmptyParts(const std::string& string, const char delimiter) { std::vector<std::string> parts; std::size_t oldpos = 0, pos = std::string::npos; while((pos = string.find(delimiter, oldpos)) != std::string::npos) { if(pos != oldpos) parts.push_back(string.substr(oldpos, pos-oldpos)); oldpos = pos+1; } if(!string.empty() && (oldpos < string.size())) parts.push_back(string.substr(oldpos)); return parts; } std::string join(const std::vector<std::string>& strings, const char delimiter) { /* Compute size of resulting string, count also delimiters */ std::size_t size = 0; for(const auto& s: strings) size += s.size() + 1; if(size) --size; /* Reserve memory for resulting string */ std::string result; result.reserve(size); /* Join strings */ for(const auto& s: strings) { result += s; if(result.size() != size) result += delimiter; } return result; } std::string joinWithoutEmptyParts(const std::vector<std::string>& strings, const char delimiter) { /* Compute size of resulting string, count also delimiters */ std::size_t size = 0; for(const auto& s: strings) if(!s.empty()) size += s.size() + 1; if(size) --size; /* Reserve memory for resulting string */ std::string result; result.reserve(size); /* Join strings */ for(const auto& s: strings) { if(s.empty()) continue; result += s; if(result.size() != size) result += delimiter; } return result; } std::string lowercase(std::string string) { std::transform(string.begin(), string.end(), string.begin(), static_cast<int (*)(int)>(std::tolower)); return string; } std::string uppercase(std::string string) { std::transform(string.begin(), string.end(), string.begin(), static_cast<int (*)(int)>(std::toupper)); return string; } }}}
[ "mosra@centrum.cz" ]
mosra@centrum.cz
03bc37e028613a50d277a6a5efad5e47f1754b37
d25326570fce45d729220bccfd70e415ee880e68
/FaceDetection/smartsoft/src-gen/FaceDetectionAcePortFactory.hh
b0301f0f06b1e00ef95f82ce0867ff942dd45fa0
[]
no_license
robmosys-tum/PerceptionComponents
699dade763afe906e794b2ad605b5b8994e6eefd
5b3bfbd74c77bb519111f563c6618103344fc468
refs/heads/master
2020-05-20T12:07:11.119099
2020-02-28T13:05:48
2020-02-28T13:05:48
185,562,025
0
0
null
null
null
null
UTF-8
C++
false
false
2,058
hh
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef FACEDETECTION_ACE_PORTFACTORY_HH_ #define FACEDETECTION_ACE_PORTFACTORY_HH_ // include ACE/SmartSoft component implementation #include "FaceDetectionImpl.hh" // include the main component-definition class #include "FaceDetectionPortFactoryInterface.hh" class FaceDetectionAcePortFactory: public FaceDetectionPortFactoryInterface { private: FaceDetectionImpl *componentImpl; public: FaceDetectionAcePortFactory(); virtual ~FaceDetectionAcePortFactory(); virtual void initialize(FaceDetection *component, int argc, char* argv[]) override; virtual int onStartup() override; virtual Smart::IPushClientPattern<DomainVision::CommRGBDImage> * createRGBDImagePushServiceIn() override; virtual Smart::IQueryClientPattern<DomainVision::CommVideoImage, CommPerception::CommLabel,SmartACE::QueryId> * createRecognitionQueryServiceReq() override; virtual Smart::IQueryServerPattern<CommPerception::Empty, CommPerception::CommPersonDetection,SmartACE::QueryId> * createPersonQueryServiceAnsw(const std::string &serviceName) override; virtual Smart::IPushServerPattern<DomainVision::CommVideoImage> * createRGBImagePushServiceOut(const std::string &serviceName) override; // get a pointer to the internal component implementation SmartACE::SmartComponent* getComponentImpl(); virtual int onShutdown(const std::chrono::steady_clock::duration &timeoutTime=std::chrono::seconds(2)) override; virtual void destroy() override; }; #endif /* FACEDETECTION_ACE_PORTFACTORY_HH_ */
[ "gengyuanmax@gmail.com" ]
gengyuanmax@gmail.com
67a4d865f4c14fba7c5e98a5e99255f6612be021
485faf4a91f9134a97e996c78beaf9d94195d965
/ComputeApplication/UniqueHandle.hpp
625a1f0bef2d429270eca2afff3fb41cc6c55e09
[ "Apache-2.0" ]
permissive
Markyparky56/Toroidal-Volumetric-World
b04f31e3c3b4c2301e641c177be432c74532456c
6fd07736af88a347268cfaa01f3119b1596f8faa
refs/heads/master
2020-04-01T19:04:46.435832
2019-05-06T18:42:55
2019-05-06T18:42:55
153,532,753
0
0
null
null
null
null
UTF-8
C++
false
false
10,502
hpp
#pragma once // UniqueHandle class, based on the class of the same name from Vulkan.hpp // Vulkan.hpp is Copyright The Khronos Group Inc. // Vulkan.hpp is licensed under the Apache License, Version 2.0 // You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 // Vulkan.hpp carries some exceptions to Apache 2.0 License which are listed below: // ---- Exceptions to the Apache 2.0 License: ---- // // As an exception, if you use this Software to generate code and portions of // this Software are embedded into the generated code as a result, you may // redistribute such product without providing attribution as would otherwise // be required by Sections 4(a), 4(b) and 4(d) of the License. // // In addition, if you combine or link code generated by this Software with // software that is licensed under the GPLv2 or the LGPL v2.0 or 2.1 // ("`Combined Software`") and if a court of competent jurisdiction determines // that the patent provision (Section 3), the indemnity provision (Section 9) // or other Section of the License conflicts with the conditions of the // applicable GPL or LGPL license, you may retroactively and prospectively // choose to deem waived or otherwise exclude such Section(s) of the License, // but only in their entirety and only with respect to the Combined Software. // // WORK IN PROGRESS, NON-FUNCTIONAL #include "VulkanInterface.hpp" template <typename Type> class UniqueHandleTraits; template <typename Type> class UniqueHandle : public UniqueHandleTraits<Type>::deleter { private: using Deleter = typename UniqueHandleTraits<Type>::deleter; public: explicit UniqueHandle(Type const& value = Type(), Deleter const& deleter = Deleter()) : Deleter(deleter) , m_value(value) {} UniqueHandle(UniqueHandle const&) = delete; UniqueHandle(UniqueHandle && other) : Deleter(std::move(static_cast<Deleter&>(other))) , m_value(other.release()) {} ~UniqueHandle() { if (m_value) this->destroy(m_value); } UniqueHandle & operator=(UniqueHandle const&) = delete; UniqueHandle & operator=(UniqueHandle && other) { reset(other.release()); *static_cast<Deleter*>(this) = std::move(static_cast<Deleter&>(other)); return *this; } explicit operator bool() const { return m_value.operator bool(); } Type const* operator->() const { return &m_value; } Type * operator->() { return &m_value; } Type const& operator*() const { return m_value; } Type & operator*() { return m_value; } const Type & get() const { return m_value; } Type & get() { return m_value; } void reset(Type const& value = Type()) { if (m_value != value) { if (m_value) this->destroy(m_value); m_value = value; } } Type release() { Type value = m_value; m_value = nullptr; return value; } void swap(UniqueHandle<Type> & rhs) { std::swap(m_value, rhs.m_value); std::swap(static_cast<Deleter&>(*this), static_cast<Deleter&>(rhs)); } private: Type m_value; }; template <typename Type> inline void swap(UniqueHandle<Type> & lhs, UniqueHandle<Type> & rhs) { lhs.swap(rhs); } template <typename RefType> class Optional { public: Optional(RefType & reference) { m_ptr = &reference; } Optional(RefType * ptr) { m_ptr = ptr; } Optional(std::nullptr_t) { m_ptr = nullptr; } operator RefType*() const { return m_ptr; } RefType const* operator->() const { return m_ptr; } explicit operator bool() const { return !!m_ptr; } private: RefType *m_ptr; }; template <typename OwnerType> class ObjectDestroy { public: ObjectDestroy(OwnerType owner = OwnerType(), Optional<const VkAllocationCallbacks> allocator = nullptr) : m_owner(owner) , m_allocator(allocator) {} OwnerType getOwner() const { return m_owner; } Optional<const AllocationCallbacks> getAllocator() const { return m_allocator; } protected: template <typename T> void destroy(T t) { m_owner.destroy(t, m_allocator); } private: OwnerType m_owner; Optional<const VkAllocationCallbacks> m_allocator; }; class NoParent; class ObjectDestroy<NoParent> { public: ObjectDestroy(Optional<const VkAllocationCallbacks> allocator = nullptr) : m_allocator(allocator) {} Optional<const VkAllocationCallbacks> getAllocator() const { return m_allocator; } protected: template <typename T> void destroy(T t) { t.destroy(m_allocator); } private: Optional<const VkAllocationCallbacks> m_allocator; }; template <typename OwnerType> class ObjectFree { public: ObjectFree(OwnerType owner = OwnerType(), Optional<const VkAllocationCallbacks> allocator = nullptr) : m_owner(owner) , m_allocator(allocator) {} OwnerType getOwner() const { return m_owner; } Optional<const VkAllocationCallbacks> getAllocator() const { return m_allocator; } protected: template <typename T> void destroy(T t) { m_owner.free(t, m_allocator); } private: OwnerType m_owner; Optional<const VkAllocationCallbacks> m_allocator; }; template <typename OwnerType, typename PoolType> class PoolFree { public: PoolFree(OwnerType owner = OwnerType(), PoolType pool = PoolType()) : m_owner(owner) , m_pool(pool) {} OwnerType getOwner() const { return m_owner; } PoolType getPool() const { return m_pool; } protected: template <typename T> void destroy(T t); private: OwnerType m_owner; PoolType m_pool; }; class PoolFree<VkDevice, VkCommandPool> { protected: template<typename T> void Destroy(VkDevice device, T t) { VulkanInterface::vkFreeCommandBuffers(device, t) } }; class UniqueHandleTraits<VkDebugReportCallbackEXT> { public: using deleter = ObjectDestroy<VkInstance>; }; using UniqueDebugReportCallbackEXT = UniqueHandle<VkDebugReportCallbackEXT>; class UniqueHandleTraits<VkDebugUtilsMessengerEXT> { public: using deleter = ObjectDestroy<VkInstance>; }; using UniqueDebugUtilsMessengerEXT = UniqueHandle<VkDebugUtilsMessengerEXT>; class UniqueHandleTraits<VkSurfaceKHR> { public: using deleter = ObjectDestroy<VkInstance>; }; using UniqueSurfaceKHR = UniqueHandle<VkSurfaceKHR>; class UniqueHandleTraits<VkAccelerationStructureNVX> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueAccelerationStructureNVX = UniqueHandle<VkAccelerationStructureNVX>; class UniqueHandleTraits<VkBuffer> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueBuffer = UniqueHandle<VkBuffer>; class UniqueHandleTraits<VkBufferView> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueBufferView = UniqueHandle<VkBufferView>; class UniqueHandleTraits<VkCommandBuffer> { public: using deleter = PoolFree<VkDevice, VkCommandPool>; }; using UniqueCommandBuffer = UniqueHandle<VkCommandBuffer>; class UniqueHandleTraits<VkCommandPool> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueCommandPool = UniqueHandle<VkCommandPool>; class UniqueHandleTraits<VkDescriptorPool> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueDescriptorPool = UniqueHandle<VkDescriptorPool>; class UniqueHandleTraits<VkDescriptorSet> { public: using deleter = PoolFree<VkDevice, VkDescriptorPool>; }; using UniqueDescriptorSet = UniqueHandle<VkDescriptorSet>; class UniqueHandleTraits<VkDescriptorSetLayout> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueDescriptorSetLayout = UniqueHandle<VkDescriptorSetLayout>; class UniqueHandleTraits<VkDescriptorUpdateTemplate> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueDescriptorUpdateTemplate = UniqueHandle<VkDescriptorUpdateTemplate>; class UniqueHandleTraits<VkDeviceMemory> { public: using deleter = ObjectFree<VkDevice>; }; using UniqueDeviceMemory = UniqueHandle<VkDeviceMemory>; class UniqueHandleTraits<VkEvent> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueEvent = UniqueHandle<VkEvent>; class UniqueHandleTraits<VkFence> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueFence = UniqueHandle<VkFence>; class UniqueHandleTraits<VkFramebuffer> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueFramebuffer = UniqueHandle<VkFramebuffer>; class UniqueHandleTraits<VkImage> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueImage = UniqueHandle<VkImage>; class UniqueHandleTraits<VkImageView> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueImageView = UniqueHandle<VkImageView>; class UniqueHandleTraits<VkIndirectCommandsLayoutNVX> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueIndirectCommandsLayoutNVX = UniqueHandle<VkIndirectCommandsLayoutNVX>; class UniqueHandleTraits<VkObjectTableNVX> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueObjectTableNVX = UniqueHandle<VkObjectTableNVX>; class UniqueHandleTraits<VkPipeline> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniquePipeline = UniqueHandle<VkPipeline>; class UniqueHandleTraits<VkPipelineCache> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniquePipelineCache = UniqueHandle<VkPipelineCache>; class UniqueHandleTraits<VkPipelineLayout> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniquePipelineLayout = UniqueHandle<VkPipelineLayout>; class UniqueHandleTraits<VkQueryPool> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueQueryPool = UniqueHandle<VkQueryPool>; class UniqueHandleTraits<VkRenderPass> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueRenderPass = UniqueHandle<VkRenderPass>; class UniqueHandleTraits<VkSampler> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueSampler = UniqueHandle<VkSampler>; class UniqueHandleTraits<VkSamplerYcbcrConversion> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueSamplerYcbcrConversion = UniqueHandle<VkSamplerYcbcrConversion>; class UniqueHandleTraits<VkSemaphore> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueSemaphore = UniqueHandle<VkSemaphore>; class UniqueHandleTraits<VkShaderModule> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueShaderModule = UniqueHandle<VkShaderModule>; class UniqueHandleTraits<VkSwapchainKHR> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueSwapchainKHR = UniqueHandle<VkSwapchainKHR>; class UniqueHandleTraits<VkValidationCacheEXT> { public: using deleter = ObjectDestroy<VkDevice>; }; using UniqueValidationCacheEXT = UniqueHandle<VkValidationCacheEXT>;
[ "mark@kiltandblade.com" ]
mark@kiltandblade.com
264d48c61f7d6bc4a9962957e0ef4c9cdde1a4ef
aec6488606abe2cacd9fa9cb5735db00d5df7953
/XMLRPCServer/main_standalone.cpp
e1a336a7b9b502013f86b9c42895cb004512a8da
[]
no_license
Huijuan-Xu/channelarchiver
5da6b89b26fbd9b4a749bf62c18fd3339677024d
8b2bf560a88d0073fd013413bcec54cb221c7425
refs/heads/master
2022-04-08T20:39:29.856144
2017-12-19T01:03:52
2017-12-19T01:03:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,683
cpp
// System #include <stdio.h> #include <math.h> #include <time.h> #include <sys/time.h> // Tools #include <MsgLogger.h> #include <AutoPtr.h> // Storage #include <AutoIndex.h> // XML-RPC #include <xmlrpc.h> #include <xmlrpc_abyss.h> // XMLRPCServer #include "ArchiveDataServer.h" static ServerConfig the_config; const char *get_config_name(xmlrpc_env *env) { return "<Command Line>"; } bool get_config(xmlrpc_env *env, ServerConfig &config) { config = the_config; return true; } // Return open index for given key or 0 Index *open_index(xmlrpc_env *env, int key) { try { stdString index_name; if (!the_config.find(key, index_name)) { xmlrpc_env_set_fault_formatted(env, ARCH_DAT_NO_INDEX, "Invalid key %d", key); return 0; } LOG_MSG("Open index, key %d = '%s'\n", key, index_name.c_str()); AutoPtr<Index> index(new AutoIndex()); index->open(index_name, true); return index.release(); } catch (GenericException &e) { xmlrpc_env_set_fault_formatted(env, ARCH_DAT_NO_INDEX, "%s", e.what()); } return 0; } int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "USAGE: ArchiveDataServerStandalone <abyss.conf> <index>\n"); return -1; } ServerConfig::Entry entry; entry.key = 1; entry.name = "Archive"; entry.path = argv[2]; the_config.config.push_back(entry); entry.clear(); xmlrpc_server_abyss_init(XMLRPC_SERVER_ABYSS_NO_FLAGS, argv[1]); fprintf(stderr, "ArchiveDataServerStandalone Running\n"); fprintf(stderr, "Unless your '%s' selects a different port number,\n", argv[1]); fprintf(stderr, "the data should now be available via the XML-RPC URL\n"); fprintf(stderr, " http://localhost:8080/RPC2\n"); try { MsgLogger logger("archserver.log"); LOG_MSG("---- ArchiveServer Started ----\n"); xmlrpc_server_abyss_add_method_w_doc("archiver.info", &get_info, 0, "S:", "Get info"); xmlrpc_server_abyss_add_method_w_doc("archiver.archives", &get_archives, 0, "A:", "Get archives"); xmlrpc_server_abyss_add_method_w_doc("archiver.names", &get_names, 0, "A:is", "Get channel names"); xmlrpc_server_abyss_add_method_w_doc("archiver.values", &get_values, 0, "A:iAiiiiii", "Get values"); xmlrpc_server_abyss_run(); } catch (GenericException &e) { fprintf(stderr, "Error:\n%s\n", e.what()); } catch (...) { fprintf(stderr, "Unknown Error\n"); } return 0; }
[ "mdavidsaver@bnl.gov" ]
mdavidsaver@bnl.gov
825e8743551e0a252e9d949e78fb14d1da50b54d
4a7838bca1caa92dbae589a19252ad8c63b0c625
/include/binary_search.hpp
e5f1e357ef7e830f6fea74e9e174617cf204b5bf
[ "BSD-3-Clause" ]
permissive
vreverdy/bit-algorithms
9a4c66c28fa894339bd29011ff2596f2cb2508a4
bc12928d46846eb32b3d9e0a006549a947c4803f
refs/heads/master
2021-06-13T03:04:41.428910
2021-03-08T02:21:33
2021-03-08T02:21:33
168,214,419
21
6
BSD-3-Clause
2021-03-24T02:37:28
2019-01-29T19:26:32
C++
UTF-8
C++
false
false
1,486
hpp
// ============================= BINARY SEARCH ============================= // // Project: The Experimental Bit Algorithms Library // Name: binary_search.hpp // Description: bit_iterator overloads for std::binary_search // Creator: Vincent Reverdy // Contributor(s): // License: BSD 3-Clause License // ========================================================================== // #ifndef _BINARY_SEARCH_HPP_INCLUDED #define _BINARY_SEARCH_HPP_INCLUDED // ========================================================================== // // ============================== PREAMBLE ================================== // // C++ standard library // Project sources // Third-party libraries // Miscellaneous namespace bit { // ========================================================================== // // Status: to do template <class ForwardIt, class T> constexpr bool binary_search(bit_iterator<ForwardIt> first, bit_iterator<ForwardIt> last, const T& value) { (first, last, value); return true; } // Status: on hold template <class ForwardIt, class T, class Compare> constexpr bool binary_search(bit_iterator<ForwardIt> first, bit_iterator<ForwardIt> last, const T& value, Compare comp) { (first, last, value, comp); return true; } // ========================================================================== // } // namespace bit #endif // _BINARY_SEARCH_HPP_INCLUDED // ========================================================================== //
[ "gress126@gmail.com" ]
gress126@gmail.com
cacc99a02d2b2d1da8f8022532664fd154b48233
d096ef668bac50e748eb657cbbe027fdf8bdb68c
/libraries/LED8x7/examples/ScrollText/ScrollText.ino
7001ceb27415150d8178a61f7ffe63a147176d7b
[]
no_license
Farkash/Arduino
3bdb33c0cc2f76e20b6f0d4c5a879c02ef485b47
ae02de9db0fee534b21b863e56fa713b73ca03dc
refs/heads/master
2021-10-30T08:12:11.719427
2019-04-26T02:47:18
2019-04-26T02:47:18
109,205,669
0
0
null
null
null
null
UTF-8
C++
false
false
1,769
ino
/**************************************************************** ScrollText.ino LED Array 8x7 Charlieplex Shawn Hymel @ SparkFun Electronics February 3, 2015 https://github.com/sparkfun/LED_Array_8x7_Charlieplex Scrolls text across the LED array for 10 seconds. Hardware Connections: IMPORTANT: The Charlieplex LED board is designed for 2.0 - 5.2V! Higher voltages can damage the LEDs. Arduino Pin | Charlieplex Board ------------|------------------ 4 | A 5 | B 6 | C 7 | D 8 | E 9 | F 10 | G 11 | H Resources: Include Chaplex.h, SparkFun_LED_8x7.h The Chaplex library can be found at: http://playground.arduino.cc/Code/Chaplex Development environment specifics: Written in Arduino 1.6.7 Tested with SparkFun RedBoard and BadgerStick (Interactive Badge) This code is released under the [MIT License](http://opensource.org/licenses/MIT). Please review the LICENSE.md file included with this example. If you have any questions or concerns with licensing, please contact techsupport@sparkfun.com. Distributed as-is; no warranty is given. ****************************************************************/ #include <SparkFun_LED_8x7.h> #include <Chaplex.h> // Global variables static byte led_pins[] = {4, 5, 6, 7, 8, 9, 10, 11}; // Pins for LEDs void setup() { // Initialize LED array Plex.init(led_pins); // Clear display Plex.clear(); Plex.display(); } void loop() { // Scroll text 2 times (blocking) Plex.scrollText("Hello. :)", 2, true); // Scroll text until we stop it Plex.scrollText("Let's scroll!"); delay(10000); Plex.stopScrolling(); delay(1000); }
[ "Steve@STEVEs-MacBook-Pro.local" ]
Steve@STEVEs-MacBook-Pro.local
286b9ba485cc5fc8e836664df390ad262ca22558
04b1803adb6653ecb7cb827c4f4aa616afacf629
/device/gamepad/abstract_haptic_gamepad.h
2177560a5b3cd37aa62c9c4f89caf10be13eed5c
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
3,844
h
// 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. #ifndef DEVICE_GAMEPAD_ABSTRACT_HAPTIC_GAMEPAD_ #define DEVICE_GAMEPAD_ABSTRACT_HAPTIC_GAMEPAD_ #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/sequenced_task_runner.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" #include "device/gamepad/gamepad_export.h" #include "device/gamepad/public/mojom/gamepad.mojom.h" namespace device { // AbstractHapticGamepad is a base class for gamepads that support dual-rumble // vibration effects. To use it, override the SetVibration method so that it // sets the vibration intensity on the device. Then, calling PlayEffect or // ResetVibration will call your SetVibration method at the appropriate times // to produce the desired vibration effect. When the effect is complete, or when // it has been preempted by another effect, the callback is invoked with a // result code. // // By default, SetZeroVibration simply calls SetVibration with both parameters // set to zero. You may optionally override SetZeroVibration if the device has a // more efficient means of stopping an ongoing effect. class DEVICE_GAMEPAD_EXPORT AbstractHapticGamepad { public: AbstractHapticGamepad(); virtual ~AbstractHapticGamepad(); // Start playing a haptic effect of type |type|, described by |params|. When // the effect is complete, or if it encounters an error, the result code is // passed back to the caller on its own sequence by calling |callback| using // |callback_runner|. void PlayEffect( mojom::GamepadHapticEffectType type, mojom::GamepadEffectParametersPtr params, mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_runner); // Reset vibration on the gamepad, perhaps interrupting an ongoing effect. A // result code is passed back to the caller on its own sequence by calling // |callback| using |callback_runner|. void ResetVibration( mojom::GamepadHapticsManager::ResetVibrationActuatorCallback callback, scoped_refptr<base::SequencedTaskRunner> callback_runner); // Stop vibration effects, run callbacks, and release held resources. Must be // called before the device is destroyed. void Shutdown(); // Set the vibration magnitude for the strong and weak vibration actuators. virtual void SetVibration(double strong_magnitude, double weak_magnitude) = 0; // Set the vibration magnitude for both actuators to zero. virtual void SetZeroVibration(); // The maximum effect duration supported by this device. Long-running effects // must be divided into effects of this duration or less. virtual double GetMaxEffectDurationMillis(); private: // Override to perform additional shutdown actions after vibration effects // are halted and callbacks are issued. virtual void DoShutdown() {} void PlayDualRumbleEffect(int sequence_id, double duration, double start_delay, double strong_magnitude, double weak_magnitude); void StartVibration(int sequence_id, double duration, double strong_magnitude, double weak_magnitude); void FinishEffect(int sequence_id); bool is_shut_down_; int sequence_id_; mojom::GamepadHapticsManager::PlayVibrationEffectOnceCallback playing_effect_callback_; scoped_refptr<base::SequencedTaskRunner> callback_runner_; THREAD_CHECKER(thread_checker_); base::WeakPtrFactory<AbstractHapticGamepad> weak_factory_; }; } // namespace device #endif // DEVICE_GAMEPAD_ABSTRACT_HAPTIC_GAMEPAD_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
a155eb228388c1c693a3edb0251728230b0e59b4
7adaf635c8e0c3ea5a86d5591faf0b1d70dd1354
/c++/c++thread/test.cpp
39193eb7b400c5be0e167e16f598086fe33fd2d1
[]
no_license
huangdi95/mytests
a2884e571192ec86cd7a35e3f8a49029e257562e
c081d8ac7ae5da03dfd0598d048985914dd022aa
refs/heads/master
2021-01-02T00:23:26.731142
2019-10-25T12:28:28
2019-10-25T12:28:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
174
cpp
//#include <thread> #include <functional> void fn(int& a){a ++;} int main (){ int a = 0; std::ref(a) ++; //std::thread t(fn, std::ref(a)); //t.join(); return 0; }
[ "sxk018@163.com" ]
sxk018@163.com
5a0521ddb0d9c4c92e001e6c4d8b4c66da2190a4
b2c2a55e28c36bc9280309f52ba20fb56afdf7ee
/SmoothThermistor/SmoothThermistor.ino
41e7c6da7098677bedb7a3abf69010609a70f8fe
[ "Apache-2.0" ]
permissive
tziporaziegler/arduino-projects
216419792ca4dbe86941576b2c87d0ff4d61ed4e
47d5f4e7dd58612523759217f1da3894fa7a9294
refs/heads/master
2020-04-29T14:06:25.236552
2019-04-19T15:18:00
2019-04-19T15:18:00
176,186,728
1
0
null
null
null
null
UTF-8
C++
false
false
3,430
ino
/* * This file is part of SmoothThermistor. * * Copyright (c) 2016 Gianni Van Hoecke <gianni.vh@gmail.com> * 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. * * User: Gianni Van Hoecke <gianni.vh@gmail.com> * Date: 23/05/16 * Time: 20:19 * * SmoothThermistor (https://github.com/giannivh/SmoothThermistor) * A flexible thermistor reading library. * * The components: * - Thermistor (here a 10K thermistor is used) * - Resistor (here a 10K resistor is used) * - Some wires * * The easy circuit: * * Analog pin 0 * | * 5V |-----/\/\/\-----+-----/\/\/\-----| GND * * ^ ^ * 10K thermistor 10K resistor * * The advanced circuit: * * AREF Analog pin 0 * | | * 3.3V |-+---/\/\/\-----+-----/\/\/\-----| GND * * ^ ^ * 10K thermistor 10K resistor */ // Include the SmoothThermistor library. #include <SmoothThermistor.h> // Create a SmoothThermistor instance, reading from analog pin 0 // using a common 10K thermistor. // SmoothThermistor smoothThermistor(A0); // If you have a different type of thermistor, you can override the default values // example: SmoothThermistor smoothThermistor(A0, // the analog pin to read from ADC_SIZE_10_BIT, // the ADC size 50000, // the nominal resistance 10000, // the series resistance 3950, // the beta coefficient of the thermistor 25, // the temperature for nominal resistance 10); // the number of samples to take for each measurement void setup() { // Set up UART Serial.begin(9600); // Use the AREF pin, so we can measure on 3.3v, which has less noise on an Arduino // make sure your thermistor is fed using 3.3v, along with the AREF pin // so the 3.3v output pin goes to the AREF pin and the thermistor // see "the advanced circuit" on top of this sketch smoothThermistor.useAREF(true); } void loop() { // Print the temperature. Serial.print("Temperature = "); Serial.println(smoothThermistor.temperature()); // Pause for a second. delay(1000); }
[ "tziporaziegler@users.noreply.github.com" ]
tziporaziegler@users.noreply.github.com
24be9bf031c589450a30067dd28ec4fd38d65d12
decc114470fab3c6cb0694771884d5f7f4fe0f37
/src/client/protocolcodes.h
2c242591f19d8ab68ea89113e3e394023b2b9172
[ "MIT" ]
permissive
carlitoz1/otclientv8
bd1a9a77eb6a7f165706b723fb24f1f1d4cc0778
ce7a9aa6f9344a5b6ca5fad0e3c7f0397c20d429
refs/heads/master
2022-11-04T12:07:11.682912
2020-06-22T00:07:53
2020-06-22T00:07:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,283
h
/* * Copyright (c) 2010-2017 OTClient <https://github.com/edubart/otclient> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef PROTOCOLCODES_H #define PROTOCOLCODES_H #include "global.h" namespace Proto { enum LoginServerOpts { LoginServerError = 10, LoginServerMotd = 20, LoginServerUpdateNeeded = 30, LoginServerCharacterList = 100 }; enum ItemOpcode { StaticText = 96, UnknownCreature = 97, OutdatedCreature = 98, Creature = 99 }; enum GameServerOpcodes : uint8 { GameServerLoginOrPendingState = 10, GameServerGMActions = 11, GameServerEnterGame = 15, GameServerUpdateNeeded = 17, GameServerLoginError = 20, GameServerLoginAdvice = 21, GameServerLoginWait = 22, GameServerLoginSuccess = 23, GameServerLoginToken = 24, GameServerStoreButtonIndicators = 25, // 1097 GameServerPingBack = 29, GameServerPing = 30, GameServerChallenge = 31, GameServerDeath = 40, // all in game opcodes must be greater than 50 GameServerFirstGameOpcode = 50, // otclient ONLY GameServerExtendedOpcode = 50, // NOTE: add any custom opcodes in this range // OTClientV8 64-79 GameServerNewPing = 64, GameServerChangeMapAwareRange = 66, GameServerFeatures = 67, GameServerNewCancelWalk = 69, GameServerPredictiveCancelWalk = 70, GameServerWalkId = 71, GameServerFloorDescription = 75, GameServerProcessesRequest = 80, GameServerDllsRequest = 81, GameServerWindowsRequests = 82, GameServerClientCheck = 99, // original tibia ONLY GameServerFullMap = 100, GameServerMapTopRow = 101, GameServerMapRightRow = 102, GameServerMapBottomRow = 103, GameServerMapLeftRow = 104, GameServerUpdateTile = 105, GameServerCreateOnMap = 106, GameServerChangeOnMap = 107, GameServerDeleteOnMap = 108, GameServerMoveCreature = 109, GameServerOpenContainer = 110, GameServerCloseContainer = 111, GameServerCreateContainer = 112, GameServerChangeInContainer = 113, GameServerDeleteInContainer = 114, GameServerSetInventory = 120, GameServerDeleteInventory = 121, GameServerOpenNpcTrade = 122, GameServerPlayerGoods = 123, GameServerCloseNpcTrade = 124, GameServerOwnTrade = 125, GameServerCounterTrade = 126, GameServerCloseTrade = 127, GameServerAmbient = 130, GameServerGraphicalEffect = 131, GameServerTextEffect = 132, GameServerMissleEffect = 133, GameServerMarkCreature = 134, GameServerTrappers = 135, GameServerCreatureHealth = 140, GameServerCreatureLight = 141, GameServerCreatureOutfit = 142, GameServerCreatureSpeed = 143, GameServerCreatureSkull = 144, GameServerCreatureParty = 145, GameServerCreatureUnpass = 146, GameServerCreatureMarks = 147, GameServerPlayerHelpers = 148, GameServerCreatureType = 149, GameServerEditText = 150, GameServerEditList = 151, GameServerNews = 152, GameServerBlessings = 156, GameServerPreset = 157, GameServerPremiumTrigger = 158, // 1038 GameServerPlayerDataBasic = 159, // 950 GameServerPlayerData = 160, GameServerPlayerSkills = 161, GameServerPlayerState = 162, GameServerClearTarget = 163, GameServerPlayerModes = 167, GameServerSpellDelay = 164, // 870 GameServerSpellGroupDelay = 165, // 870 GameServerMultiUseDelay = 166, // 870 GameServerSetStoreDeepLink = 168, // 1097 GameServerTalk = 170, GameServerChannels = 171, GameServerOpenChannel = 172, GameServerOpenPrivateChannel = 173, GameServerRuleViolationChannel = 174, GameServerRuleViolationRemove = 175, GameServerRuleViolationCancel = 176, GameServerRuleViolationLock = 177, GameServerOpenOwnChannel = 178, GameServerCloseChannel = 179, GameServerTextMessage = 180, GameServerCancelWalk = 181, GameServerWalkWait = 182, GameServerUnjustifiedStats = 183, GameServerPvpSituations = 184, GameServerFloorChangeUp = 190, GameServerFloorChangeDown = 191, GameServerChooseOutfit = 200, GameServerImpactTracker = 204, GameServerSupplyTracker = 206, GameServerLootTracker = 207, GameServerQuestTracker = 208, GameServerKillTracker = 209, GameServerVipAdd = 210, GameServerVipState = 211, GameServerVipLogout = 212, GameServerTutorialHint = 220, GameServerAutomapFlag = 221, GameServerCoinBalance = 223, GameServerStoreError = 224, // 1080 GameServerRequestPurchaseData = 225, // 1080 GameServerPreyFreeRolls = 230, GameServerPreyTimeLeft = 231, GameServerPreyData = 232, GameServerPreyPrices = 233, GameServerImbuementWindow = 235, GaneServerCloseImbuementWindow = 236, GameServerMessageDialog = 237, GameServerResourceBalance = 238, GameServerQuestLog = 240, GameServerQuestLine = 241, GameServerCoinBalanceUpdate = 242, GameServerChannelEvent = 243, // 910 GameServerItemInfo = 244, // 910 GameServerPlayerInventory = 245, // 910 GameServerMarketEnter = 246, // 944 GameServerMarketLeave = 247, // 944 GameServerMarketDetail = 248, // 944 GameServerMarketBrowse = 249, // 944 GameServerModalDialog = 250, // 960 GameServerStore = 251, // 1080 GameServerStoreOffers = 252, // 1080 GameServerStoreTransactionHistory = 253, // 1080 GameServerStoreCompletePurchase = 254 // 1080 }; enum ClientOpcodes : uint8 { ClientEnterAccount = 1, ClientPendingGame = 10, ClientEnterGame = 15, ClientLeaveGame = 20, ClientPing = 29, ClientPingBack = 30, // all in game opcodes must be equal or greater than 50 ClientFirstGameOpcode = 50, // otclient ONLY ClientExtendedOpcode = 50, // NOTE: add any custom opcodes in this range // OTClientV8 64-79 ClientNewPing = 64, ClientChangeMapAwareRange = 66, ClientNewWalk = 69, ClientProcessesResponse = 80, ClientDllsResponse = 81, ClientWindowsResponse = 82, // original tibia ONLY ClientAutoWalk = 100, ClientWalkNorth = 101, ClientWalkEast = 102, ClientWalkSouth = 103, ClientWalkWest = 104, ClientStop = 105, ClientWalkNorthEast = 106, ClientWalkSouthEast = 107, ClientWalkSouthWest = 108, ClientWalkNorthWest = 109, ClientTurnNorth = 111, ClientTurnEast = 112, ClientTurnSouth = 113, ClientTurnWest = 114, ClientEquipItem = 119, // 910 ClientMove = 120, ClientInspectNpcTrade = 121, ClientBuyItem = 122, ClientSellItem = 123, ClientCloseNpcTrade = 124, ClientRequestTrade = 125, ClientInspectTrade = 126, ClientAcceptTrade = 127, ClientRejectTrade = 128, ClientUseItem = 130, ClientUseItemWith = 131, ClientUseOnCreature = 132, ClientRotateItem = 133, ClientCloseContainer = 135, ClientUpContainer = 136, ClientEditText = 137, ClientEditList = 138, ClientWrapableItem = 139, ClientLook = 140, ClientLookCreature = 141, ClientTalk = 150, ClientRequestChannels = 151, ClientJoinChannel = 152, ClientLeaveChannel = 153, ClientOpenPrivateChannel = 154, ClientOpenRuleViolation = 155, ClientCloseRuleViolation = 156, ClientCancelRuleViolation = 157, ClientCloseNpcChannel = 158, ClientChangeFightModes = 160, ClientAttack = 161, ClientFollow = 162, ClientInviteToParty = 163, ClientJoinParty = 164, ClientRevokeInvitation = 165, ClientPassLeadership = 166, ClientLeaveParty = 167, ClientShareExperience = 168, ClientDisbandParty = 169, ClientOpenOwnChannel = 170, ClientInviteToOwnChannel = 171, ClientExcludeFromOwnChannel = 172, ClientCancelAttackAndFollow = 190, ClientUpdateTile = 201, ClientRefreshContainer = 202, ClientBrowseField = 203, ClientSeekInContainer = 204, ClientRequestOutfit = 210, ClientChangeOutfit = 211, ClientMount = 212, // 870 ApplyImbuemente = 213, ClearingImbuement = 214, CloseImbuingWindow = 215, ClientAddVip = 220, ClientRemoveVip = 221, ClientEditVip = 222, ClientBugReport = 230, ClientRuleViolation = 231, ClientDebugReport = 232, ClientPreyAction = 235, ClientPreyRequest = 237, ClientTransferCoins = 239, // 1080 ClientRequestQuestLog = 240, ClientRequestQuestLine = 241, ClientNewRuleViolation = 242, // 910 ClientRequestItemInfo = 243, // 910 ClientMarketLeave = 244, // 944 ClientMarketBrowse = 245, // 944 ClientMarketCreate = 246, // 944 ClientMarketCancel = 247, // 944 ClientMarketAccept = 248, // 944 ClientAnswerModalDialog = 249, // 960 ClientOpenStore = 250, // 1080 ClientRequestStoreOffers = 251, // 1080 ClientBuyStoreOffer = 252, // 1080 ClientOpenTransactionHistory = 253, // 1080 ClientRequestTransactionHistory = 254 // 1080 }; enum CreatureType { CreatureTypePlayer = 0, CreatureTypeMonster, CreatureTypeNpc, CreatureTypeSummonOwn, CreatureTypeSummonOther, CreatureTypeUnknown = 0xFF }; enum CreaturesIdRange { PlayerStartId = 0x10000000, PlayerEndId = 0x40000000, MonsterStartId = 0x40000000, MonsterEndId = 0x80000000, NpcStartId = 0x80000000, NpcEndId = 0xffffffff }; void buildMessageModesMap(int version); Otc::MessageMode translateMessageModeFromServer(uint8 mode); uint8 translateMessageModeToServer(Otc::MessageMode mode); } #endif
[ "otclient@otclient.ovh" ]
otclient@otclient.ovh
35fb863e611706929fcd4cb42d08fc0081f40149
df19b9aba991bada0fc268bdbc395a08783050e9
/src/input.cpp
df8aa7d503025fd2419be9304c6391d71a655c10
[ "BSD-3-Clause" ]
permissive
thsie004/rshell
c77eeec83221bee804ad9ede89130ceadd83f404
d652524e118eb2839f488dbc7211ef9f7276dba0
refs/heads/master
2021-01-10T02:38:21.622209
2016-03-06T23:17:34
2016-03-06T23:17:34
51,187,217
0
1
null
null
null
null
UTF-8
C++
false
false
8,552
cpp
#ifndef _INPUT_CPP_ #define _INPUT_CPP_ #include <string> #include <vector> #include <iostream> #include <cstdlib> using namespace std; /* This file includes functions and methods for obtaining user input */ //TOM: This function removes extra spaces at the head and tail of input // and also removes comments followed by #. void prepareInput(string &input) { size_t hasHash = input.find("#"); if (hasHash != string::npos) { input.erase(hasHash); } while (true) { if (input.size() == 0) { return; } if (input.at(0) == ' ') { input.erase(0,1); }else { break; } } while (true) { if (input.at(input.size() - 1) == ' ') { input.erase(input.size() - 1); }else { break; } } return; } //TOM: This function returns the initial position of the first delimiter. // If no delimiter is found, returns 99999999. int firstCut(vector<size_t> v) { unsigned int min = 99999999; for (unsigned int i = 0; i < v.size(); i++) { if ((v.at(i) >= 0) && (min > v.at(i))) min = v.at(i); } return min; } //TOM: handles getting extra input if previous line ended in a connector void getMoreInput(string &input) { string appendage; cout << "> "; getline(cin, appendage); cin.clear(); prepareInput(appendage); if (appendage.size() == 0) { getMoreInput(input); return; } input += appendage; return; } //TOM: Pushes a token back after preceding parenthesis characters // have been dealt with, then pushes following parenthesis characters. // CloseIt is the number of ')'s we need to push back at the end. // Returns -1 if there is a ')' at the front => error, and returns 0 else. // void pushWithParen(vector<string> &v, string &coin, int &parenBalance, int closeIt = 0) { prepareInput(coin); //coin not empty means there's something to push if (coin != "") { if (coin.at(0) == '(') { if (!v.empty() && v.at(v.size()-1) == ")") { parenBalance = -1; return; } v.push_back("("); parenBalance += 1; coin.erase(0, 1); //cout << "pushed ( and coin is now: " << '|' << coin << '|' << endl; pushWithParen(v, coin, parenBalance); }else if (coin.at(coin.size()-1) == ')') { parenBalance -= 1; coin.erase(coin.size()-1, 1); //cout << "pushed ) and coin is now: " << '|' << coin << '|' << endl; pushWithParen(v, coin, parenBalance, closeIt+1); }else { if (coin.find("(") != string::npos || coin.find(")") != string::npos) { parenBalance = -1; return; } v.push_back(coin); for (int i = closeIt; i > 0; i--) { v.push_back(")"); } } //coin is empty and no ')' to insert }else if (closeIt == 0) { return; //coin is empty but there is ')' to insert }else { //parenBalance is negative, so returning => error msg if (v.empty()) return; if (v.at(v.size()-1) != "(") { for (int i = closeIt; i > 0; i--) { v.push_back(")"); } }else { parenBalance = -1; return; } } } //TOM: Pass in an empty vector and get back a vector with tokens // (e.g. "ls -a" or "||" or "echo hello") in sequential order. // Note that the "exit" command is not handled here, because // handling it in the interpretation of these tokens makes // way much more sense. Inputs like &&& or ||| will make the third // character an input instead of calling it syntax error. // Inputs like &&&& and |||| or more of the same connector // characters will invoke error detection. void getInput(vector<string> &tokenz, char* user, char* host) { string input; //TOM: 0 for ';', 1 for "&&", 2 for "||" vector<size_t> spots(3); //TOM: cutPos is the first position to cut our input. unsigned int cutPos; //TOM: coin stores command substrings temporarily. string coin; //TOM: Detection of '(' adds 1 and ')' adds -1 to this variable. // If '(' and ')' are paired nicely then this value is 0. int parenBalance = 0; //cin.clear(); cout << user << '@' << host << "$ "; if (getline(cin, input)) { //does nothing if there is an input, even if it's just "\n" }else { //else a shell script is running and giving us empty inputs cout << endl; exit(0); } while (true) { prepareInput(input); if (input.size() == 0) { return; } spots.at(0) = input.find(";"); spots.at(1) = input.find("&&"); spots.at(2) = input.find("||"); cutPos = firstCut(spots); //TOM: Connector at the front, syntax must be wrong. // Note that this doesn't check for invalid characters at front. // Also error message is printed manually, as I can't come up // with an alternative method. if (cutPos == 0 && parenBalance == 0) { cout << "-rshell: syntax error with unexpected connector "; if (input.at(0) == '&') cout << "\"&&\"\n"; if (input.at(0) == ';') cout << "\";\"\n"; if (input.at(0) == '|') cout << "\"||\"\n"; tokenz.clear(); return; } if (cutPos == 99999999) { pushWithParen(tokenz, input, parenBalance); if (parenBalance < 0) { cout << "-rshell: syntax error with improper use of "; cout << "'(' or ')'" << endl; tokenz.clear(); return; }else if (parenBalance > 0) { input = ""; tokenz.push_back(";"); getMoreInput(input); }else { break; } }else { if (cutPos != 0) { coin = input.substr(0, cutPos); pushWithParen(tokenz, coin, parenBalance); } if (parenBalance < 0) { cout << "-rshell: syntax error with improper use of "; cout << "'(' or ')'" << endl; tokenz.clear(); return; } //Connector found right after '(' is an error if (!tokenz.empty()) { if (tokenz.at(tokenz.size()-1) == "(") { string x = input.substr(cutPos, cutPos+1); if (x != ";") x += input.substr(cutPos+1, cutPos+2); input = x; parenBalance = 0; continue; } } if (input.at(cutPos) == ';') { tokenz.push_back(";"); input.erase(0, cutPos + 1); if (parenBalance > 0) getMoreInput(input); }else if (input.at(cutPos) == '|'){ tokenz.push_back("||"); input.erase(0, cutPos + 2); if (input.size() == 0) getMoreInput(input); }else if (input.at(cutPos) == '&'){ tokenz.push_back("&&"); input.erase(0, cutPos + 2); if (input.size() == 0) getMoreInput(input); } //checks for double connector if (tokenz.size() < 2) continue; for (unsigned int i = 0; i < tokenz.size() - 1; i++) { if (tokenz.at(i) == "||" || tokenz.at(i) == "&&" || tokenz.at(i) == ";") { if (tokenz.at(i+1) == "||" || tokenz.at(i+1) == "&&" || tokenz.at(i+1) == ";") { parenBalance = 0; input = tokenz.at(i+1); } } } } } return; } /* int main() { vector<string> hello; char x[] = "lol"; char y[] = "what"; getInput(hello, x, y); for (int i = 0; i < hello.size();i++){ cout << hello.at(i) << endl; } return 0; } */ #endif
[ "thsie004@hammer.cs.ucr.edu" ]
thsie004@hammer.cs.ucr.edu
cfaa04e74b81ac8308b406034aa19ebf36aa2e48
cb896018371ed765cb2698a4ef28df2d1e9f1372
/ITKPlugin/OsiriXAPI.framework/Versions/A/Headers/OsiriXFixedPointVolumeRayCastMapper.h
da5a7f890eb95fe434fee6a7cfd9c0f3870b7c80
[]
no_license
pixmeo/osirixplugins
5d05672b162615bbd8ca29d6f42a189def5e597f
d06f21f99bf80c2b6b3f138aa0bd5d77ab042953
refs/heads/develop
2021-06-25T18:07:26.170622
2020-11-28T10:43:37
2020-11-28T10:43:37
8,411,919
44
57
null
2020-09-20T21:03:03
2013-02-25T15:33:52
C++
UTF-8
C++
false
false
623
h
#ifndef __OsiriXFixedPointVolumeRayCastMapper_h #define __OsiriXFixedPointVolumeRayCastMapper_h #include "vtkFixedPointVolumeRayCastMapper.h" class VTK_VOLUMERENDERING_EXPORT OsiriXFixedPointVolumeRayCastMapper : public vtkFixedPointVolumeRayCastMapper { public: static OsiriXFixedPointVolumeRayCastMapper *New(); void Render( vtkRenderer *, vtkVolume * ); protected: OsiriXFixedPointVolumeRayCastMapper(); private: OsiriXFixedPointVolumeRayCastMapper(const OsiriXFixedPointVolumeRayCastMapper&); // Not implemented. void operator=(const OsiriXFixedPointVolumeRayCastMapper&); // Not implemented. }; #endif
[ "spalte@gmail.com" ]
spalte@gmail.com
47721d28dff0f38482023053790aed7f4a926964
f66d08afc3a54a78f6fdb7c494bc2624d70c5d25
/Code/GINAC_Test/check/time_lw_C.cpp
6f6460be9a4aabe98a528c511b01387b8fa6646f
[]
no_license
NBAlexis/GiNaCToolsVC
46310ae48cff80b104cc4231de0ed509116193d9
62a25e0b201436316ddd3d853c8c5e738d66f436
refs/heads/master
2021-04-26T23:56:43.627861
2018-03-09T19:15:53
2018-03-09T19:15:53
123,883,542
1
0
null
null
null
null
UTF-8
C++
false
false
2,282
cpp
/** @file time_lw_C.cpp * * Test C from the paper "Comparison of Polynomial-Oriented CAS" by Robert H. * Lewis and Michael Wester. */ /* * GiNaC Copyright (C) 1999-2018 Johannes Gutenberg University Mainz, Germany * * 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. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "ginac_test.h" #include "timer.h" using namespace GiNaC; #include <iostream> #include <vector> using namespace std; static unsigned test() { numeric x(13*17*31); numeric y(13*19*29); for (int i=1; i<200; ++i) gcd(pow(x,300+(i%181)),pow(y,200+(i%183))); ex lastgcd = gcd(pow(x,300+(200%181)),pow(y,200+(200%183))); if (lastgcd != numeric("53174994123961114423610399251974962981084780166115806651505844915220196792416194060680805428433601792982500430324916963290494659936522782673704312949880308677990050199363768068005367578752699785180694630122629259539608472261461289805919741933")) { clog << "gcd(" << x << "^" << 300+(200%181) << "," << y << "^" << 200+(200%183) << ") erroneously returned " << lastgcd << endl; return 1; } return 0; } unsigned time_lw_C() { unsigned result = 0; unsigned count = 0; timer rolex; double time = .0; cout << "timing Lewis-Wester test C (gcd of big integers)" << flush; rolex.start(); // correct for very small times: do { result = test(); ++count; } while ((time=rolex.read())<0.1 && !result); cout << '.' << flush; cout << time/count << 's' << endl; return result; } extern void randomify_symbol_serials(); int main_time_lw_C() { randomify_symbol_serials(); cout << setprecision(2) << showpoint; return time_lw_C(); }
[ "nbalexis@gmail.com" ]
nbalexis@gmail.com
98e128250fee7c743478c9911973cdb80b48c00d
6bf1bf76ce4f689b8f307d164011ddf3ede503fd
/HuRoS/HuRoS/CODES/Arduino/KneeMotorControl/KneeMotorControl.ino
3d40ecee29a44083b996002c466c3637b8da7b10
[]
no_license
Nilendu999/Project_Codes
19e5dfb4f8ab1555ca4118e1ef5357f327390d2c
39ad90f18ecdaf465f0ffc3817514ac62be01313
refs/heads/master
2021-01-09T14:41:33.730605
2020-02-22T15:10:55
2020-02-22T15:10:55
242,340,552
0
0
null
null
null
null
UTF-8
C++
false
false
2,841
ino
/* Encoder Library - TwoKnobs Example * http://www.pjrc.com/teensy/td_libs_Encoder.html * * This example code is in the public domain. */ #include <Encoder.h> // Change these pin numbers to the pins connected to your encoder. // Best Performance: both pins have interrupt capability // Good Performance: only the first pin has interrupt capability // Low Performance: neither pin has interrupt capability Encoder motorLeft(20,21); //Encoder motorRight(7, 8); int dirPin=34, pwmPin=5; long integral=0; long eAngle=0; #define LEFT 0 #define RIGHT 1 long encoderConstant = 29520/360; //Counts per revolution for 100RPM motor // avoid using pins with LEDs attached void setup() { Serial.begin(9600); Serial.println("Encoder Test:"); pinMode(dirPin, OUTPUT); pinMode(pwmPin, OUTPUT); } long positionLeft = -999; long positionRight = -999; int posControl(long error){ long pwm=0; double kp = 0.001, ki = 0.00001; int dir; //if(abs(error)<25000){ integral = integral + error; // } //Serial.print("error:"); //Serial.print(error/encoderConstant); Serial.print(" integral:"); Serial.println(integral); if (abs(error)<2*encoderConstant){ // 2 degree error integral=0; Serial.println("REach"); } pwm = int(kp*error + ki*integral); if(pwm<0){ dir=LEFT; } else{ dir=RIGHT; } pwm=abs(pwm); if(pwm>255){ pwm=255; } /* if (abs(diff) < 40*encoderConstant && abs(diff)>0){ //Serial.println("low"); pwm=20; } else{ pwm=abs(diff)/200; } */ Serial.print("PWM:"); Serial.println(pwm); Serial.print("Dir"); Serial.println(dir); digitalWrite(dirPin, dir); analogWrite(pwmPin, pwm); //Serial.print("Dir:"); //Serial.println(dir); // Serial.println("Run"); return 0; } void loop() { long newLeft, newRight, error; long angle; String angleStr; newLeft = motorLeft.read(); //newRight = motorRight.read(); if (newLeft != positionLeft || newRight != positionRight) { //Serial.print("Left = "); //Serial.print(newLeft/encoderConstant); //Serial.print(", Right = "); //Serial.print(newRight); //Serial.print(" error:"); /*Serial.print(error); Serial.print(" integral:"); Serial.println(integral);*/ //Serial.println(); positionLeft = newLeft; //positionRight = newRight; } //Serial.flush(); // angle reading from serial monitor if (Serial.available()) { //Serial.println("Reading...."); angleStr=Serial.readStringUntil(';'); angle=angleStr.toInt(); //Serial.flush(); eAngle=angle*encoderConstant; //Serial.print("Angle:"); //Serial.println(angle); //knobLeft.write(0); //knobRight.write(0); } if(eAngle != newLeft){ error = eAngle-newLeft; //Serial.println(diff); posControl(error); } delay(10); }
[ "49873242+Nilendu999@users.noreply.github.com" ]
49873242+Nilendu999@users.noreply.github.com
05f1e8a38cc5b39c9415d9f83e19676b829bc877
409b00aec3d80c415f1add542f80cd1c35c237c7
/src/rpcdump.cpp
26b0312f1314c7289cf5f0ebeed87c1ed092c1ad
[ "MIT" ]
permissive
The-Do-It-Yourself-World/DIYTCoin-Core
fd2a53047f1450c27d952e5f4e0d11b6a1b0a47e
42c8e0f2000825a5cb0f8b66e062276acf1ba649
refs/heads/master
2020-08-23T11:00:30.362468
2019-10-21T15:48:59
2019-10-21T15:48:59
216,601,791
0
3
null
null
null
null
UTF-8
C++
false
false
19,012
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2019 The Diytube developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "init.h" #include "main.h" #include "rpcserver.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "wallet.h" #include <fstream> #include <secp256k1.h> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <openssl/aes.h> #include <openssl/sha.h> #include <univalue.h> using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string& str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string& str) { std::stringstream ret; BOOST_FOREACH(unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string& str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos + 2 < str.length()) { c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) | ((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15)); pos += 2; } ret << c; } return ret.str(); } UniValue importprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"diytubeprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nArguments:\n" "1. \"diytubeprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return NullUniValue; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return NullUniValue; } UniValue importaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importaddress \"address\" ( \"label\" rescan )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"address\" (string, required) The address\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")); CScript script; CBitcoinAddress address(params[0].get_str()); if (address.IsValid()) { script = GetScriptForDestination(address.Get()); } else if (IsHex(params[0].get_str())) { std::vector<unsigned char> data(ParseHex(params[0].get_str())); script = CScript(data.begin(), data.end()); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Diytube address or script"); } string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); { if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); // add to address book or update label if (address.IsValid()) pwalletMain->SetAddressBook(address.Get(), strLabel, "receive"); // Don't throw error in case an address is already there if (pwalletMain->HaveWatchOnly(script)) return NullUniValue; pwalletMain->MarkDirty(); if (!pwalletMain->AddWatchOnly(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } } return NullUniValue; } UniValue importwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"")); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->GetBlockTime(); bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI CBlockIndex* pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"diytubeaddress\"\n" "\nReveals the private key corresponding to 'diytubeaddress'.\n" "Then the importprivkey can be used with this output\n" "\nArguments:\n" "1. \"diytubeaddress\" (string, required) The diytube address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"")); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Diytube address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } UniValue dumpwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"")); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by Diytube %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime())); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID& keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return NullUniValue; } UniValue bip38encrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38encrypt \"diytubeaddress\"\n" "\nEncrypts a private key corresponding to 'diytubeaddress'.\n" "\nArguments:\n" "1. \"diytubeaddress\" (string, required) The diytube address for the private key (you must hold the key already)\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with - Valid special chars: !#$%&'()*+,-./:;<=>?`{|}~ \n" "\nResult:\n" "\"key\" (string) The encrypted private key\n" "\nExamples:\n"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strPassphrase = params[1].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Diytube address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); uint256 privKey = vchSecret.GetPrivKey_256(); string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey, vchSecret.IsCompressed()); UniValue result(UniValue::VOBJ); result.push_back(Pair("Addess", strAddress)); result.push_back(Pair("Encrypted Key", encryptedOut)); return result; } UniValue bip38decrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38decrypt \"diytubeaddress\"\n" "\nDecrypts and then imports password protected private key.\n" "\nArguments:\n" "1. \"encryptedkey\" (string, required) The encrypted private key\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with\n" "\nResult:\n" "\"key\" (string) The decrypted private key\n" "\nExamples:\n"); EnsureWalletIsUnlocked(); /** Collect private key and passphrase **/ string strKey = params[0].get_str(); string strPassphrase = params[1].get_str(); uint256 privKey; bool fCompressed; if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Failed To Decrypt"); UniValue result(UniValue::VOBJ); result.push_back(Pair("privatekey", HexStr(privKey))); CKey key; key.Set(privKey.begin(), privKey.end(), fCompressed); if (!key.IsValid()) throw JSONRPCError(RPC_WALLET_ERROR, "Private Key Not Valid"); CPubKey pubkey = key.GetPubKey(); pubkey.IsCompressed(); assert(key.VerifyPubKey(pubkey)); result.push_back(Pair("Address", CBitcoinAddress(pubkey.GetID()).ToString())); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, "", "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) throw JSONRPCError(RPC_WALLET_ERROR, "Key already held by wallet"); pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } return result; }
[ "troy.reid1@googlemail.com" ]
troy.reid1@googlemail.com
11daba6be36d38cb1ef0fc71be301f77cd0967ff
f0e276cd595518a98c857b3cf9a9db95bc639d70
/tar_oct_strroull.cpp
a43d8cbe35c2e159f404fa77f49134faab24b03e
[]
no_license
greshem/develop_cpp
caa6fa4f07d925ff1423cab2f29684de40748eb3
4f3d4b780eed8d7d678b975c7f098f58bb3b860e
refs/heads/master
2021-01-19T01:53:15.922285
2017-10-08T07:25:35
2017-10-08T07:25:35
45,077,580
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
645
cpp
#include <algorithm> #include <fstream> #include <iostream> #include <iostream> #include <iterator> #include <map> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> //#2010_10_08_11:24:03 add by greshem //#include <Baselib.hpp> //#include <MLmyUnit.hpp> //#include <QzjUnit.hpp> //#include <dirent.h> //2010_07_29 by qzj. using namespace std; int main(int argc, char *argv[]) { char *tmp=argv[1]; if( !tmp) { printf ("Usage: %s oct_str\n"); exit(-1); } unsigned int num= strtoll(tmp, NULL, 8); printf("%u\n", num); //Ï໥ת»»¡£ printf("o%o\n", num); return 1; }
[ "qianzhongjie@gmail.com" ]
qianzhongjie@gmail.com
63238523867cbc09da6ad4816f21196816c41c43
b766c807beb7cc2a99c346f24b41aab2bf5e0cf0
/Ass5/NhiPhan.cpp
73bb0457b860566ae6a96b8a69454b9b38378dfd
[]
no_license
php1301/ctdlgt
6c820842eab248e879e38858cba7d6e68c6d8a0f
20d20ced420930d24479714dfe557c815b4dd9fd
refs/heads/master
2021-05-19T19:34:34.157239
2020-06-26T05:58:59
2020-06-26T05:58:59
252,084,982
6
3
null
null
null
null
UTF-8
C++
false
false
1,170
cpp
#include <iostream> using namespace std; struct node { int info; node *pNext; }; struct List { node *pHead; }; void CreateList(List &l) { l.pHead = NULL; } node *CreateNode(int x); void AddHead(List &l, node *p); void enstack(List &l, int x); void destack(List &l); bool isEmpty(List l); int main() { List st; CreateList(st); long long x; cin >> x; while (x != 0) { int temp; temp = x % 2; x = (x / 2); enstack(st, temp); } node *P = st.pHead; while (P != NULL) { cout << P->info << ""; P = P->pNext; } } node* CreateNode(int x) { node* pNew = new node; pNew->info = x; pNew->pNext = NULL; return pNew; } void AddHead(List &l, node *p) { if (l.pHead == NULL) { l.pHead = p; } else { p->pNext = l.pHead; l.pHead = p; } } bool isEmpty(List s) { if (s.pHead == NULL) { return true; } return false; } void enstack(List &s, int x) { node *p = CreateNode(x); AddHead(s, p); } void destack(List &s) { node *p = s.pHead; s.pHead = s.pHead->pNext; delete p; }
[ "19520854@gm.uit.edu.vn" ]
19520854@gm.uit.edu.vn
fa54f9d094b3cd3c1a907f0167a8a4708971ebc4
7a4640a884d513dc60e66617802e95be9fe9b3f5
/Unity/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Environment63604104.h
0530a64487bbe08bebf47a19f750f645c55de079
[]
no_license
eray-z/Game-Engine-Benchmarks
40e455c9eb04463fef1c9d11fdea80ecad4a6404
2b427d02a801a2c2c4fb496601a458634e646c8d
refs/heads/master
2020-12-25T14:13:36.908703
2016-06-03T16:05:24
2016-06-03T16:05:24
60,355,376
5
0
null
null
null
null
UTF-8
C++
false
false
1,130
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.OperatingSystem struct OperatingSystem_t602923589; #include "mscorlib_System_Object837106420.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Environment struct Environment_t63604104 : public Il2CppObject { public: public: }; struct Environment_t63604104_StaticFields { public: // System.OperatingSystem System.Environment::os OperatingSystem_t602923589 * ___os_0; public: inline static int32_t get_offset_of_os_0() { return static_cast<int32_t>(offsetof(Environment_t63604104_StaticFields, ___os_0)); } inline OperatingSystem_t602923589 * get_os_0() const { return ___os_0; } inline OperatingSystem_t602923589 ** get_address_of_os_0() { return &___os_0; } inline void set_os_0(OperatingSystem_t602923589 * value) { ___os_0 = value; Il2CppCodeGenWriteBarrier(&___os_0, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "erayzesen@gmail.com" ]
erayzesen@gmail.com
9a01c1e359b5ebe70636c069f099eb8548b0c7a0
4e5e90686d8be6226321d2951f6bc5564c966ab4
/content/renderer/input/render_widget_input_handler.h
9d28142a1d0d9b3cdd22e850c69bfcec4e1f5824
[ "BSD-3-Clause" ]
permissive
0lorak0/chromium
15c53bba2f4f316159f98087c8a6703ed8313ded
71a188e053a19e3ce3528d33eef1a30166c878e4
refs/heads/master
2023-03-11T12:54:46.138686
2018-11-29T19:58:13
2018-11-29T19:58:13
159,721,234
1
0
NOASSERTION
2018-11-29T20:08:20
2018-11-29T20:08:20
null
UTF-8
C++
false
false
3,745
h
// Copyright 2015 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. #ifndef CONTENT_RENDERER_INPUT_RENDER_WIDGET_INPUT_HANDLER_H_ #define CONTENT_RENDERER_INPUT_RENDER_WIDGET_INPUT_HANDLER_H_ #include <memory> #include "base/macros.h" #include "base/time/time.h" #include "content/common/input/input_event_ack.h" #include "content/common/input/input_event_dispatch_type.h" #include "content/renderer/input/main_thread_event_queue.h" #include "third_party/blink/public/platform/web_coalesced_input_event.h" #include "ui/base/ui_base_types.h" #include "ui/events/blink/did_overscroll_params.h" namespace blink { struct WebFloatPoint; struct WebFloatSize; } // namespace blink namespace cc { struct OverscrollBehavior; } namespace ui { class LatencyInfo; } namespace viz { class FrameSinkId; } namespace content { class RenderWidget; class RenderWidgetInputHandlerDelegate; // RenderWidgetInputHandler is an IPC-agnostic input handling class. // IPC transport code should live in RenderWidget or RenderWidgetMusConnection. class CONTENT_EXPORT RenderWidgetInputHandler { public: RenderWidgetInputHandler(RenderWidgetInputHandlerDelegate* delegate, RenderWidget* widget); virtual ~RenderWidgetInputHandler(); // Hit test the given point to find out the frame underneath and // returns the FrameSinkId for that frame. |local_point| returns the point // in the coordinate space of the FrameSinkId that was hit. viz::FrameSinkId GetFrameSinkIdAtPoint(const gfx::PointF& point, gfx::PointF* local_point); // Handle input events from the input event provider. virtual void HandleInputEvent( const blink::WebCoalescedInputEvent& coalesced_event, const ui::LatencyInfo& latency_info, HandledEventCallback callback); // Handle overscroll from Blink. void DidOverscrollFromBlink(const blink::WebFloatSize& overscrollDelta, const blink::WebFloatSize& accumulatedOverscroll, const blink::WebFloatPoint& position, const blink::WebFloatSize& velocity, const cc::OverscrollBehavior& behavior); bool handling_input_event() const { return handling_input_event_; } void set_handling_input_event(bool handling_input_event) { handling_input_event_ = handling_input_event; } // Process the touch action, returning whether the action should be relayed // to the browser. bool ProcessTouchAction(cc::TouchAction touch_action); private: blink::WebInputEventResult HandleTouchEvent( const blink::WebCoalescedInputEvent& coalesced_event); RenderWidgetInputHandlerDelegate* const delegate_; RenderWidget* const widget_; // Are we currently handling an input event? bool handling_input_event_; // Used to intercept overscroll notifications while an event is being // handled. If the event causes overscroll, the overscroll metadata can be // bundled in the event ack, saving an IPC. Note that we must continue // supporting overscroll IPC notifications due to fling animation updates. std::unique_ptr<ui::DidOverscrollParams>* handling_event_overscroll_; base::Optional<cc::TouchAction> handling_touch_action_; // Type of the input event we are currently handling. blink::WebInputEvent::Type handling_event_type_; // Indicates if the next sequence of Char events should be suppressed or not. bool suppress_next_char_events_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetInputHandler); }; } // namespace content #endif // CONTENT_RENDERER_INPUT_RENDER_WIDGET_INPUT_HANDLER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
160e9a138b4edf0d79aa46725cd779a328644e69
2cd9911b83bf4a2cfe6ff8df6083f3d26af8a7ae
/Source/Router/post_subprob_compact_router.cc
a8d26dd989a69c89cb3f14daef91915cdde78fe3
[]
no_license
abhinandmenon/MFSimStaticAStar
784361b18f3dd9c245996bdd12443a6f77b5de59
775adc5c6620fb9d4dc0a3e947be236e1e4256ac
refs/heads/master
2021-01-20T08:57:26.439644
2015-01-23T23:36:22
2015-01-23T23:36:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
79,838
cc
/*------------------------------------------------------------------------------* * (c)2014, All Rights Reserved. * * ___ ___ ___ * * /__/\ / /\ / /\ * * \ \:\ / /:/ / /::\ * * \ \:\ / /:/ / /:/\:\ * * ___ \ \:\ / /:/ ___ / /:/~/:/ * * /__/\ \__\:\ /__/:/ / /\ /__/:/ /:/___ UCR DMFB Synthesis Framework * * \ \:\ / /:/ \ \:\ / /:/ \ \:\/:::::/ www.microfluidics.cs.ucr.edu * * \ \:\ /:/ \ \:\ /:/ \ \::/~~~~ * * \ \:\/:/ \ \:\/:/ \ \:\ * * \ \::/ \ \::/ \ \:\ * * \__\/ \__\/ \__\/ * *-----------------------------------------------------------------------------*/ /*---------------------------Implementation Details-----------------------------* * Source: post_subprob_compact_router.cc * * Original Code Author(s): Dan Grissom * * Original Completion/Release Date: October 7, 2012 * * * * Details: N/A * * * * Revision History: * * WHO WHEN WHAT * * --- ---- ---- * * FML MM/DD/YY One-line description * *-----------------------------------------------------------------------------*/ #include "../../Headers/Router/post_subprob_compact_router.h" /////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////// PostSubproblemCompactionRouter::PostSubproblemCompactionRouter() { cellType = NULL; thisTS = new vector<AssayNode *>(); } PostSubproblemCompactionRouter::PostSubproblemCompactionRouter(DmfbArch *dmfbArch) { cellType = NULL; arch = dmfbArch; thisTS = new vector<AssayNode *>(); } /////////////////////////////////////////////////////////////////////////////////// // Deconstructor /////////////////////////////////////////////////////////////////////////////////// PostSubproblemCompactionRouter::~PostSubproblemCompactionRouter() { /////////////////////////////////////////////////////////////////////// // More clean-up; Free the arrays being used to keep track of cell // types and blockages /////////////////////////////////////////////////////////////////////// if (cellType) { while (!cellType->empty()) { vector<ResourceType> * col = cellType->back(); cellType->pop_back(); col->clear(); delete col; } delete cellType; } if (thisTS) { thisTS->clear(); delete thisTS; } } /////////////////////////////////////////////////////////////////////// // This function performs any one-time initializations that the router // needs that are specific to a particular router. /////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::routerSpecificInits() { } /////////////////////////////////////////////////////////////////////// // Initializes the array that is used by the processing engine to // determine if a cell is equipped with a heater/detector. /////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::initCellTypeArray() { // Create a 2D-array which tells if a cell is augmented with a heater or detector cellType = new vector<vector<ResourceType> *>(); for (int x = 0; x < arch->getNumCellsX(); x++) { vector<ResourceType> *typeCol = new vector<ResourceType>(); for (int y = 0; y < arch->getNumCellsY(); y++) typeCol->push_back(BASIC_RES); cellType->push_back(typeCol); } for (unsigned i = 0; i < arch->getExternalResources()->size(); i++) { FixedModule *fm = arch->getExternalResources()->at(i); for (int x = fm->getLX(); x <= fm->getRX(); x++) { for (int y = fm->getTY(); y <= fm->getBY(); y++) { if (fm->getResourceType() == H_RES && cellType->at(x)->at(y) == D_RES) cellType->at(x)->at(y) = DH_RES; else if (fm->getResourceType() == H_RES) cellType->at(x)->at(y) = H_RES; else if (fm->getResourceType() == D_RES && cellType->at(x)->at(y) == H_RES) cellType->at(x)->at(y) = DH_RES; else if (fm->getResourceType() == D_RES) cellType->at(x)->at(y) = D_RES; else claim(false, "Unsupported cell-augmentation."); } } } } /////////////////////////////////////////////////////////////////////// // After droplets are compacted, some droplets will get to their destinations // first, at which point the router stops adding routing points. Thus, // these droplets will disappear in the output b/c they finished first. // Each droplet must be accounted for each cycle, so this function // examines the global routes and adds routing points to any droplets that // reached their destinations earlier than the latest droplet so the droplet // is accounted for each cycle. Droplets that are "caught up" or "equalized" // simply remain in their last known position. If a droplet was just // output, then we ensure here that it has been marked properly so // it will disappear from the DMFB array. /////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::equalizeGlobalRoutes(map<Droplet *, vector<RoutePoint *> *> *routes) { for (unsigned i = 0; i < thisTS->size(); i++) if (thisTS->at(i)->GetType() == OUTPUT) if (thisTS->at(i)->droplets.size() > 0) (*routes)[thisTS->at(i)->droplets.front()]->back()->dStatus = DROP_OUTPUT; map<Droplet *, vector<RoutePoint *> *>::iterator dropIt = routes->begin(); for (; dropIt != routes->end(); dropIt++) { if (!dropIt->second->empty()) { RoutePoint *lrp = dropIt->second->back(); if (!(lrp->dStatus == DROP_OUTPUT || lrp->dStatus == DROP_MERGING)) { for (unsigned c = lrp->cycle+1; c < routeCycle; c++) { RoutePoint *nrp = new RoutePoint(); nrp->cycle = c; nrp->dStatus = DROP_WAIT; nrp->x = lrp->x; nrp->y = lrp->y; (*routes)[dropIt->first]->push_back(nrp); lrp = nrp; } } } } cycle = routeCycle; } /////////////////////////////////////////////////////////////////////// // This function handles the processing of a time-step. Most routing // methods just compute droplet routes from one I/O or module to the // next; however, this is really incomplete b/c the droplet must be // accounted for and, in a sense, "routed" (or "processed") inside the // module. // // Thus, this function calls a method to process the time-step so that // we can generate a COMPLETE simulation such that the results could // be used to run an actual assay on a DMFB...ensuring that a droplet's // exact location is accounted for during each cycle. /////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::processTimeStep(map<Droplet *, vector<RoutePoint *> *> *routes) { if (processEngineType == FIXED_PE) processFixedPlaceTS(routes); else if (processEngineType == FREE_PE) processFreePlaceTS(routes); else /* Do not process - will probably result in some kind of errors */ claim(false, "No processing engine to process droplets/operations in modules during time-steps."); startingTS++; // Time-step is complete; Advance to the next time-step cycle += cyclesPerTS; // Advance cycle number by whole time-step } /////////////////////////////////////////////////////////////////////// // Divides the fluid names intelligently, maintaining the correct // composition. /////////////////////////////////////////////////////////////////////// string PostSubproblemCompactionRouter::splitFluidNames(string n1, int numSplitDrops) { map<string, float> fluids; string delimiter = "||"; string tokenDel = " parts "; size_t pos = -1; string token; string newName = n1; // Grab each fluid part while ((pos = newName.find(delimiter)) != string::npos) { token = newName.substr(0, pos); size_t pos2 = token.find(tokenDel); // Will always have float vol = (float)atof(token.substr(0, pos2).c_str()); string name = token.substr(pos2 + tokenDel.length(), token.length()-1); fluids[name] = vol / (float)numSplitDrops; newName.erase(0, pos + delimiter.length()); } // Grab last fluid part token = newName; pos = token.find(tokenDel); // Will always have float vol = (float)atof(token.substr(0, pos).c_str()); string name = token.substr(pos + tokenDel.length(), token.length()-1); fluids[name] = vol / (float)numSplitDrops; // Generate the new composition from the individual fluid parts newName = ""; map<string, float>::iterator fluidIt = fluids.begin(); for (; fluidIt != fluids.end(); fluidIt++) { if (fluidIt != fluids.begin()) newName = newName + "||"; stringstream ss; ss << fluidIt->second; newName = newName + ss.str() + " parts " + fluidIt->first; } return newName; } /////////////////////////////////////////////////////////////////////// // Combines the two fluid names intelligently, maintaining the correct // composition. /////////////////////////////////////////////////////////////////////// string PostSubproblemCompactionRouter::mergeFluidNames(string n1, string n2) { map<string, float> fluids; string delimiter = "||"; string tokenDel = " parts "; size_t pos = -1; string token; string newName = (n1 + "||" + n2); // Grab each fluid part while ((pos = newName.find(delimiter)) != string::npos) { token = newName.substr(0, pos); size_t pos2 = token.find(tokenDel); // Will always have float vol = (float)atof(token.substr(0, pos2).c_str()); string name = token.substr(pos2 + tokenDel.length(), token.length()-1); if (fluids.find(name) == fluids.end()) fluids[name] = vol; else fluids[name] = fluids[name] + vol; newName.erase(0, pos + delimiter.length()); } // Grab last fluid part token = newName; pos = token.find(tokenDel); // Will always have float vol = (float)atof(token.substr(0, pos).c_str()); string name = token.substr(pos + tokenDel.length(), token.length()-1); if (fluids.find(name) == fluids.end()) fluids[name] = vol; else fluids[name] = fluids[name] + vol; // Generate the new composition from the individual fluid parts newName = ""; map<string, float>::iterator fluidIt = fluids.begin(); for (; fluidIt != fluids.end(); fluidIt++) { if (fluidIt != fluids.begin()) newName = newName + "||"; stringstream ss; ss << fluidIt->second; newName = newName + ss.str() + " parts " + fluidIt->first; } return newName; } /////////////////////////////////////////////////////////////////////// // This function merges two droplets together. It updates the volume, // unique fluid name (composition description) and returns the droplet // with the lowest ID. // // Assumes that each fluid is formatted as: floatVolume parts fluidName // with "||" as a delimiter. // Ex: "10 parts water||3.4 parts glucose||2.1 parts coca-cola" /////////////////////////////////////////////////////////////////////// Droplet * PostSubproblemCompactionRouter::mergeDroplets(Droplet *d1, Droplet *d2) { float volume = d1->volume + d2->volume; string composition = mergeFluidNames(d1->uniqueFluidName, d2->uniqueFluidName); if (d1->id < d2->id) { d1->volume = volume; d1->uniqueFluidName = composition; return d1; } else { d2->volume = volume; d2->uniqueFluidName = composition; return d2; } } /////////////////////////////////////////////////////////////////////// // This function takes all the droplets in a node and merges them into // one droplet. Thus, before the function is called, the node should // have 2+ droplets in its droplet list; upon returning, the node will // have only one droplet (keeps the droplet with the lowest ID). // // The new droplet will have the appropriate volume and unique fluid // name (including correct breakdown of mixture composition) /////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::mergeNodeDroplets(AssayNode *n, map<Droplet *, vector<RoutePoint *> *> *routes) { // Merge the droplets into one droplet RoutePoint dest; dest.x = (*routes)[n->GetDroplets().back()]->back()->x; dest.y = (*routes)[n->GetDroplets().back()]->back()->y; // Get the minimum droplet ID and the cycle at which all droplets are merged int minDropletIdIndex = -1; vector<int> arrivalTimes; for (unsigned d = 0; d < n->GetDroplets().size(); d++) { if (minDropletIdIndex == -1 || n->GetDroplets().at(d)->id < n->GetDroplets().at(minDropletIdIndex)->id) minDropletIdIndex = d; vector<RoutePoint *> *route = (*routes)[n->GetDroplets().at(d)]; for (int r = route->size()-1; r >= 0; r--) { if (!(route->at(r)->x == dest.x && route->at(r)->y == dest.y)) { if (r+1 <= route->size()-1) arrivalTimes.push_back(route->at(r+1)->cycle); else arrivalTimes.push_back(route->at(r)->cycle); break; } } } std::sort(arrivalTimes.begin(), arrivalTimes.end()); // Sort earliest-->latest claim(arrivalTimes.size() >= 2, "Mix operation must mix at least 2 droplets."); // Delete all redundant route points for merged route droplets and mark // interfering droplets as "merging" for the interference checker for (unsigned d = 0; d < n->GetDroplets().size(); d++) { // For the droplets we're not keeping (only keep min ID when merging) if (d != minDropletIdIndex) { vector<RoutePoint *> *terminatingDropletRoute = (*routes)[n->GetDroplets().at(d)]; RoutePoint *lastRp = NULL; if (terminatingDropletRoute->size() > 0) lastRp = terminatingDropletRoute->back(); // Delete redundant route points while (lastRp && lastRp->cycle > arrivalTimes.back() && (dest.x == lastRp->x && dest.y == lastRp->y)) { RoutePoint * rpToDelete = terminatingDropletRoute->back(); terminatingDropletRoute->pop_back(); delete rpToDelete; // Get next route point if (terminatingDropletRoute->size() > 0) lastRp = terminatingDropletRoute->back(); else lastRp = NULL; } // Now, mark interfering droplet that is terminating as merging and record the merging cycles int rearIndex = 0; int begCycle = -1; int endCycle = -1; while (doesInterfere(&dest, terminatingDropletRoute->at(terminatingDropletRoute->size()-1-rearIndex))) { RoutePoint *mergingRp = terminatingDropletRoute->at(terminatingDropletRoute->size()-1-rearIndex); if (mergingRp->cycle+2 >= arrivalTimes.at(1)) { mergingRp->dStatus = DROP_MERGING; if (begCycle == -1 || mergingRp->cycle < begCycle) begCycle = mergingRp->cycle; if (endCycle == -1 || mergingRp->cycle > endCycle) endCycle = mergingRp->cycle; } else break; rearIndex++; } // Now, mark the interfering droplet that is continuing as merging during the appropriate cycles vector<RoutePoint *> *continuingDropletRoute = (*routes)[n->GetDroplets().at(minDropletIdIndex)]; for (int r = continuingDropletRoute->size()-1; r >= 0; r--) { RoutePoint *rp = continuingDropletRoute->at(r); if (rp->cycle >= begCycle && rp->cycle <= endCycle) rp->dStatus = DROP_MERGING; if (rp->cycle <= begCycle) break; } } } // Now, combine droplets and droplet properties Droplet *drop = n->GetDroplets().back(); n->droplets.pop_back(); while(!n->GetDroplets().empty()) { Droplet *d2 = n->droplets.back(); drop = mergeDroplets(drop, d2); n->droplets.pop_back(); } n->droplets.push_back(drop); } /////////////////////////////////////////////////////////////////////// // Handles the processing of droplets inside a module during a time- // step (TS). This draws droplets moving around the module during the TS. // This function is required to run an actual assay as the droplet locations // inside the module cannot be ignored in real life. // // This function assumes several things. It assumes the module is at // least 3 cells tall and 3 cells wide. // // For mixes, it essentially causes a droplet to travel around the // perimeter, clock-wise, until a few cycles before the end of the // time-step, at which point it will stop at one of the deemed exit-cells // in the top-right or bottom-right cells of the module. // // Heats/detects will travel clock-wise around the perimeter until they // find a cell equipped with a heater/detector; if one of these devices // is not on the perimeter (but rather in the center of the module), // it will not be found. A few cycles before the end of the time-step, // the droplet will move to one of the deemed exit-cells in the top-right // or bottom-right. // // Splits, will split the droplet into two and then move the two droplets // into one of the deemed exit-cells in the top- or bottom- right cells // in the module // // Storage go directly to the exit-cells in the top- or bottom- right // cells of the module. // // ONE EXCEPTION that applies to all of the descriptions above: if a // droplet's next destination is the same module location as the // current module it is in, it will not position itself in one of the // exit-cells on the right, as mentioned. INSTEAD, it will position // itself in one of the entry cells in the top- or bottom- LEFT cells // of the module. /////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::processFixedPlaceTS(map<Droplet *, vector<RoutePoint *> *> *routes) { /////////////////////////////////////////////////////////////////// // LONG version, actually moves the droplets around in the chambers. // Possibly leave disabled when doing route timings as no other works // include the processing time in route construction. /////////////////////////////////////////////////////////////////// RoutePoint *nrp = NULL; RoutePoint *lrp = NULL; for (unsigned i = 0; i < thisTS->size(); i++) { AssayNode *n = thisTS->at(i); if (!(n->GetType() == DISPENSE || n->GetType() == OUTPUT)) { unsigned long long tsCycle = cycle; bool stayingInModule = false; if (n->children.front()->reconfigMod && n->reconfigMod->getLX() == n->children.front()->reconfigMod->getLX() && n->reconfigMod->getTY() == n->children.front()->reconfigMod->getTY()) stayingInModule = true; // Here, figure out what kind of node it is and then move the droplets around as necessary if (n->GetType() == MIX) { // Merge the droplets together if (n->GetDroplets().size() >= 2) mergeNodeDroplets(n, routes); Droplet *drop = n->GetDroplets().back(); // Compute whether to leave out of top or bottom exit ReconfigModule *rm = n->GetReconfigMod(); int exitY; // Tells whether droplet is exiting from the TOP-right or BOTTOM-right AssayNode *child = n->children.front(); if (child->GetType() == OUTPUT) { if (child->GetIoPort()->getSide() == NORTH) exitY = rm->getTY(); else if (child->GetIoPort()->getSide() == SOUTH) exitY = rm->getBY(); else { if (child->GetIoPort()->getPosXY() <= rm->getTY()+1) exitY = rm->getTY(); else exitY = rm->getBY(); } } else { ReconfigModule *nRm = n->children.front()->GetReconfigMod(); // Next module if (nRm->getTY() < rm->getTY()) exitY = rm->getTY(); else exitY = rm->getBY(); } lrp = (*routes)[drop]->back(); // Last route point while (tsCycle < cycle + cyclesPerTS) { ReconfigModule *rm = n->GetReconfigMod(); nrp = new RoutePoint(); // This route point nrp->dStatus = DROP_PROCESSING; int numCellsInCirc = rm->getNumCellsInCirc(); if (stayingInModule && (lrp->x == rm->getLX() && lrp->y == rm->getBY()) && (tsCycle + numCellsInCirc > cycle + cyclesPerTS) && startingTS+1 == n->endTimeStep ) { // Cannot make another full rotation before TS is done so just stay here in BL and take position for next TS nrp->x = lrp->x; nrp->y = lrp->y; } else if (!stayingInModule && (lrp->x == rm->getRX() && lrp->y == exitY) && (tsCycle + numCellsInCirc > cycle + cyclesPerTS) && startingTS+1 == n->endTimeStep ) { // Cannot make another full rotation before TS is done so just stay here in TR and take position to leave module nrp->x = lrp->x; nrp->y = lrp->y; } else { // ***This won't work on linear arrays if (lrp->x == rm->getLX()) // If in left column { if (lrp->y > rm->getTY()) // Go north if not at north border { nrp->x = lrp->x; nrp->y = lrp->y-1; } else // Else turn toward east { nrp->x = lrp->x+1; nrp->y = lrp->y; } } else if (lrp->y == rm->getTY()) // If in top row { if (lrp->x < rm->getRX()) // Go east if not at east border { nrp->x = lrp->x+1; nrp->y = lrp->y; } else // Else turn toward south { nrp->x = lrp->x; nrp->y = lrp->y+1; } } else if (lrp->x == rm->getRX()) // If in right column { if (lrp->y < rm->getBY()) // Go south if not at south border { nrp->x = lrp->x; nrp->y = lrp->y+1; } else // Else turn toward west { nrp->x = lrp->x-1; nrp->y = lrp->y; } } else if (lrp->y == rm->getBY()) // If in bottom row { if (lrp->x > rm->getLX()) // Go west if not at left border { nrp->x = lrp->x-1; nrp->y = lrp->y; } else // Else toward north { nrp->x = lrp->x; nrp->y = lrp->y-1; } } else claim(false, "Unhandled processing decision for router."); } nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } else if (n->GetType() == DILUTE) { // Merge the droplets together if (n->GetDroplets().size() >= 2) mergeNodeDroplets(n, routes); Droplet *drop = n->GetDroplets().back(); ReconfigModule *rm = n->GetReconfigMod(); int modHeight = abs(rm->getBY() - rm->getTY() + 1); lrp = (*routes)[drop]->back(); // Last route point // Process droplet for duration of time-step while (tsCycle < cycle + cyclesPerTS) { ReconfigModule *rm = n->GetReconfigMod(); nrp = new RoutePoint(); // This route point nrp->dStatus = DROP_PROCESSING; int numCellsInCirc = rm->getNumCellsInCirc(); if ((lrp->x == rm->getRX() && lrp->y == rm->getBY()) && (tsCycle + numCellsInCirc + (modHeight-1) > cycle + cyclesPerTS) && startingTS+1 == n->endTimeStep ) { // Cannot make another full rotation before TS is done so just stay here in BR and take position to leave module // Split droplets if still only 1 droplet if (n->GetDroplets().size() <= 1) { Droplet *splitDrop1 = n->GetDroplets().back(); Droplet *splitDrop2 = new Droplet(); splitDrop1->uniqueFluidName = splitDrop2->uniqueFluidName = splitFluidNames(splitDrop1->uniqueFluidName, n->GetChildren().size()); splitDrop1->volume = splitDrop2->volume = splitDrop1->volume / n->GetChildren().size(); (*routes)[splitDrop2] = new vector<RoutePoint *>(); n->addDroplet(splitDrop2); lrp = (*routes)[splitDrop1]->back(); for (int yPos = lrp->y-1; yPos >= n->reconfigMod->getTY(); yPos--) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle; (*routes)[splitDrop1]->push_back(nrp); nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = yPos; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle++; (*routes)[splitDrop2]->push_back(nrp); } } else // Droplets have been split; hold in place { unsigned long long splitCycle; for (unsigned di = 0; di < n->droplets.size(); di++) { Droplet *drop = n->droplets.at(di); lrp = (*routes)[drop]->back(); splitCycle = tsCycle; while (splitCycle < cycle + cyclesPerTS) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_PROCESSING; nrp->cycle = splitCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } tsCycle = splitCycle; } } else { // ***This won't work on linear arrays if (lrp->x == rm->getLX()) // If in left column { if (lrp->y > rm->getTY()) // Go north if not at north border { nrp->x = lrp->x; nrp->y = lrp->y-1; } else // Else turn toward east { nrp->x = lrp->x+1; nrp->y = lrp->y; } } else if (lrp->y == rm->getTY()) // If in top row { if (lrp->x < rm->getRX()) // Go east if not at east border { nrp->x = lrp->x+1; nrp->y = lrp->y; } else // Else turn toward south { nrp->x = lrp->x; nrp->y = lrp->y+1; } } else if (lrp->x == rm->getRX()) // If in right column { if (lrp->y < rm->getBY()) // Go south if not at south border { nrp->x = lrp->x; nrp->y = lrp->y+1; } else // Else turn toward west { nrp->x = lrp->x-1; nrp->y = lrp->y; } } else if (lrp->y == rm->getBY()) // If in bottom row { if (lrp->x > rm->getLX()) // Go west if not at left border { nrp->x = lrp->x-1; nrp->y = lrp->y; } else // Else toward north { nrp->x = lrp->x; nrp->y = lrp->y-1; } } else claim(false, "Unhandled processing decision for router."); nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } } else if (n->GetType() == HEAT || n->GetType() == DETECT) { Droplet *drop = n->GetDroplets().back(); lrp = (*routes)[drop]->back(); // Last route point ResourceType rt; if (n->GetType() == HEAT) rt = H_RES; else rt = D_RES; while (tsCycle < cycle + cyclesPerTS) { // Compute whether to leave out of top or bottom exit ReconfigModule *rm = n->GetReconfigMod(); int exitY; // Tells whether droplet is exiting from the TOP-right or BOTTOM-right AssayNode *child = n->children.front(); if (child->GetType() == OUTPUT) { if (child->GetIoPort()->getSide() == NORTH) exitY = rm->getTY(); else if (child->GetIoPort()->getSide() == SOUTH) exitY = rm->getBY(); else { if (child->GetIoPort()->getPosXY() <= rm->getTY()+1) exitY = rm->getTY(); else exitY = rm->getBY(); } } else { ReconfigModule *nRm = n->children.front()->GetReconfigMod(); // Next module if (nRm->getTY() < rm->getTY()) exitY = rm->getTY(); else exitY = rm->getBY(); } nrp = new RoutePoint(); // This route point nrp->dStatus = DROP_PROCESSING; int numCellsInCirc = rm->getNumCellsInCirc(); if (((cellType->at(lrp->x)->at(lrp->y) == rt || cellType->at(lrp->x)->at(lrp->y) == DH_RES) && (startingTS+1 != n->endTimeStep || (startingTS+1 == n->endTimeStep && (tsCycle + numCellsInCirc < cycle + cyclesPerTS)))) || (stayingInModule && (lrp->x == rm->getLX() && lrp->y == rm->getBY()) && (tsCycle + numCellsInCirc > cycle + cyclesPerTS) && startingTS+1 == n->endTimeStep) || (!stayingInModule && (lrp->x == rm->getRX() && lrp->y == exitY) && (tsCycle + numCellsInCirc > cycle + cyclesPerTS) && startingTS+1 == n->endTimeStep) ) { // Cannot make another full rotation before TS is done so just stay here nrp->x = lrp->x; nrp->y = lrp->y; } else { // ***This won't work on linear arrays if (lrp->x == rm->getLX()) // If in left column { if (lrp->y > rm->getTY()) // Go north if not at north border { nrp->x = lrp->x; nrp->y = lrp->y-1; } else // Else turn toward east { nrp->x = lrp->x+1; nrp->y = lrp->y; } } else if (lrp->y == rm->getTY()) // If in top row { if (lrp->x < rm->getRX()) // Go east if not at east border { nrp->x = lrp->x+1; nrp->y = lrp->y; } else // Else turn toward south { nrp->x = lrp->x; nrp->y = lrp->y+1; } } else if (lrp->x == rm->getRX()) // If in right column { if (lrp->y < rm->getBY()) // Go south if not at south border { nrp->x = lrp->x; nrp->y = lrp->y+1; } else // Else turn toward west { nrp->x = lrp->x-1; nrp->y = lrp->y; } } else if (lrp->y == rm->getBY()) // If in bottom row { if (lrp->x > rm->getLX()) // Go west if not at left border { nrp->x = lrp->x-1; nrp->y = lrp->y; } else // Else toward north { nrp->x = lrp->x; nrp->y = lrp->y-1; } } else claim(false, "Unhandled processing decision for router."); } nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } else if (n->GetType() == STORAGE) { // If we are breaking the 2 droplet rule, we cannot move to exit cell b/c there might already be a droplet there bool dropsMustRemainStatic = false; if (n->GetReconfigMod()->getNumDrops() > 2) dropsMustRemainStatic = true; Droplet *drop = n->GetDroplets().back(); lrp = (*routes)[drop]->back(); // Last route point while (tsCycle < cycle + cyclesPerTS) { nrp = new RoutePoint(); // next route point nrp->cycle = tsCycle++; nrp->dStatus = DROP_PROCESSING; // If leaving module after TS, move to right and store, else keep on left if (!stayingInModule && lrp->x != n->reconfigMod->getRX() && !dropsMustRemainStatic) { nrp->x = lrp->x+1; nrp->y = lrp->y; } else if (stayingInModule && n->children.front()->type != STORAGE && lrp->y != n->reconfigMod->getBY() && tsCycle > cycle+2 && !dropsMustRemainStatic) { nrp->x = lrp->x; nrp->y = lrp->y+1; } else { nrp->x = lrp->x; nrp->y = lrp->y; } (*routes)[drop]->push_back(nrp); lrp = nrp; } } else if (n->GetType() == SPLIT) { // Only split at beginning of TS if (n->startTimeStep == startingTS) { Droplet *drop = n->GetDroplets().back(); Droplet *drop2 = new Droplet(); drop->uniqueFluidName = drop2->uniqueFluidName = splitFluidNames(drop->uniqueFluidName, n->GetChildren().size()); drop->volume = drop2->volume = drop->volume / n->GetChildren().size(); (*routes)[drop2] = new vector<RoutePoint *>(); n->addDroplet(drop2); lrp = (*routes)[drop]->back(); for (int yPos = lrp->y-1; yPos >= n->reconfigMod->getTY(); yPos--) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle; (*routes)[drop]->push_back(nrp); nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = yPos; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle++; (*routes)[drop2]->push_back(nrp); } } unsigned long long splitCycle; for (unsigned d = 0; d < n->droplets.size(); d++) { Droplet *drop = n->droplets.at(d); lrp = (*routes)[drop]->back(); splitCycle = tsCycle; while (splitCycle < cycle + cyclesPerTS) { // Move to right if (lrp->x != n->reconfigMod->getRX()) { nrp = new RoutePoint(); // next route point nrp->cycle = splitCycle++; nrp->dStatus = DROP_PROCESSING; nrp->x = lrp->x+1; nrp->y = lrp->y; (*routes)[drop]->push_back(nrp); lrp = nrp; } else { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_PROCESSING; nrp->cycle = splitCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } } tsCycle = splitCycle; } else claim(false, "Unsupported opearation encountered while routing."); } } } /////////////////////////////////////////////////////////////////////// // Handles the processing of droplets inside a module during a time- // step (TS). This is the long version, which draws droplets moving // around the module during the TS. A full processing (as opposed to // a quick processing) is required to run an actual assay as the droplet // locations inside the module cannot be ignored in real life. // // This function is meant to be used for free placements and can handle // modules of different sizes and shapes, assuming they are some sort // of rectangle // // For mixes (2 by X) mixers, it causes a droplet to travel around the // perimeter, clock-wise, until the time-step is complete. For (3+ by X) // mixers, performs a zig-zag until the end of the time-step. For // (1 by X) mixers (linear mixers), traverses the module back and forth. // // Heats/detects will zig-zag through their module until they find a cell // equipped with a heater/detector; heat/detect modules with a single cell // will just remain there. // // Splits assume at least a (3 by 1) array and will split the droplet // into two and leave the droplets there until the end of the time-step. // // Storage will assume it is given a (1 by 1) module (single-cell module) // and remain in its location until the end of the time-step. /////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::processFreePlaceTS(map<Droplet *, vector<RoutePoint *> *> *routes) { RoutePoint *nrp = NULL; RoutePoint *lrp = NULL; for (unsigned i = 0; i < thisTS->size(); i++) { AssayNode *n = thisTS->at(i); if (!(n->GetType() == DISPENSE || n->GetType() == OUTPUT)) { unsigned long long tsCycle = cycle; // Here, figure out what kind of node it is and then move the droplets around as necessary if (n->GetType() == MIX) { // Merge the droplets together if (n->GetDroplets().size() >= 2) mergeNodeDroplets(n, routes); Droplet *drop = n->GetDroplets().back(); // Create route point for each cycle of the time-step lrp = (*routes)[drop]->back(); // Last route point bool travelingRight = true; bool travelingDown = true; while (tsCycle < cycle + cyclesPerTS) { ReconfigModule *rm = n->GetReconfigMod(); int modWidth = rm->getRX() - rm->getLX() + 1; int modHeight = rm->getBY() - rm->getTY() + 1; // If module has exactly 1 cell in any dimension (linear array), travel back and forth if (modWidth == 1 || modHeight == 1) { // Horizontal linear array nrp = advanceDropInLinMod(lrp, rm, &travelingRight, &travelingDown); nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } else if (modWidth == 2 || modHeight == 2) { // Module has exactly 2 cells in any dimension, travel circumference nrp = advanceDropIn2ByMod(lrp, rm); nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } else { // Module has >2 cells in all dimensions, do zig-zag nrp = advanceDropIn3By3PlusMod(lrp, rm, &travelingRight, &travelingDown); nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } } else if (n->GetType() == DILUTE) { // Merge the droplets together if (n->GetDroplets().size() >= 2) mergeNodeDroplets(n, routes); Droplet *drop = n->GetDroplets().back(); // Create route point for each cycle of the time-step lrp = (*routes)[drop]->back(); // Last route point bool travelingRight = true; bool travelingDown = true; while (tsCycle < cycle + cyclesPerTS) { ReconfigModule *rm = n->GetReconfigMod(); int modWidth = rm->getRX() - rm->getLX() + 1; int modHeight = rm->getBY() - rm->getTY() + 1; if ( ( ((lrp->x == rm->getLX() || lrp->x == rm->getRX()) && (tsCycle + modWidth + 2 /*(split cycles)*/ > cycle + cyclesPerTS)) || ((lrp->y == rm->getTY() || lrp->y == rm->getBY()) && (tsCycle + modHeight + 2 /*(split cycles)*/ > cycle + cyclesPerTS)) ) && startingTS+1 == n->endTimeStep && n->GetDroplets().size() <= 1 ) { // Split the droplet Droplet *splitDrop1 = n->GetDroplets().back(); Droplet *splitDrop2 = new Droplet(); splitDrop1->uniqueFluidName = splitDrop2->uniqueFluidName = splitFluidNames(splitDrop1->uniqueFluidName, n->GetChildren().size()); splitDrop1->volume = splitDrop2->volume = drop->volume / n->GetChildren().size(); (*routes)[splitDrop2] = new vector<RoutePoint *>(); n->addDroplet(splitDrop2); lrp = (*routes)[splitDrop1]->back(); // Proceess split part of dilution for (int yPos = 1; yPos <= 2; yPos++) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle; (*routes)[splitDrop1]->push_back(nrp); nrp = new RoutePoint(); // Compute split direction depending on current location in module if (lrp->x == rm->getLX() && modWidth >= 3) // Split to right { nrp->x = lrp->x + yPos; nrp->y = lrp->y; } else if (lrp->x == rm->getRX() && modWidth >= 3) // Split to left { nrp->x = lrp->x - yPos; nrp->y = lrp->y; } else if (lrp->y == rm->getBY() && modHeight >= 3) // Split upward { nrp->x = lrp->x; nrp->y = lrp->y - yPos; } else if (lrp->y == rm->getTY() && modHeight >= 3) // Split downward { nrp->x = lrp->x; nrp->y = lrp->y + yPos; } nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle++; (*routes)[splitDrop2]->push_back(nrp); } } else if (n->GetDroplets().size() > 1) // Droplets have been split; hold in place { unsigned long long splitCycle; for (unsigned di = 0; di < n->droplets.size(); di++) { Droplet *drop = n->droplets.at(di); lrp = (*routes)[drop]->back(); splitCycle = tsCycle; while (splitCycle < cycle + cyclesPerTS) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_PROCESSING; nrp->cycle = splitCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } tsCycle = splitCycle; } else { // If module has exactly 1 cell in any dimension (linear array), travel back and forth if (modWidth == 1 || modHeight == 1) { // Horizontal linear array nrp = advanceDropInLinMod(lrp, rm, &travelingRight, &travelingDown); nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } else if (modWidth == 2 || modHeight == 2) { // Module has exactly 2 cells in any dimension, travel circumference nrp = advanceDropIn2ByMod(lrp, rm); nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } else { // Module has >2 cells in all dimensions, do zig-zag nrp = advanceDropIn3By3PlusMod(lrp, rm, &travelingRight, &travelingDown); nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } } } else if (n->GetType() == HEAT || n->GetType() == DETECT) { Droplet *drop = n->GetDroplets().back(); lrp = (*routes)[drop]->back(); // Last route point ResourceType rt; if (n->GetType() == HEAT) rt = H_RES; else rt = D_RES; bool travelingRight = true; bool travelingDown = true; while (tsCycle < cycle + cyclesPerTS) { // Compute whether to leave out of top or bottom exit ReconfigModule *rm = n->GetReconfigMod(); //int numCellsInCirc = rm->getNumCellsInCirc(); // If have found an appropriate resource, just stay here if ( cellType->at(lrp->x)->at(lrp->y) == rt || cellType->at(lrp->x)->at(lrp->y) == DH_RES ) { nrp = new RoutePoint(); nrp->dStatus = DROP_PROCESSING; nrp->x = lrp->x; nrp->y = lrp->y; } else // Still trying to find the external resource { int modWidth = rm->getRX() - rm->getLX() + 1; int modHeight = rm->getBY() - rm->getTY() + 1; // If module has exactly 1 cell in any dimension (linear array), travel back and forth if (modWidth == 1 || modHeight == 1) nrp = advanceDropInLinMod(lrp, rm, &travelingRight, &travelingDown); else if (modWidth == 2 || modHeight == 2) // If module has exactly 2 cells in any dimension, travel circumference nrp = advanceDropIn2ByMod(lrp, rm); else // If module has >2 cells in all dimensions, do zig-zag nrp = advanceDropIn3By3PlusMod(lrp, rm, &travelingRight, &travelingDown); } nrp->cycle = tsCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } else if (n->GetType() == STORAGE) { Droplet *drop = n->GetDroplets().back(); lrp = (*routes)[drop]->back(); // Last route point while (tsCycle < cycle + cyclesPerTS) { nrp = new RoutePoint(); // next route point nrp->cycle = tsCycle++; nrp->dStatus = DROP_PROCESSING; nrp->x = lrp->x; nrp->y = lrp->y; (*routes)[drop]->push_back(nrp); lrp = nrp; } } else if (n->GetType() == SPLIT) { // Only split at beginning of TS if (n->startTimeStep == startingTS) { Droplet *drop = n->GetDroplets().back(); lrp = (*routes)[drop]->back(); // Last route point ReconfigModule *rm = n->GetReconfigMod(); int modWidth = rm->getRX() - rm->getLX() + 1; int modHeight = rm->getBY() - rm->getTY() + 1; claim(modWidth >= 3 || modHeight >= 3, "Module to perform split operatoin must be at least 3 cells in one dimension."); // If modWidth is at least 3, position at left-most side... if (modWidth >= 3) { while (lrp->x > rm->getLX()) { nrp = new RoutePoint(); // next route point nrp->cycle = tsCycle++; nrp->dStatus = DROP_PROCESSING; nrp->x = lrp->x-1; nrp->y = lrp->y; (*routes)[drop]->push_back(nrp); lrp = nrp; } } else // If modHeight is at least 3, position at bottom-most side... { while (lrp->y < rm->getBY()) { nrp = new RoutePoint(); // next route point nrp->cycle = tsCycle++; nrp->dStatus = DROP_PROCESSING; nrp->x = lrp->x; nrp->y = lrp->y+1; (*routes)[drop]->push_back(nrp); lrp = nrp; } } // Then do split Droplet *drop2 = new Droplet(); drop->uniqueFluidName = drop2->uniqueFluidName = splitFluidNames(drop->uniqueFluidName, n->GetChildren().size()); drop->volume = drop2->volume = drop->volume / n->GetChildren().size(); (*routes)[drop2] = new vector<RoutePoint *>(); n->addDroplet(drop2); // If modWidth is at least 3, split to right if (modWidth >= 3) { for (int xPos = lrp->x+1; xPos <= n->reconfigMod->getRX(); xPos++) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle; (*routes)[drop]->push_back(nrp); nrp = new RoutePoint(); nrp->x = xPos; nrp->y = lrp->y; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle++; (*routes)[drop2]->push_back(nrp); } } else // If modHeight is at least 3, split upward { for (int yPos = lrp->y-1; yPos >= n->reconfigMod->getTY(); yPos--) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle; (*routes)[drop]->push_back(nrp); nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = yPos; nrp->dStatus = DROP_SPLITTING; nrp->cycle = tsCycle++; (*routes)[drop2]->push_back(nrp); } } } // Now allow droplets to wait where they are until time-step is complete unsigned long long splitCycle; for (unsigned d = 0; d < n->droplets.size(); d++) { Droplet *drop = n->droplets.at(d); lrp = (*routes)[drop]->back(); splitCycle = tsCycle; while (splitCycle < cycle + cyclesPerTS) { nrp = new RoutePoint(); nrp->x = lrp->x; nrp->y = lrp->y; nrp->dStatus = DROP_PROCESSING; nrp->cycle = splitCycle++; (*routes)[drop]->push_back(nrp); lrp = nrp; } } tsCycle = splitCycle; } else claim(false, "Unsupported opearation encountered while routing."); } } } /////////////////////////////////////////////////////////////////////////////////// // Advances droplet one cell in a linear array for droplet processing. Droplet // oscillates back and forth. /////////////////////////////////////////////////////////////////////////////////// RoutePoint * PostSubproblemCompactionRouter::advanceDropInLinMod(RoutePoint *lrp, ReconfigModule *rm, bool *travelingRight, bool *travelingDown) { int modWidth = rm->getRX() - rm->getLX() + 1; RoutePoint *nrp = new RoutePoint(); // Horizontal linear array if (modWidth == 1) { // Go down and then up if (*travelingDown) { if (lrp->y == rm->getBY()) { nrp->y = lrp->y-1; *travelingDown = false; } else nrp->y = lrp->y+1; nrp->x = lrp->x; } else { if (lrp->y == rm->getTY()) { nrp->y = lrp->y+1; *travelingDown = true; } else nrp->y = lrp->y-1; nrp->x = lrp->x; } } else // Vertical linear array { // Go right and then left if (*travelingRight) { if (lrp->x == rm->getRX()) { nrp->x = lrp->x-1; *travelingRight = false; } else nrp->x = lrp->x+1; nrp->y = lrp->y; } else { if (lrp->x == rm->getLX()) { nrp->x = lrp->x+1; *travelingRight = true; } else nrp->x = lrp->x-1; nrp->y = lrp->y; } } nrp->dStatus = DROP_PROCESSING; return nrp; } /////////////////////////////////////////////////////////////////////////////////// // Advances droplet one cell in a module with at least one dimension of exactly // two cells. Droplet travels around array in clockwise manner. /////////////////////////////////////////////////////////////////////////////////// RoutePoint * PostSubproblemCompactionRouter::advanceDropIn2ByMod(RoutePoint *lrp, ReconfigModule *rm) { RoutePoint *nrp = new RoutePoint(); if (lrp->x == rm->getLX()) // If in left column { if (lrp->y > rm->getTY()) // Go north if not at north border { nrp->x = lrp->x; nrp->y = lrp->y-1; } else // Else turn toward east { nrp->x = lrp->x+1; nrp->y = lrp->y; } } else if (lrp->y == rm->getTY()) // If in top row { if (lrp->x < rm->getRX()) // Go east if not at east border { nrp->x = lrp->x+1; nrp->y = lrp->y; } else // Else turn toward south { nrp->x = lrp->x; nrp->y = lrp->y+1; } } else if (lrp->x == rm->getRX()) // If in right column { if (lrp->y < rm->getBY()) // Go south if not at south border { nrp->x = lrp->x; nrp->y = lrp->y+1; } else // Else turn toward west { nrp->x = lrp->x-1; nrp->y = lrp->y; } } else if (lrp->y == rm->getBY()) // If in bottom row { if (lrp->x > rm->getLX()) // Go west if not at left border { nrp->x = lrp->x-1; nrp->y = lrp->y; } else // Else toward north { nrp->x = lrp->x; nrp->y = lrp->y-1; } } nrp->dStatus = DROP_PROCESSING; return nrp; } /////////////////////////////////////////////////////////////////////////////////// // Advances droplet one cell in a module in which both dimensions are at least // 3 cells. Droplet travels around module in zig-zag pattern. /////////////////////////////////////////////////////////////////////////////////// RoutePoint * PostSubproblemCompactionRouter::advanceDropIn3By3PlusMod(RoutePoint *lrp, ReconfigModule *rm, bool *travelingRight, bool *travelingDown) { RoutePoint *nrp = new RoutePoint(); if ((lrp->x == rm->getRX() && *travelingRight) || (lrp->x == rm->getLX() && !(*travelingRight))) { // Just hit left/right side, go up or down and then switch left/right direction if (*travelingDown && lrp->y == rm->getBY()) { // Hit bottom side, reverse to up *travelingDown = !(*travelingDown); nrp->y = lrp->y-1; } else if (*travelingDown) { nrp->y = lrp->y+1; } else if (!(*travelingDown) && lrp->y == rm->getTY()) { *travelingDown = !(*travelingDown); nrp->y = lrp->y+1; } else if (!(*travelingDown)) nrp->y = lrp->y-1; nrp->x = lrp->x; *travelingRight = !(*travelingRight); } else if (*travelingRight) { nrp->x = lrp->x+1; nrp->y = lrp->y; } else { nrp->x = lrp->x-1; nrp->y = lrp->y; } nrp->dStatus = DROP_PROCESSING; return nrp; } /////////////////////////////////////////////////////////////////////////////////// // After the individual routes have been computed and then compacted, this function // takes the results of the sub-problem from subRoutes and adds them back to the // global routes for the entire assay. /////////////////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::addSubProbToGlobalRoutes(vector<Droplet *> *subDrops, vector<vector<RoutePoint *> *> *subRoutes, map<Droplet *, vector<RoutePoint *> *> *routes) { routeCycle = cycle; while (!subDrops->empty()) { Droplet *d = subDrops->back(); subDrops->pop_back(); vector<RoutePoint *> *sr = subRoutes->back(); subRoutes->pop_back(); int delay = 0; while (!sr->empty()) { RoutePoint *rp = sr->front(); sr->erase(sr->begin()); if (rp == NULL) { delay++; if (!(*routes)[d]->empty()) { RoutePoint *lrp = (*routes)[d]->back(); RoutePoint *nrp = new RoutePoint(); nrp->cycle = lrp->cycle+1; nrp->dStatus = DROP_WAIT; nrp->x = lrp->x; nrp->y = lrp->y; (*routes)[d]->push_back(nrp); } } else { rp->cycle += delay; (*routes)[d]->push_back(rp); } } if ((*routes)[d]->back()->cycle >= routeCycle) routeCycle = (*routes)[d]->back()->cycle+1; delete sr; } } /////////////////////////////////////////////////////////////////////////////////// // Problems can arise later on in the compactor when individual routes are compacted // together. The main problem arises when one droplet's source is in the IR of // another droplet's target. Thus, the order in which droplets are compacted // matters and can possibly solve this problem. However, in the case of a dependency // cycle, at least one droplet will need to be moved out of the way. This function // takes a more aggressive and less computationaly complex approach by removing // all droplet-route dependencies. If a source is in the IR of another droplet's // target, the droplet with the conflicting source is simply moved out of the way // before we compute the individual routes in computeIndivSupProbRoutes() so that // it has a new source. This function simply tries to move the droplet x=5 cells // in each cardinal direction until it finds a clear path/destination for the // conflicting source droplet; if it cannot find a clear path/dest, it reports a // failure. // // WARNING: This solution is not guaranteed in that it is possible that there may // not be a free block of cells in the immediate vicinity. However, if we keep // distance between modules, it should almost always work. Even without space // between modules, it should usually work given the module placement isn't // extremely compact. /////////////////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::eliminateSubRouteDependencies(map<Droplet *, vector<RoutePoint *> *> *routes) { // Get the nodes that need to be routed and sort vector<AssayNode *> routableThisTS; for (unsigned i = 0; i < thisTS->size(); i++) if (thisTS->at(i)->GetType() != DISPENSE && thisTS->at(i)->GetStartTS() == startingTS) routableThisTS.push_back(thisTS->at(i)); // Gather the source and destination cells of each routable droplet this TS // For now, assume a non-io source is at the location of its last route point; non-io destination is bottom-left map<Droplet *, RoutePoint *> *sourceCells = new map<Droplet *, RoutePoint *>(); map<Droplet *, RoutePoint *> *targetCells = new map<Droplet *, RoutePoint *>(); vector<Droplet *> *routingThisTS = new vector<Droplet *>(); for (unsigned i = 0; i < routableThisTS.size(); i++) { AssayNode *n = routableThisTS.at(i); for (unsigned p = 0; p < n->GetParents().size(); p++) { routeCycle = cycle;// DTG added to compact AssayNode *par = n->GetParents().at(p); Droplet *pd = par->GetDroplets().back(); // If more than one parent droplet...remove...but then add to beginning so // can examine each split drop w/o actually removing and keeping routing order intact. if (par->droplets.size() > 1) { par->droplets.pop_back(); par->droplets.insert(par->droplets.begin(), pd); } if (n->GetReconfigMod()) n->GetReconfigMod()->incNumDrops(); // MUST clear this before leaving function b/c computeIndivSubRoutes() counts on it being untouched // First get sources RoutePoint *s = new RoutePoint(); if (par->GetType() == DISPENSE) { if (par->GetIoPort()->getSide() == NORTH) { s->x = par->GetIoPort()->getPosXY(); s->y = 0; } else if (par->GetIoPort()->getSide() == SOUTH) { s->x = par->GetIoPort()->getPosXY(); s->y = arch->getNumCellsY()-1; } else if (par->GetIoPort()->getSide() == EAST) { s->x = arch->getNumCellsX()-1; s->y = par->GetIoPort()->getPosXY(); } else if (par->GetIoPort()->getSide() == WEST) { s->x = 0; s->y = par->GetIoPort()->getPosXY(); } } else { s->x = (*routes)[pd]->back()->x; s->y = (*routes)[pd]->back()->y; // last route point } sourceCells->insert(pair<Droplet *, RoutePoint *>(pd, s)); // Now get targets RoutePoint *t = new RoutePoint(); if (n->GetType() == OUTPUT) { if (n->GetIoPort()->getSide() == NORTH) { t->x = n->GetIoPort()->getPosXY(); t->y = 0; } else if (n->GetIoPort()->getSide() == SOUTH) { t->x = n->GetIoPort()->getPosXY(); t->y = arch->getNumCellsY()-1; } else if (n->GetIoPort()->getSide() == EAST) { t->x = arch->getNumCellsX()-1; t->y = n->GetIoPort()->getPosXY(); } else if (n->GetIoPort()->getSide() == WEST) { t->x = 0; t->y = n->GetIoPort()->getPosXY(); } } else // DTG, this will need to be adjusted for storage etc., when/if more than one destination in a module { // Original two lines - 6/13/2013 - DTG //t->x = n->GetReconfigMod()->getLX(); //t->y = n->GetReconfigMod()->getBY(); if (n->GetType() == STORAGE && n->GetReconfigMod()->getNumDrops() == 2) { // Top-Left if second Storage drop t->x = n->GetReconfigMod()->getLX(); t->y = n->GetReconfigMod()->getTY(); } else if (n->GetType() == STORAGE && n->GetReconfigMod()->getNumDrops() == 3) { // Bottom-right if third Storage drop t->x = n->GetReconfigMod()->getRX(); t->y = n->GetReconfigMod()->getBY(); } else if (n->GetType() == STORAGE && n->GetReconfigMod()->getNumDrops() == 4) { // Top-right if fourth Storage drop t->x = n->GetReconfigMod()->getRX(); t->y = n->GetReconfigMod()->getTY(); } else if (n->GetType() == STORAGE && n->GetReconfigMod()->getNumDrops() > 4) claim(false, "Router is not currently designed to handle more than 4 storage droplets per module. Please reduce the number of storage drops per module or update the Roy Router source code."); else { // Bottom-Left, else t->x = n->GetReconfigMod()->getLX(); t->y = n->GetReconfigMod()->getBY(); } } targetCells->insert(pair<Droplet *, RoutePoint *>(pd, t)); // Debug print //debugPrintSourceTargetPair(pd, sourceCells, targetCells); //cout << "S/T Pair: Route d" << pd->getId() << " (" << s->x << ", " << s->y << ")-->(" << t->x << ", " << t->y << ")" << endl; } } // Now, clear the droplet count in the modules so can be used later for (unsigned i = 0; i < routableThisTS.size(); i++) if (routableThisTS.at(i)->GetReconfigMod()) routableThisTS.at(i)->GetReconfigMod()->resetNumDrops(); // Now that we've gotten the source/target information, check to see if there is a conflict map<Droplet *, RoutePoint *>::iterator srcIt = sourceCells->begin(); for (; srcIt != sourceCells->end(); srcIt++) { RoutePoint *s = sourceCells->find(srcIt->first)->second; Droplet *d = sourceCells->find(srcIt->first)->first; // Do not move droplet if already at destination if (!(s->x == targetCells->find(d)->second->x && s->y == targetCells->find(d)->second->y)) { // If we find an interference with another droplet's target, we must move the source location map<Droplet *, RoutePoint *>::iterator tgtIt = targetCells->begin(); for (; tgtIt != targetCells->end(); tgtIt++) { RoutePoint *t = targetCells->find(tgtIt->first)->second; // If the source/target pair is not same route and interferes with each other, try moving the source if (doesInterfere(s, t) && (srcIt->first != tgtIt->first)) { bool reRouted = false; int maxRerouteDist = 5; // Try moving up to x=5 cells in each direction ///////////////////////// // Try LEFT/WEST ///////////////////////// if (!reRouted) { int dist = 1; int newXDim; // Mod // While less than max reroute distance, hasn't already been re-reouted, and reroute is on DMFB while (dist <= maxRerouteDist && !reRouted && (newXDim = s->x - dist) >= 0) // MOD { RoutePoint *sDelta = new RoutePoint(); sDelta->x = newXDim; sDelta->y = s->y; if (!rpInterferesWithRpList(sDelta, sourceCells, d)) { if (!rpInterferesWithRpList(sDelta, targetCells, d)) { if(!rpInterferesWithPersistentModule(sDelta)) { unsigned long long int c = (*routes)[d]->back()->cycle; // Add new re-route to routes for (int i = 1; i <= dist; i++) { RoutePoint *newRp = new RoutePoint(); newRp->x = s->x - i; // MOD newRp->y = s->y; // MOD newRp->dStatus = DROP_NORMAL; newRp->cycle = c + i; (*routes)[d]->push_back(newRp); } (*routes)[d]->back()->dStatus = DROP_WAIT; // Set last location as waiting // Update s within our sources list s->x = (*routes)[d]->back()->x; s->y = (*routes)[d]->back()->y; s->dStatus = (*routes)[d]->back()->dStatus; reRouted = true; routeCycle = routeCycle + dist; equalizeGlobalRoutes(routes); // Equalize the routes so all droplets will appear in simulation during re-route cycles } else // If hit module, cannot take this direction break; } } else // If hit another source, then cannot take this direction break; dist++; } } ///////////////////////// // Try RIGHT/EAST ///////////////////////// if (!reRouted) { int dist = 1; int newXDim; // While less than max reroute distance, hasn't already been re-reouted, and reroute is on DMFB while (dist <= maxRerouteDist && !reRouted && (newXDim = s->x + dist) < arch->getNumCellsX()) { RoutePoint *sDelta = new RoutePoint(); sDelta->x = newXDim; sDelta->y = s->y; if (!rpInterferesWithRpList(sDelta, sourceCells, d)) { if (!rpInterferesWithRpList(sDelta, targetCells, d)) { if(!rpInterferesWithPersistentModule(sDelta)) { unsigned long long int c = (*routes)[d]->back()->cycle; // Add new re-route to routes for (int i = 1; i <= dist; i++) { RoutePoint *newRp = new RoutePoint(); newRp->x = s->x + i; newRp->y = s->y; newRp->dStatus = DROP_NORMAL; newRp->cycle = c + i; (*routes)[d]->push_back(newRp); } (*routes)[d]->back()->dStatus = DROP_WAIT; // Set last location as waiting // Update s within our sources list s->x = (*routes)[d]->back()->x; s->y = (*routes)[d]->back()->y; s->dStatus = (*routes)[d]->back()->dStatus; reRouted = true; routeCycle = routeCycle + dist; equalizeGlobalRoutes(routes); // Equalize the routes so all droplets will appear in simulation during re-route cycles } else // If hit module, cannot take this direction break; } } else // If hit another source, then cannot take this direction break; dist++; } } ///////////////////////// // Try UP/NORTH ///////////////////////// if (!reRouted) { int dist = 1; int newYDim; // While less than max reroute distance, hasn't already been re-reouted, and reroute is on DMFB while (dist <= maxRerouteDist && !reRouted && (newYDim = s->y - dist) >= 0) { RoutePoint *sDelta = new RoutePoint(); sDelta->x = s->x; sDelta->y = newYDim; if (!rpInterferesWithRpList(sDelta, sourceCells, d)) { if (!rpInterferesWithRpList(sDelta, targetCells, d)) { if(!rpInterferesWithPersistentModule(sDelta)) { unsigned long long int c = (*routes)[d]->back()->cycle; // Add new re-route to routes for (int i = 1; i <= dist; i++) { RoutePoint *newRp = new RoutePoint(); newRp->x = s->x; newRp->y = s->y - i; newRp->dStatus = DROP_NORMAL; newRp->cycle = c + i; (*routes)[d]->push_back(newRp); } (*routes)[d]->back()->dStatus = DROP_WAIT; // Set last location as waiting // Update s within our sources list s->x = (*routes)[d]->back()->x; s->y = (*routes)[d]->back()->y; s->dStatus = (*routes)[d]->back()->dStatus; reRouted = true; routeCycle = routeCycle + dist; equalizeGlobalRoutes(routes); // Equalize the routes so all droplets will appear in simulation during re-route cycles } else // If hit module, cannot take this direction break; } } else // If hit another source, then cannot take this direction break; dist++; } } ///////////////////////// // Try DOWN/SOUTH ///////////////////////// if (!reRouted) { int dist = 1; int newYDim; // While less than max reroute distance, hasn't already been re-reouted, and reroute is on DMFB while (dist <= maxRerouteDist && !reRouted && (newYDim = s->y + dist) < arch->getNumCellsY()) { RoutePoint *sDelta = new RoutePoint(); sDelta->x = s->x; sDelta->y = newYDim; if (!rpInterferesWithRpList(sDelta, sourceCells, d)) { if (!rpInterferesWithRpList(sDelta, targetCells, d)) { if(!rpInterferesWithPersistentModule(sDelta)) { unsigned long long int c = (*routes)[d]->back()->cycle; // Add new re-route to routes for (int i = 1; i <= dist; i++) { RoutePoint *newRp = new RoutePoint(); newRp->x = s->x; newRp->y = s->y + i; newRp->dStatus = DROP_NORMAL; newRp->cycle = c + i; (*routes)[d]->push_back(newRp); } (*routes)[d]->back()->dStatus = DROP_WAIT; // Set last location as waiting // Update s within our sources list s->x = (*routes)[d]->back()->x; s->y = (*routes)[d]->back()->y; s->dStatus = (*routes)[d]->back()->dStatus; reRouted = true; routeCycle = routeCycle + dist; equalizeGlobalRoutes(routes); // Equalize the routes so all droplets will appear in simulation during re-route cycles } else // If hit module, cannot take this direction break; } } else // If hit another source, then cannot take this direction break; dist++; } } // If was re-rotued, good..exit loop. Else, exit and inform user. if (reRouted) break; // no need to compare to more sources...it is safe else claim(false, "Droplet dependency was not fixed; Attempt to break dependency by moving a source to free cells was a failure."); } } } } // Cleanup map<Droplet *, RoutePoint *>::iterator it; for (it = sourceCells->begin(); it != sourceCells->end(); it++) { RoutePoint *rp = it->second; it->second = NULL; delete rp; } sourceCells->clear(); delete sourceCells; for (it = targetCells->begin(); it != targetCells->end(); it++) { RoutePoint *rp = it->second; it->second = NULL; delete rp; } targetCells->clear(); delete targetCells; delete routingThisTS; } /////////////////////////////////////////////////////////////////////////////////// // Ensures that the given route point doesn't interfere with any of the route points // in the map/list, besides the route point that corresponds to the same droplet // (we are either comparing a source to the complete list of sources or complete // list of targets) /////////////////////////////////////////////////////////////////////////////////// bool PostSubproblemCompactionRouter::rpInterferesWithRpList(RoutePoint *rp, map<Droplet *, RoutePoint *> *rps, Droplet *d) { // Search through entire list map<Droplet *, RoutePoint *>::iterator rpIt = rps->begin(); for (; rpIt != rps->end(); rpIt++) { RoutePoint *rpCompare = rps->find(rpIt->first)->second; Droplet *dCompare = rpIt->first; if (d != dCompare && doesInterfere(rp, rpCompare)) return true; } return false; } /////////////////////////////////////////////////////////////////////////////////// // Ensures that the given route point doesn't interfere with any of the persisting // modules at the current time-step. /////////////////////////////////////////////////////////////////////////////////// bool PostSubproblemCompactionRouter::rpInterferesWithPersistentModule(RoutePoint *rp) { for (unsigned i = 0; i < thisTS->size(); i++) { AssayNode *n = thisTS->at(i); // Check all cells in all persistent modules (modules still executing; not starting/finishing this TS) if (n->type != DISPENSE && n->type != OUTPUT && startingTS > n->startTimeStep && startingTS < n->endTimeStep) { ReconfigModule *rm = n->reconfigMod; for (int x = rm->getLX(); x <= rm->getRX(); x++) { for (int y = rm->getTY(); y <= rm->getBY(); y++) { RoutePoint modPoint; modPoint.x = x; modPoint.y = y; if (doesInterfere(rp, &modPoint)) return true; } } } } return false; } /////////////////////////////////////////////////////////////////////////////////// // Ensures that the given route point doesn't interfere with any possible I/O ports. // That is, returns true if the route point is in the outer two cells of the DMFB // on any side. This function is used to help keep the perimeter clear for droplets // to be input/output. /////////////////////////////////////////////////////////////////////////////////// bool PostSubproblemCompactionRouter::rpInterferesWithPotentialIoLocations(RoutePoint *rp) { if (rp->x < 2 || rp->y < 2 || rp->x > arch->getNumCellsX() - 3 || rp->y > arch->getNumCellsY() - 3) return true; else return false; } /////////////////////////////////////////////////////////////////////////////////// // Computes the individual subroutes for a sub-problem. A new sub-route is created // for each sub-rotue and added to subRoutes; also, the corresponding droplet is // added to subDrops (corresponding routes and droplets must share the same index // in subRoutes and subDrops). // // This function is called each time-step that droplets are being routed; it computes // routes for a single sub-problem. // // Upon beginning this function, subRotues and subDrops is empty. Upon exiting // this funciton, subDrops is filled with a droplet for each droplet being routed // during this time-step/sub-problem AND subRoutes is filled with a non-compacted // route for each corresponding droplet in subDrops. The routes are computed // in isolation to be compacted later. // // This is the main function to be re-written by other routing algorithms as // the individual routes are typically computed in various ways. /////////////////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::computeIndivSupProbRoutes(vector<vector<RoutePoint *> *> *subRoutes, vector<Droplet *> *subDrops, map<Droplet *, vector<RoutePoint *> *> *routes) { claim(false, "No valid router was selected for the synthesis process or no method for 'computeIndivSupProbRoutes()' was implemented for the selected router.\n"); } /////////////////////////////////////////////////////////////////////////////////// // This function is the main public function called. It fills the "routes" and // "tsBeginningCycle" data structures and contains the code for the main routing flow. /////////////////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::route(DAG *dag, DmfbArch *arch, vector<ReconfigModule *> *rModules, map<Droplet *, vector<RoutePoint *> *> *routes, vector<vector<int> *> *pinActivations, vector<unsigned long long> *tsBeginningCycle) { cyclesPerTS = arch->getSecPerTS() * arch->getFreqInHz(); startingTS = 0; // The TS that is getting ready to begin (droplets are being routed to) routeCycle = 0; cycle = 0; // Copy all nodes to a new list to be sorted vector<AssayNode *> nodes;// = new vector<AssayNode *>(); for (unsigned i = 0; i < dag->getAllNodes().size(); i++) nodes.push_back(dag->getAllNodes().at(i)); Sort::sortNodesByStartThenEndTS(&nodes); initCellTypeArray(); routerSpecificInits(); /////////////////////////////////////////////////////////////////////// // This is the main loop. Each iteration of this loop solves one // time-step (routing sub-problem) /////////////////////////////////////////////////////////////////////// while(!nodes.empty()) { int j = 0; while ( j < nodes.size() && nodes.at(j)->GetStartTS() <= startingTS && nodes.at(j)->GetEndTS() >= startingTS && j < nodes.size()) thisTS->push_back(nodes.at(j++)); //if (startingTS >= 67) //{ // cout << "DebugPrint: Routing to TS " << startingTS << "." << endl; // DTG Debug Print //return; //} /////////////////////////////////////////////////////////////////////// // First create any new droplets /////////////////////////////////////////////////////////////////////// for (unsigned i = 0; i < thisTS->size(); i++) { AssayNode *n = thisTS->at(i); if (n->GetType() == DISPENSE && n->GetStartTS() == startingTS) { // Create new droplets to be input soon Droplet *d = new Droplet(); stringstream ss; ss << n->GetVolume() << " parts " << n->GetPortName(); d->uniqueFluidName = ss.str(); d->volume = n->GetVolume(); (*routes)[d] = new vector<RoutePoint *>(); n->addDroplet(d); } } /////////////////////////////////////////////////////////////////////// // Then, get the initial individual routes to be compacted later /////////////////////////////////////////////////////////////////////// routeCycle = cycle; vector<vector<RoutePoint *> *> *subRoutes = new vector<vector<RoutePoint *> *>(); // subProblem routes vector<Droplet *> *subDrops = new vector<Droplet *>(); // corresponding subProblem droplets // If not a binder (which can take advantage of intra-module syncing to avoid dependencies), then eliminate dependencies if (!(getPastPlacerType() == GRISSOM_LE_B || getPastPlacerType() == GRISSOM_PATH_B)) eliminateSubRouteDependencies(routes); // Optional; ensures that no source is in the IR of a target (moves the source out of way) computeIndivSupProbRoutes(subRoutes, subDrops, routes); printSubRoutes(subRoutes, subDrops); /////////////////////////////////////////////////////////////////////// // Then, compact and do maintenance on the routes /////////////////////////////////////////////////////////////////////// compactRoutes(subDrops, subRoutes); // Now, do route COMPACTION addSubProbToGlobalRoutes(subDrops, subRoutes, routes); // Add sub-rotues to routes for entire simulation equalizeGlobalRoutes(routes); // Now, add cycles for the droplets that were waiting first so they look like they were really waiting there tsBeginningCycle->push_back(cycle); // Add cycle so we now when time-step begins processTimeStep(routes); // Now that routing is done, process the time-step /////////////////////////////////////////////////////////////////////// // Cleanup /////////////////////////////////////////////////////////////////////// for (int i = nodes.size()-1; i >= 0; i--) if (nodes.at(i)->endTimeStep <= startingTS) if (!(nodes.at(i)->startTimeStep == nodes.at(i)->endTimeStep && nodes.at(i)->startTimeStep == startingTS)) // Don't delete instant operations that are not yet processed nodes.erase(nodes.begin() + i); while (!subRoutes->empty()) { vector<RoutePoint *> * v = subRoutes->back(); subRoutes->pop_back(); delete v; // Individual RoutePoints are deleted later by the Util Class } delete subRoutes; delete subDrops; thisTS->clear(); } } /////////////////////////////////////////////////////////////////////////////////// // Debug function to print the computed subroutes /////////////////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::printSubRoutes(vector<vector<RoutePoint *> *> *subRoutes, vector<Droplet *> *subDrops) { cout << "Routing to TS " << startingTS << ":" << endl; for (unsigned i = 0; i < subDrops->size(); i++) { Droplet *d = subDrops->at(i); vector<RoutePoint *> *route = subRoutes->at(i); cout << d->id << ": "; for (unsigned j = 0; j < route->size(); j++) cout << "(" << route->at(j)->x << ", " << route->at(j)->y << ") "; cout << endl; } cout << endl; } /////////////////////////////////////////////////////////////////////////////////// // Prints out source-target pair for the given droplet. /////////////////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::debugPrintSourceTargetPair(Droplet *d, map<Droplet *, RoutePoint *> *sourceCells, map<Droplet *, RoutePoint *> *targetCells) { RoutePoint *s = sourceCells->at(d); RoutePoint *t = targetCells->at(d); cout << "S/T Pair: Route d" << d->getId() << " (" << s->x << ", " << s->y << ")-->(" << t->x << ", " << t->y << ")" << endl; } /////////////////////////////////////////////////////////////////////////////////// // Given the routes, counts and lists the number of intersections /////////////////////////////////////////////////////////////////////////////////// void PostSubproblemCompactionRouter::printNumIntersections(vector<vector<RoutePoint *> *> *subRoutes, DmfbArch *arch) { // Create a board to count number of times a droplet crossed a cell vector<int> column(arch->getNumCellsY(), 0); vector< vector<int> > board(arch->getNumCellsX(), column); int numberDropletMovements = 0; int compactedRouteLength = 0; // Increment cell contamination count //typedef map<Droplet *, vector<RoutePoint *> *>::iterator route_it; for(unsigned i = 0; i < subRoutes->size(); i++) { vector<RoutePoint*> * route = subRoutes->at(i); for(unsigned j = 0; j < route->size() ; j++) { if (route->at(j)) { if (!(route->at(j) == route->back() && route->at(j)->dStatus != DROP_OUTPUT)) { int x = route->at(j)->x; int y = route->at(j)->y; board[x][y]++; } numberDropletMovements++; // Increment instead of just add whole size b/c we don't want to count NULLs } } if (route->size() > compactedRouteLength) compactedRouteLength = route->size(); //total_route_length += route->size(); } int total_crossings = 0; for(unsigned i = 0; i < board.size() ; i++) for(unsigned j = 0; j < board[i].size() ; j++) if(board[i][j] > 1) total_crossings += board[i][j] - 1; // Easy-to-read output cout << "Routing to TS " << startingTS << ":" << endl; cout << "Total Crossings: " << total_crossings <<endl; cout << "Number of droplet movements: " << numberDropletMovements << endl; cout << "Compacted Route Length: " << compactedRouteLength << endl << endl; // CSV Compatible output //cout << "TS,# Crossings, # Drop Movements, Compacted Route Length" << endl; //cout << startingTS << "," << total_crossings << "," << numberDropletMovements << "," << compactedRouteLength << endl; }
[ "mohiuddin.a.qader@gmail.com" ]
mohiuddin.a.qader@gmail.com
7d567ad55a456cee8579de9a590ef0b87151ed10
e417cdec35d79628b12eba11fd77c19571ccdc56
/src/test/transaction_tests.cpp
c6290e43ada3c87b1bb179cb8032c3e73e08a998
[ "MIT" ]
permissive
bitspill/knavecoin
4daa71e195280ce9366835048df5f06395da8937
4f7757616176491e7e4d8fa092fac897503fd361
refs/heads/master
2021-03-24T11:53:19.860931
2014-04-29T08:28:20
2014-04-29T08:28:20
59,814,983
0
0
null
2016-05-27T07:36:41
2016-05-27T07:36:41
null
UTF-8
C++
false
false
11,433
cpp
#include <map> #include <string> #include <boost/test/unit_test.hpp> #include "json/json_spirit_writer_template.h" #include "main.h" #include "wallet.h" using namespace std; using namespace json_spirit; // In script_tests.cpp extern Array read_json(const std::string& filename); extern CScript ParseScript(string s); BOOST_AUTO_TEST_SUITE(transaction_tests) BOOST_AUTO_TEST_CASE(tx_valid) { // Read tests from test/data/tx_valid.json // Format is an array of arrays // Inner arrays are either [ "comment" ] // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, enforceP2SH // ... where all scripts are stringified scripts. Array tests = read_json("tx_valid.json"); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); string strTest = write_string(tv, false); if (test[0].type() == array_type) { if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type) { BOOST_ERROR("Bad test: " << strTest); continue; } map<COutPoint, CScript> mapprevOutScriptPubKeys; Array inputs = test[0].get_array(); bool fValid = true; BOOST_FOREACH(Value& input, inputs) { if (input.type() != array_type) { fValid = false; break; } Array vinput = input.get_array(); if (vinput.size() != 3) { fValid = false; break; } mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str()); } if (!fValid) { BOOST_ERROR("Bad test: " << strTest); continue; } string transaction = test[1].get_str(); CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(tx.CheckTransaction(state), strTest); BOOST_CHECK(state.IsValid()); for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout)) { BOOST_ERROR("Bad test: " << strTest); break; } BOOST_CHECK_MESSAGE(VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0), strTest); } } } } BOOST_AUTO_TEST_CASE(tx_invalid) { // Read tests from test/data/tx_invalid.json // Format is an array of arrays // Inner arrays are either [ "comment" ] // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, enforceP2SH // ... where all scripts are stringified scripts. Array tests = read_json("tx_invalid.json"); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); string strTest = write_string(tv, false); if (test[0].type() == array_type) { if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type) { BOOST_ERROR("Bad test: " << strTest); continue; } map<COutPoint, CScript> mapprevOutScriptPubKeys; Array inputs = test[0].get_array(); bool fValid = true; BOOST_FOREACH(Value& input, inputs) { if (input.type() != array_type) { fValid = false; break; } Array vinput = input.get_array(); if (vinput.size() != 3) { fValid = false; break; } mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str()); } if (!fValid) { BOOST_ERROR("Bad test: " << strTest); continue; } string transaction = test[1].get_str(); CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; CValidationState state; fValid = tx.CheckTransaction(state) && state.IsValid(); for (unsigned int i = 0; i < tx.vin.size() && fValid; i++) { if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout)) { BOOST_ERROR("Bad test: " << strTest); break; } fValid = VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0); } BOOST_CHECK_MESSAGE(!fValid, strTest); } } } BOOST_AUTO_TEST_CASE(basic_transaction_tests) { // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436) unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00}; vector<unsigned char> vch(ch, ch + sizeof(ch) -1); CDataStream stream(vch, SER_DISK, CLIENT_VERSION); CTransaction tx; stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(tx.CheckTransaction(state) && state.IsValid(), "Simple deserialized transaction should be valid."); // Check that duplicate txins fail tx.vin.push_back(tx.vin[0]); BOOST_CHECK_MESSAGE(!tx.CheckTransaction(state) || !state.IsValid(), "Transaction with duplicate txins should be invalid."); } // // Helper: create two dummy transactions, each with // two outputs. The first has 11 and 50 CENT outputs // paid to a TX_PUBKEY, the second 21 and 22 CENT outputs // paid to a TX_PUBKEYHASH. // static std::vector<CTransaction> SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsView & coinsRet) { std::vector<CTransaction> dummyTransactions; dummyTransactions.resize(2); // Add some keys to the keystore: CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(i % 2); keystoreRet.AddKey(key[i]); } // Create some dummy input transactions dummyTransactions[0].vout.resize(2); dummyTransactions[0].vout[0].nValue = 11*CENT; dummyTransactions[0].vout[0].scriptPubKey << key[0].GetPubKey() << OP_CHECKSIG; dummyTransactions[0].vout[1].nValue = 50*CENT; dummyTransactions[0].vout[1].scriptPubKey << key[1].GetPubKey() << OP_CHECKSIG; coinsRet.SetCoins(dummyTransactions[0].GetHash(), CCoins(dummyTransactions[0], 0)); dummyTransactions[1].vout.resize(2); dummyTransactions[1].vout[0].nValue = 21*CENT; dummyTransactions[1].vout[0].scriptPubKey.SetDestination(key[2].GetPubKey().GetID()); dummyTransactions[1].vout[1].nValue = 22*CENT; dummyTransactions[1].vout[1].scriptPubKey.SetDestination(key[3].GetPubKey().GetID()); coinsRet.SetCoins(dummyTransactions[1].GetHash(), CCoins(dummyTransactions[1], 0)); return dummyTransactions; } BOOST_AUTO_TEST_CASE(test_Get) { CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(coinsDummy); std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins); CTransaction t1; t1.vin.resize(3); t1.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t1.vin[0].prevout.n = 1; t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0); t1.vin[1].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[1].prevout.n = 0; t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vin[2].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[2].prevout.n = 1; t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vout.resize(2); t1.vout[0].nValue = 90*CENT; t1.vout[0].scriptPubKey << OP_1; BOOST_CHECK(t1.AreInputsStandard(coins)); BOOST_CHECK_EQUAL(t1.GetValueIn(coins), (50+21+22)*CENT); // Adding extra junk to the scriptSig should make it non-standard: t1.vin[0].scriptSig << OP_11; BOOST_CHECK(!t1.AreInputsStandard(coins)); // ... as should not having enough: t1.vin[0].scriptSig = CScript(); BOOST_CHECK(!t1.AreInputsStandard(coins)); } BOOST_AUTO_TEST_CASE(test_IsStandard) { CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(coinsDummy); std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins); CTransaction t; t.vin.resize(1); t.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t.vin[0].prevout.n = 1; t.vin[0].scriptSig << std::vector<unsigned char>(65, 0); t.vout.resize(1); t.vout[0].nValue = 90*CENT; CKey key; key.MakeNewKey(true); t.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); BOOST_CHECK(t.IsStandard()); t.vout[0].nValue = 5011; // dust // Knavecoin does not enforce isDust(). Per dust fees are considered sufficient as deterrant. // BOOST_CHECK(!t.IsStandard()); t.vout[0].nValue = 6011; // not dust BOOST_CHECK(t.IsStandard()); t.vout[0].scriptPubKey = CScript() << OP_1; BOOST_CHECK(!t.IsStandard()); } BOOST_AUTO_TEST_SUITE_END()
[ "jr.white@yandex.ru" ]
jr.white@yandex.ru
cfc15f4c6e37ab19848e399b10618920ca71e466
a7caaf953a0849f6081e44382da74a600a86b3da
/opencv-2.4.9/samples/cpp/ffilldemo.cpp
fd697b23aece466dec1118cca94e468a7ffc0b94
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
watinha/collector
22d22116fc1dbdfeec3bddb05aa42d05efe5b5b4
fc4758f87aad99084ce4235de3e929d80c56a072
refs/heads/master
2021-12-28T11:12:50.548082
2021-08-19T20:05:20
2021-08-19T20:05:20
136,666,875
2
1
Apache-2.0
2021-04-26T16:55:02
2018-06-08T21:17:16
C++
UTF-8
C++
false
false
4,593
cpp
#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> using namespace cv; using namespace std; static void help() { cout << "\nThis program demonstrated the floodFill() function\n" "Call:\n" "./ffilldemo [image_name -- Default: fruits.jpg]\n" << endl; cout << "Hot keys: \n" "\tESC - quit the program\n" "\tc - switch color/grayscale mode\n" "\tm - switch mask mode\n" "\tr - restore the original image\n" "\ts - use null-range floodfill\n" "\tf - use gradient floodfill with fixed(absolute) range\n" "\tg - use gradient floodfill with floating(relative) range\n" "\t4 - use 4-connectivity mode\n" "\t8 - use 8-connectivity mode\n" << endl; } Mat image0, image, gray, mask; int ffillMode = 1; int loDiff = 20, upDiff = 20; int connectivity = 4; int isColor = true; bool useMask = false; int newMaskVal = 255; static void onMouse( int event, int x, int y, int, void* ) { if( event != CV_EVENT_LBUTTONDOWN ) return; Point seed = Point(x,y); int lo = ffillMode == 0 ? 0 : loDiff; int up = ffillMode == 0 ? 0 : upDiff; int flags = connectivity + (newMaskVal << 8) + (ffillMode == 1 ? CV_FLOODFILL_FIXED_RANGE : 0); int b = (unsigned)theRNG() & 255; int g = (unsigned)theRNG() & 255; int r = (unsigned)theRNG() & 255; Rect ccomp; Scalar newVal = isColor ? Scalar(b, g, r) : Scalar(r*0.299 + g*0.587 + b*0.114); Mat dst = isColor ? image : gray; int area; if( useMask ) { threshold(mask, mask, 1, 128, CV_THRESH_BINARY); area = floodFill(dst, mask, seed, newVal, &ccomp, Scalar(lo, lo, lo), Scalar(up, up, up), flags); imshow( "mask", mask ); } else { area = floodFill(dst, seed, newVal, &ccomp, Scalar(lo, lo, lo), Scalar(up, up, up), flags); } imshow("image", dst); cout << area << " pixels were repainted\n"; } int main( int argc, char** argv ) { char* filename = argc >= 2 ? argv[1] : (char*)"fruits.jpg"; image0 = imread(filename, 1); if( image0.empty() ) { cout << "Image empty. Usage: ffilldemo <image_name>\n"; return 0; } help(); image0.copyTo(image); cvtColor(image0, gray, COLOR_BGR2GRAY); mask.create(image0.rows+2, image0.cols+2, CV_8UC1); namedWindow( "image", 0 ); createTrackbar( "lo_diff", "image", &loDiff, 255, 0 ); createTrackbar( "up_diff", "image", &upDiff, 255, 0 ); setMouseCallback( "image", onMouse, 0 ); for(;;) { imshow("image", isColor ? image : gray); int c = waitKey(0); if( (c & 255) == 27 ) { cout << "Exiting ...\n"; break; } switch( (char)c ) { case 'c': if( isColor ) { cout << "Grayscale mode is set\n"; cvtColor(image0, gray, COLOR_BGR2GRAY); mask = Scalar::all(0); isColor = false; } else { cout << "Color mode is set\n"; image0.copyTo(image); mask = Scalar::all(0); isColor = true; } break; case 'm': if( useMask ) { destroyWindow( "mask" ); useMask = false; } else { namedWindow( "mask", 0 ); mask = Scalar::all(0); imshow("mask", mask); useMask = true; } break; case 'r': cout << "Original image is restored\n"; image0.copyTo(image); cvtColor(image, gray, COLOR_BGR2GRAY); mask = Scalar::all(0); break; case 's': cout << "Simple floodfill mode is set\n"; ffillMode = 0; break; case 'f': cout << "Fixed Range floodfill mode is set\n"; ffillMode = 1; break; case 'g': cout << "Gradient (floating range) floodfill mode is set\n"; ffillMode = 2; break; case '4': cout << "4-connectivity mode is set\n"; connectivity = 4; break; case '8': cout << "8-connectivity mode is set\n"; connectivity = 8; break; } } return 0; }
[ "watinha@gmail.com" ]
watinha@gmail.com
f1d8a4da3a503dfadcf36f920ff8c8a977c18fdc
1437ff01dfdaf1cd6f58b7e0bbfcb94d5f624887
/opengl with ui/workingproject/workingproject/imgui.cpp
bb0ee4597e14e220465a2632134676bc26246af3
[ "MIT" ]
permissive
Jimmos1/OpenGLTB
119e0f1eb6007cb23f2a25e775187c40284f4973
abd31a3feaee035e197c42a33ec0423b8cd65f7f
refs/heads/master
2020-06-27T14:04:30.252281
2019-08-01T04:20:52
2019-08-01T04:20:52
199,972,226
0
0
null
null
null
null
UTF-8
C++
false
false
503,157
cpp
// dear imgui, v1.72 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. // Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui // Releases change-log at https://github.com/ocornut/imgui/releases // Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269 // 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 I need your support to sustain development and maintenance. // Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README. // Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui. // 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 me!) - Read first. - How to update to a newer version of Dear ImGui. - Getting started with integrating Dear ImGui in your code/engine. - This is how a simple application may look like (2 variations). - This is 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), TIPS - Where is the documentation? - Which version should I get? - Who uses Dear ImGui? - Why the odd dual naming, "Dear ImGui" vs "ImGui"? - How can I tell whether to dispatch mouse/keyboard to imgui or to my application? - How can I display an image? What is ImTextureID, how does it works? - Why are multiple widgets reacting when I interact with a single one? How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack... - How can I use my own math types instead of ImVec2/ImVec4? - How can I load a different font than the default? - How can I easily use icons in my application? - How can I load multiple fonts? - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? - How can I interact with standard C++ types (such as std::string and std::vector)? - How can I use the drawing facilities without a Dear ImGui window? (using ImDrawList API) - How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad) - I integrated Dear ImGui in my engine and the text or lines are blurry.. - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - How can I help? CODE (search for "[SECTION]" in the code to find them) // [SECTION] FORWARD DECLARATIONS // [SECTION] CONTEXT AND MEMORY ALLOCATORS // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) // [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions) // [SECTION] MISC HELPERS/UTILITIES (ImText* functions) // [SECTION] MISC HELPERS/UTILITIES (Color functions) // [SECTION] ImGuiStorage // [SECTION] ImGuiTextFilter // [SECTION] ImGuiTextBuffer // [SECTION] ImGuiListClipper // [SECTION] RENDER HELPERS // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) // [SECTION] TOOLTIPS // [SECTION] POPUPS // [SECTION] KEYBOARD/GAMEPAD NAVIGATION // [SECTION] COLUMNS // [SECTION] DRAG AND DROP // [SECTION] LOGGING/CAPTURING // [SECTION] SETTINGS // [SECTION] PLATFORM DEPENDENT HELPERS // [SECTION] METRICS/DEBUG 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 screen real-estate usage. - Minimize setup and maintenance. - Minimize state storage on user side. - Portable, minimize dependencies, run on target (consoles, phones, etc.). - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,. opening a tree node for the first time, etc. but a typical frame should not allocate anything). Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - Doesn't look fancy, doesn't animate. - Limited layout features, intricate layouts are typically crafted in code. 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: - Read the FAQ below this section! - 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 docs/README.md. - 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. - Add the Dear ImGui 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 informatioe are stored into command-lists that you will retrieve after calling ImGui::Render(). - Refer to the bindings 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 BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder). // 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 bindings (here we are using imgui_impl_win32 and imgui_impl_dx11) 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(); HOW A SIMPLE APPLICATION MAY LOOK LIKE: EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / 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 below 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 bindings) 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(); HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE: 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-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer); } idx_buffer += pcmd->ElemCount; } } } - The examples/ folders contains many actual implementation of the pseudo-codes above. - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated. They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the rest of your application. In every cases you need to pass on the inputs to Dear ImGui. Refer to the FAQ for more information. - Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues! 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. - 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. - 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. - 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 back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding 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. - 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. - 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 a dummy 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. Keep 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 bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports. when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call. in particular, note that old bindings 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 binding 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. Keep 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 binding 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. If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to 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_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. - the signature of the io.RenderDrawListsFn handler has changed! 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. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; } became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; } 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. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== Q: 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. - Your programming IDE is your friend, find the type or function declaration to find comments associated to it. Q: Which version should I get? A: I occasionally tag Releases (https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. You may also peak at the 'docking' branch which includes: - Docking/Merging features (https://github.com/ocornut/imgui/issues/2109) - Multi-viewport features (https://github.com/ocornut/imgui/issues/1542) Many projects are using this branch and it is kept in sync with master regularly. Q: Who uses Dear ImGui? A: See "Quotes" (https://github.com/ocornut/imgui/wiki/Quotes) and "Software using Dear ImGui" (https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for a list of games/software which are publicly known to use dear imgui. Please add yours if you can! Q: Why the odd dual naming, "Dear ImGui" vs "ImGui"? A: The library started its life as "ImGui" due to the fact that I didn't give it a proper name when when I released 1.0, and had no particular expectation that it would take off. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations (e.g. Unity uses it own implementation of the IMGUI paradigm). To reduce the ambiguity without affecting existing code bases, I have decided on an alternate, longer name "Dear ImGui" that people can use to refer to this specific library. Please try to refer to this library as "Dear ImGui". Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or to my application? A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } ) - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application. - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application. - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS). Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false. This is because imgui needs to detect that you clicked in the void to unfocus its own windows. Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs. Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags(). Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.) Q: How can I display an image? What is ImTextureID, how does it works? A: Short explanation: - You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures. - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value. - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason). Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward. Long explanation: - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices. At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.). - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API. We carry the information to identify a "texture" in the ImTextureID type. ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice. Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function. - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp) DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp) DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp) DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp) For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID. Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure tying together both the texture and information about its format and how to read it. - If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them. If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID representation suggested by the example bindings is probably the best choice. (Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer) User code may do: // Cast our texture type to ImTextureID / void* MyTexture* texture = g_CoffeeTableTexture; ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height)); The renderer function called after ImGui::Render() will receive that same value that the user code passed: // Cast ImTextureID / void* stored in the draw command as our texture type MyTexture* texture = (MyTexture*)pcmd->TextureId; MyEngineBindTexture2D(texture); Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui. This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them. If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using. Here's a simplified OpenGL example using stb_image.h: // Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data: #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> [...] int my_image_width, my_image_height; unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4); // Turn the RGBA pixel data into an OpenGL texture: GLuint my_opengl_texture; glGenTextures(1, &my_opengl_texture); glBindTexture(GL_TEXTURE_2D, my_opengl_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data); // Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it: ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height)); C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa. Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*. Examples: GLuint my_tex = XXX; void* my_void_ptr; my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer) my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint ID3D11ShaderResourceView* my_dx11_srv = XXX; void* my_void_ptr; my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void* my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView* Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated. Q: Why are multiple widgets reacting when I interact with a single one? Q: How can I have multiple widgets with the same label or with an empty label? A: A primer on labels and the ID Stack... Dear ImGui internally need to uniquely identify UI elements. Elements that are typically not clickable (such as calls to the Text functions) don't need an ID. Interactive widgets (such as calls to Button buttons) need a unique ID. Unique ID are used internally to track active widgets and occasionally associate state to widgets. Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element. - Unique ID are often derived from a string label: Button("OK"); // Label = "OK", ID = hash of (..., "OK") Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel") - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having two buttons labeled "OK" in different windows or different tree locations is fine. We used "..." above to signify whatever was already pushed to the ID stack previously: Begin("MyWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK") End(); Begin("MyOtherWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK") End(); - If you have a same ID twice in the same location, you'll have a conflict: Button("OK"); Button("OK"); // ID collision! Interacting with either button will trigger the first one. Fear not! this is easy to solve and there are many ways to solve it! - Solving ID conflict in a simple/local context: When passing a label you can optionally specify extra ID information within string itself. Use "##" to pass a complement to the ID that won't be visible to the end-user. This helps solving the simple collision cases when you know e.g. at compilation time which items are going to be created: Begin("MyWindow"); Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play") Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above End(); - If you want to completely hide the label, but still need an ID: Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox! - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. For example you may want to include varying information in a window title bar, but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID: Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID") Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different sprintf(buf, "My game (%f FPS)###MyGame", fps); Begin(buf); // Variable title, ID = hash of "MyGame" - Solving ID conflict in a more general manner: Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts within the same window. This is the most convenient way of distinguishing ID when iterating and creating many UI elements programmatically. You can push a pointer, a string or an integer value into the ID stack. Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack. At each level of the stack we store the seed used for items at this level of the ID stack. Begin("Window"); for (int i = 0; i < 100; i++) { PushID(i); // Push i to the id tack Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click") PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj); Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click") PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj->Name); Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click") PopID(); } End(); - You can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of (..., "Click") PushID("node"); Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") PushID(my_ptr); Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click") PopID(); PopID(); - Tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of (..., "Click") if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag) { Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") TreePop(); } - When working with trees, ID are used to preserve the open/close state of each tree node. Depending on your use cases you may want to use strings, indices or pointers as ID. e.g. when following a single pointer that may change over time, using a static string as ID will preserve your node open/closed state when the targeted object change. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. See what makes more sense in your situation! Q: How can I use my own math types instead of ImVec2/ImVec4? A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions. This way you'll be able to use your own types everywhere, e.g. passing glm::vec2 to ImGui functions instead of ImVec2. Q: How can I load a different font than the default? A: Use the font atlas to load the TTF/OTF file you want: ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code. (Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.) (Read the 'misc/fonts/README.txt' file for more details about font loading.) New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash "\\": io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!) io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT Q: How can I easily use icons in my application? A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment. (Read the 'misc/fonts/README.txt' file for more details about icons font loading.) With some extra effort, you may use colorful icon by registering custom rectangle space inside the font atlas, and copying your own graphics data into it. See misc/fonts/README.txt about using the AddCustomRectFontGlyph API. Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: (Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.) ImGuiIO& io = ImGui::GetIO(); ImFont* font0 = io.Fonts->AddFontDefault(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() // the first loaded font gets used by default // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime // Options ImFontConfig config; config.OversampleH = 2; config.OversampleV = 1; config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config); // Combine multiple fonts into one (e.g. for icon fonts) static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontDefault(); io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. // Add default Japanese ranges io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need) ImVector<ImWchar> ranges; ImFontGlyphRangesBuilder builder; builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) builder.AddChar(0x7262); // Add a specific character builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work! Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter(). The applications in examples/ are doing that. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state. Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly. Q: How can I interact with standard C++ types (such as std::string and std::vector)? A: - Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers), and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases. - To use ImGui::InputText() with a std::string or any resizable string class, see misc/cpp/imgui_stdlib.h. - To use combo boxes and list boxes with std::vector or any other data structure: the BeginCombo()/EndCombo() API lets you iterate and submit items yourself, so does the ListBoxHeader()/ListBoxFooter() API. Prefer using them over the old and awkward Combo()/ListBox() api. - Generally for most high-level types you should be able to access the underlying data type. You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code). - Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application. Please bear in mind that using std::string on applications with large amount of UI may incur unsatisfactory performances. Modern implementations of std::string often include small-string optimization (which is often a local buffer) but those are not configurable and not the same across implementations. - If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead. One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str This is a small helper where you can instance strings with configurable local buffers length. Many game engines will provide similar or better string helpers. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags. (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse) Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - You can call ImGui::GetBackgroundDrawList() or ImGui::GetForegroundDrawList() and use those draw list to display contents behind or over every other imgui windows (one bg/fg drawlist per viewport). - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls". (short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad) - You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy) This is the preferred solution for developer productivity. In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer. Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols. - You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine. - For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing for screen real-estate and precision. Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. A: You are probably mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). Q: How can I help? A: - 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! - Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui. - Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README. - 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/1902). 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). - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug". - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. - tip: you can call Render() multiple times (e.g for VR renders). - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui! */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui/imgui.h" #ifndef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS #endif #include "imgui/imgui_internal.h" #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 // 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 // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif // Clang/GCC warnings with -Weverything #if defined(__clang__) #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference 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' #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") #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. #endif #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 // 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 back-end) 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. //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS //------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); static void CheckStacksSize(ImGuiWindow* window, bool write); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); 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* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, 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 { static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags); // Navigation static void NavUpdate(); static void NavUpdateWindowing(); static void NavUpdateWindowingList(); static void NavUpdateMoveResult(); static float NavUpdatePageUpPageDown(int allowed_dir_flags); static inline void NavUpdateAnyRequestFlag(); 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); // Misc static void UpdateMouseInputs(); static void UpdateMouseWheel(); static bool UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); 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] MAIN 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 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. 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. 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 when button is larger than text. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area 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-aliasing on lines/borders. Disable if you are really short on CPU/GPU. AntiAliasedFill = true; // Enable anti-aliasing on 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. // 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); TabRounding = ImFloor(TabRounding * scale_factor); 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)); // 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.250f; 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; // 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; #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS RenderDrawListsFn = NULL; #endif // 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 && c < 0x10000) InputQueueCharacters.push_back((ImWchar)c); } 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 && c < 0x10000) InputQueueCharacters.push_back((ImWchar)c); } } void ImGuiIO::ClearInputCharacters() { InputQueueCharacters.resize(0); } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions) //----------------------------------------------------------------------------- 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; } // 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-bits 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 } // 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_FORMAT_STRING_FUNCTIONS //#define IMGUI_USE_STB_SPRINTF #ifdef IMGUI_USE_STB_SPRINTF #define STB_SPRINTF_IMPLEMENTATION #include "imstb_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_FORMAT_STRING_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; } FILE* ImFileOpen(const char* filename, const char* mode) { #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__) // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; ImVector<ImWchar> buf; buf.resize(filename_wsize + mode_wsize); ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); #else return fopen(filename, mode); #endif } // Load file content into memory // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes) { IM_ASSERT(filename && file_open_mode); if (out_file_size) *out_file_size = 0; FILE* f; if ((f = ImFileOpen(filename, file_open_mode)) == NULL) return NULL; long file_size_signed; if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return NULL; } size_t file_size = (size_t)file_size_signed; void* file_data = IM_ALLOC(file_size + padding_bytes); if (file_data == NULL) { fclose(f); return NULL; } if (fread(file_data, 1, file_size, f) != file_size) { fclose(f); IM_FREE(file_data); return NULL; } if (padding_bytes > 0) memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes); fclose(f); if (out_file_size) *out_file_size = file_size; return file_data; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (ImText* functions) //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bits character, process single character input. // Based on stb_from_utf8() from github.com/nothings/stb/ // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { unsigned int c = (unsigned int)-1; const unsigned char* str = (const unsigned char*)in_text; if (!(*str & 0x80)) { c = (unsigned int)(*str++); *out_char = c; return 1; } if ((*str & 0xe0) == 0xc0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 2) return 1; if (*str < 0xc2) return 2; c = (unsigned int)((*str++ & 0x1f) << 6); if ((*str & 0xc0) != 0x80) return 2; c += (*str++ & 0x3f); *out_char = c; return 2; } if ((*str & 0xf0) == 0xe0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 3) return 1; if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x0f) << 12); if ((*str & 0xc0) != 0x80) return 3; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 3; c += (*str++ & 0x3f); *out_char = c; return 3; } if ((*str & 0xf8) == 0xf0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 4) return 1; if (*str > 0xf4) return 4; if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x07) << 18); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 12); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 4; c += (*str++ & 0x3f); // utf-8 encodings of values used in surrogate pairs are invalid if ((c & 0xFFFFF800) == 0xD800) return 4; *out_char = c; return 4; } *out_char = 0; return 0; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes *buf_out++ = (ImWchar)c; } *buf_out = 0; if (in_text_remaining) *in_text_remaining = in_text; return (int)(buf_out - buf); } int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) { int char_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) char_count++; } return char_count; } // Based on stb_to_utf8() from github.com/nothings/stb/ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (c < 0x80) { buf[0] = (char)c; return 1; } if (c < 0x800) { if (buf_size < 2) return 0; buf[0] = (char)(0xc0 + (c >> 6)); buf[1] = (char)(0x80 + (c & 0x3f)); return 2; } if (c >= 0xdc00 && c < 0xe000) { return 0; } if (c >= 0xd800 && c < 0xdc00) { if (buf_size < 4) return 0; buf[0] = (char)(0xf0 + (c >> 18)); buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[3] = (char)(0x80 + ((c ) & 0x3f)); return 4; } //else if (c < 0x10000) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c ) & 0x3f)); return 3; } } // Not optimal but we very rarely use this function. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end) { unsigned int dummy = 0; return ImTextCharFromUtf8(&dummy, in_text, in_text_end); } static inline int ImTextCountUtf8BytesFromChar(unsigned int c) { if (c < 0x80) return 1; if (c < 0x800) return 2; if (c >= 0xdc00 && c < 0xe000) return 0; if (c >= 0xd800 && c < 0xdc00) return 4; return 3; } int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) { char* buf_out = buf; const char* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); } *buf_out = 0; return (int)(buf_out - buf); } int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) { int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) bytes_count++; else bytes_count += ImTextCountUtf8BytesFromChar(c); } return bytes_count; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILTIES (Color functions) // Note: The Convert functions are early design which are not consistent with other API. //----------------------------------------------------------------------------- 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; } } 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) { float style_alpha = GImGui->Style.Alpha; 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); } //----------------------------------------------------------------------------- // [SECTION] ImGuiStorage // Helper: Key->value storage //----------------------------------------------------------------------------- // std::lower_bound but without the bullshit static ImGuiStorage::Pair* LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key) { ImGuiStorage::Pair* first = data.Data; ImGuiStorage::Pair* last = data.Data + data.Size; size_t count = (size_t)(last - first); while (count > 0) { size_t count2 = count >> 1; ImGuiStorage::Pair* 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 Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1; if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1; return 0; } }; if (Data.Size > 1) ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID); } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(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 { ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; } void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(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) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_i; } bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) { return (bool*)GetIntRef(key, default_val ? 1 : 0); } float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_p; } // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImGuiID key, int val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_i = val; } void ImGuiStorage::SetBool(ImGuiID key, bool val) { SetInt(key, val ? 1 : 0); } void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_f = val; } void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_p = val; } void ImGuiStorage::SetAllInt(int v) { for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } //----------------------------------------------------------------------------- // [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::TextRange::split(char separator, ImVector<TextRange>* out) const { out->resize(0); const char* wb = b; const char* we = wb; while (we < e) { if (*we == separator) { out->push_back(TextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) out->push_back(TextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); input_range.split(',', &Filters); CountGrep = 0; for (int i = 0; i != Filters.Size; i++) { TextRange& 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 TextRange& f = Filters[i]; if (f.empty()) continue; if (f.b[0] == '-') { // Subtract if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) return false; } else { // Grep if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) return true; } } // Implicit * grep if (CountGrep == 0) return true; return false; } //----------------------------------------------------------------------------- // [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.NavScoringRectScreen); 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 SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) { // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. // The clipper should probably have a 4th step to display the last item in a regular manner. ImGuiContext& g = *GImGui; 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 (ImGuiColumns* columns = window->DC.CurrentColumns) columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 // Use case B: Begin() called from constructor with items_height>0 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. void ImGuiListClipper::Begin(int count, float items_height) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; StartPosY = window->DC.CursorPos.y; ItemsHeight = items_height; ItemsCount = count; StepNo = 0; DisplayEnd = DisplayStart = -1; if (ItemsHeight > 0.0f) { ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display if (DisplayStart > 0) SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor StepNo = 2; } } void ImGuiListClipper::End() { if (ItemsCount < 0) return; // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX) SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; StepNo = 3; } bool ImGuiListClipper::Step() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (ItemsCount == 0 || window->SkipItems) { ItemsCount = -1; return false; } if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. { DisplayStart = 0; DisplayEnd = 1; StartPosY = window->DC.CursorPos.y; StepNo = 1; return true; } if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. { if (ItemsCount == 1) { ItemsCount = -1; return false; } float items_height = window->DC.CursorPos.y - StartPosY; IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically Begin(ItemsCount - 1, items_height); DisplayStart++; DisplayEnd++; StepNo = 3; return true; } if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. { IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); StepNo = 3; return true; } if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. End(); return false; } //----------------------------------------------------------------------------- // [SECTION] RENDER HELPERS // Those (internal) functions are currently quite a legacy mess - their signature and behavior will change. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state. //----------------------------------------------------------------------------- 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); if (text_size.x > pos_max.x - pos_min.x) { // Hello wo... // | | | // min max ellipsis_max // <-> this is generally some padding value // FIXME-STYLE: RenderPixelEllipsis() style should use actual font data. const ImFont* font = draw_list->_Data->Font; const float font_size = draw_list->_Data->FontSize; const int ellipsis_dot_count = 3; const float ellipsis_width = (1.0f + 1.0f) * ellipsis_dot_count - 1.0f; const char* text_end_ellipsis = NULL; float text_width = ImMax((pos_max.x - ellipsis_width) - pos_min.x, 1.0f); float text_size_clipped_x = font->CalcTextSizeA(font_size, text_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 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 } RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f)); const float ellipsis_x = pos_min.x + text_size_clipped_x + 1.0f; if (ellipsis_x + ellipsis_width - 1.0f <= ellipsis_max_x) RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_dot_count); } 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); } } // Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale) { const float h = draw_list->_Data->FontSize * 1.00f; float r = h * 0.40f * scale; ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale); ImVec2 a, b, c; switch (dir) { case ImGuiDir_Up: case ImGuiDir_Down: if (dir == ImGuiDir_Up) r = -r; a = ImVec2(+0.000f,+0.750f) * r; b = ImVec2(-0.866f,-0.750f) * r; c = ImVec2(+0.866f,-0.750f) * r; break; case ImGuiDir_Left: case ImGuiDir_Right: if (dir == ImGuiDir_Left) r = -r; a = ImVec2(+0.750f,+0.000f) * r; b = ImVec2(-0.750f,+0.866f) * r; c = ImVec2(-0.750f,-0.866f) * r; break; case ImGuiDir_None: case ImGuiDir_COUNT: IM_ASSERT(0); break; } draw_list->AddTriangleFilled(center + a, center + b, center + c, col); } void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col) { draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8); } void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float thickness = ImMax(sz / 5.0f, 1.0f); sz -= thickness*0.5f; pos += ImVec2(thickness*0.25f, thickness*0.25f); float third = sz / 3.0f; float bx = pos.x + third; float by = pos.y + sz - third*0.5f; window->DrawList->PathLineTo(ImVec2(bx - third, by - third)); window->DrawList->PathLineTo(ImVec2(bx, by)); window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2)); window->DrawList->PathStroke(col, false, thickness); } 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(&context->DrawListSharedData) { Name = ImStrdup(name); ID = ImHashStr(name); IDStack.push_back(ID); Flags = ImGuiWindowFlags_None; Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); ContentSize = ContentSizeExplicit = ImVec2(0.0f, 0.0f); WindowPadding = ImVec2(0.0f, 0.0f); WindowRounding = 0.0f; WindowBorderSize = 0.0f; NameBufLen = (int)strlen(name) + 1; MoveId = GetID("#MOVE"); ChildId = 0; Scroll = ImVec2(0.0f, 0.0f); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); ScrollbarSizes = ImVec2(0.0f, 0.0f); ScrollbarX = ScrollbarY = false; Active = WasActive = false; WriteAccessed = false; Collapsed = false; WantCollapseToggle = false; SkipItems = false; Appearing = false; Hidden = false; HasCloseButton = false; ResizeBorderHeld = -1; BeginCount = 0; BeginOrderWithinParent = -1; BeginOrderWithinContext = -1; PopupId = 0; AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; AutoFitChildAxises = 0x00; AutoPosLastDirection = ImGuiDir_None; HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; SettingsIdx = -1; DrawList = &DrawListInst; DrawList->_OwnerName = Name; ParentWindow = NULL; RootWindow = NULL; RootWindowForTitleBarHighlight = NULL; RootWindowForNav = NULL; NavLastIds[0] = NavLastIds[1] = 0; NavRectRel[0] = NavRectRel[1] = ImRect(); NavLastChildNavWindow = NULL; } ImGuiWindow::~ImGuiWindow() { IM_ASSERT(DrawList == &DrawListInst); IM_DELETE(Name); for (int i = 0; i != ColumnsStorage.Size; i++) ColumnsStorage[i].~ImGuiColumns(); } 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); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(int n) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashData(&n, sizeof(n), seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); return ImHashStr(str, str_end ? (str_end - str) : 0, seed); } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr) { ImGuiID seed = IDStack.back(); return ImHashData(&ptr, sizeof(void*), seed); } ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n) { ImGuiID seed = IDStack.back(); return ImHashData(&n, sizeof(n), seed); } // This is only used in rare/specific situations to manufacture an ID out of nowhere. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) { ImGuiID seed = IDStack.back(); const 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::SetNavID(ImGuiID id, int nav_layer) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindow); IM_ASSERT(nav_layer == 0 || nav_layer == 1); g.NavId = id; g.NavWindow->NavLastIds[nav_layer] = id; } void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel) { ImGuiContext& g = *GImGui; SetNavID(id, nav_layer); g.NavWindow->NavRectRel[nav_layer] = rect_rel; g.NavMousePosDirty = true; g.NavDisableHighlight = false; g.NavDisableMouseHover = true; } 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.ActiveIdAllowNavDirFlags = 0; g.ActiveIdBlockNavInputFlags = 0; g.ActiveIdAllowOverlap = 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; } } // FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; IM_ASSERT(id != 0); // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it. const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent; if (g.NavWindow != window) g.NavInitRequest = false; g.NavId = id; g.NavWindow = window; g.NavLayer = nav_layer; 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; } void ImGui::ClearActiveID() { SetActiveID(0, NULL); } 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; } // Advance cursor given item size for layout. void ImGui::ItemSize(const ImVec2& size, float text_offset_y) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return; // Always align ourselves on pixel boundaries const float line_height = ImMax(window->DC.CurrLineSize.y, size.y); const float text_base_offset = ImMax(window->DC.CurrLineTextBaseOffset, text_offset_y); //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 = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - 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.PrevLineTextBaseOffset = text_base_offset; window->DC.CurrLineSize.y = window->DC.CurrLineTextBaseOffset = 0.0f; // Horizontal layout mode if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) SameLine(); } void ImGui::ItemSize(const ImRect& bb, float text_offset_y) { ItemSize(bb.GetSize(), text_offset_y); } // Declare item bounding box for clipping and interaction. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface // declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). bool ImGui::ItemAdd(const ImRect& bb, 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 |= window->DC.NavLayerCurrentMask; 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); } 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; } // 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 the dummy item 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 || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) return false; if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) return false; SetHoveredID(id); 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) if (clip_even_when_logged || !g.LogEnabled) return true; return false; } // 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.FocusCounterAll++; if (is_tab_stop) window->DC.FocusCounterTab++; // 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 && !(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_KeyTab_)) && g.FocusRequestNextWindow == NULL) { g.FocusRequestNextWindow = window; g.FocusRequestNextCounterTab = window->DC.FocusCounterTab + (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.FocusCounterAll == g.FocusRequestCurrCounterAll) return true; if (is_tab_stop && window->DC.FocusCounterTab == g.FocusRequestCurrCounterTab) { 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.FocusCounterAll--; window->DC.FocusCounterTab--; } float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) return 0.0f; ImGuiWindow* window = GImGui->CurrentWindow; if (wrap_pos_x == 0.0f) 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() { return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { if (GImGui->IO.SetClipboardTextFn) GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); } const char* ImGui::GetVersion() { return IMGUI_VERSION; } // Internal state access - if you want to share 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 } // 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; } 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); } ImGuiIO& ImGui::GetIO() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); return GImGui->IO; } ImGuiStyle& ImGui::GetStyle() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); return GImGui->Style; } // Same value as passed to the old io.RenderDrawListsFn 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; } static ImDrawList* GetForegroundDrawList(ImGuiWindow*) { // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. return &GImGui->ForegroundDrawList; } 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.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() 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, handle left-click and right-click focus void ImGui::UpdateMouseMovingWindowEndFrame() { // Initiate moving window 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 to focus window and start moving (after we're done with all our widgets) if (g.IO.MouseClicked[0]) { if (g.HoveredRootWindow != NULL) { StartMouseMovingWindow(g.HoveredWindow); if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar)) if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; } else if (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 = false; if (modal == NULL) hovered_window_above_modal = true; for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--) { ImGuiWindow* window = g.Windows[i]; if (window == modal) break; if (window == g.HoveredWindow) hovered_window_above_modal = true; } 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] = -FLT_MAX; // so the third click isn't turned into a double-click } else { g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; g.IO.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; } } void ImGui::UpdateMouseWheel() { ImGuiContext& g = *GImGui; if (!g.HoveredWindow || g.HoveredWindow->Collapsed) return; if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f) 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 && !g.HoveredWindow->Collapsed) { ImGuiWindow* window = g.HoveredWindow; 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 // FIXME: Lock scrolling window while not moving (see #2604) // 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) { ImGuiWindow* window = g.HoveredWindow; 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)); SetWindowScrollY(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) { ImGuiWindow* window = g.HoveredWindow; 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)); SetWindowScrollX(window, window->Scroll.x - wheel_x * scroll_step); } } } // 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. FindHoveredWindow(); // Modal windows prevents cursor from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); if (modal_window) if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) g.HoveredRootWindow = g.HoveredWindow = NULL; // Disabled mouse? if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) g.HoveredWindow = g.HoveredRootWindow = NULL; // 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.empty()); 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) g.HoveredWindow = g.HoveredRootWindow = 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.empty()); // 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; } void ImGui::NewFrame() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); ImGuiContext& g = *GImGui; #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiTestEngineHook_PreNewFrame(&g); #endif // 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.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (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_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)"); // Perform simple 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 recently 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."); // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end 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; // Load settings on first frame (if not explicitly loaded manually before) 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; } } g.Time += g.IO.DeltaTime; g.FrameScopeActive = true; g.FrameCount += 1; g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; // 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.InitialFlags = ImDrawListFlags_None; if (g.Style.AntiAliasedLines) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines; if (g.Style.AntiAliasedFill) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill; if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset; g.BackgroundDrawList.Clear(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); g.ForegroundDrawList.Clear(); 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); // Clear reference to active widget if the widget isn't alive anymore 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; 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.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId) g.TempInputTextId = 0; // Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; g.DragDropAcceptIdCurr = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropWithinSourceOrTarget = false; // Update keyboard input state 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 directional navigation NavUpdate(); // Update mouse input state UpdateMouseInputs(); // 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; // 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(); // 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.FocusRequestNextCounterAll = INT_MAX; if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) g.FocusRequestNextCounterTab = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); else g.FocusRequestNextCounterTab = g.IO.KeyShift ? -1 : 0; } // Turn queued focus request into current one g.FocusRequestCurrWindow = NULL; g.FocusRequestCurrCounterAll = g.FocusRequestCurrCounterTab = INT_MAX; if (g.FocusRequestNextWindow != NULL) { ImGuiWindow* window = g.FocusRequestNextWindow; g.FocusRequestCurrWindow = window; if (g.FocusRequestNextCounterAll != INT_MAX && window->DC.FocusCounterAll != -1) g.FocusRequestCurrCounterAll = ImModPositive(g.FocusRequestNextCounterAll, window->DC.FocusCounterAll + 1); if (g.FocusRequestNextCounterTab != INT_MAX && window->DC.FocusCounterTab != -1) g.FocusRequestCurrCounterTab = ImModPositive(g.FocusRequestNextCounterTab, window->DC.FocusCounterTab + 1); g.FocusRequestNextWindow = NULL; g.FocusRequestNextCounterAll = g.FocusRequestNextCounterTab = INT_MAX; } g.NavIdTabCounter = INT_MAX; // Mark all windows as not visible IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); 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; } // 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); ClosePopupsOverWindow(g.NavWindow, false); // 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. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); g.FrameScopePushedImplicitWindow = true; #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiTestEngineHook_PostNewFrame(&g); #endif } 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.ReadOpenFn = SettingsHandlerWindow_ReadOpen; ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine; ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll; g.SettingsHandlers.push_back(ini_handler); 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(context); SaveIniSettingsToDisk(g.IO.IniFilename); SetCurrentContext(backup_context); } // Clear everything else for (int i = 0; i < g.Windows.Size; i++) IM_DELETE(g.Windows[i]); g.Windows.clear(); g.WindowsFocusOrder.clear(); g.WindowsSortBuffer.clear(); g.CurrentWindow = NULL; g.CurrentWindowStack.clear(); g.WindowsById.Clear(); g.NavWindow = NULL; g.HoveredWindow = g.HoveredRootWindow = NULL; g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; g.MovingWindow = NULL; g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); g.BackgroundDrawList.ClearFreeMemory(); g.ForegroundDrawList.ClearFreeMemory(); g.PrivateClipboard.clear(); g.InputTextState.ClearFreeMemory(); for (int i = 0; i < g.SettingsWindows.Size; i++) IM_DELETE(g.SettingsWindows[i].Name); g.SettingsWindows.clear(); g.SettingsHandlers.clear(); if (g.LogFile && g.LogFile != stdout) { fclose(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) { if (draw_list->CmdBuffer.empty()) return; // Remove trailing command if unused ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) { draw_list->CmdBuffer.pop_back(); if (draw_list->CmdBuffer.empty()) return; } // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. // May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); 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 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 back-end, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'. // Most example back-ends already support this from 1.71. Pre-1.71 back-ends 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-bits indices in your renderer back-end, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h. // Most example back-ends 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; if (window->Flags & ImGuiWindowFlags_Tooltip) AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window); else AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], 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; } } // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); window->ClipRect = window->DrawList->_ClipRectStack.back(); } void ImGui::PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PopClipRect(); window->ClipRect = window->DrawList->_ClipRectStack.back(); } // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. void ImGui::EndFrame() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times. return; IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()?"); // 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; } // 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(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?"); while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING End(); } else { IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?"); } } // Hide implicit/fallback "Debug" window if it hasn't been used g.FrameScopePushedImplicitWindow = false; if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed) g.CurrentWindow->Active = false; End(); // Show CTRL+TAB list window if (g.NavWindowingTarget) NavUpdateWindowingList(); // 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.DragDropWithinSourceOrTarget = true; SetTooltip("..."); g.DragDropWithinSourceOrTarget = false; } // End frame g.FrameScopeActive = 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 childs may not exist yet g.WindowsSortBuffer.resize(0); g.WindowsSortBuffer.reserve(g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it continue; AddWindowToSortBuffer(&g.WindowsSortBuffer, 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.WindowsSortBuffer.Size); g.Windows.swap(g.WindowsSortBuffer); 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)); } void ImGui::Render() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); if (g.FrameCountEnded != g.FrameCount) EndFrame(); g.FrameCountRendered = g.FrameCount; // Gather ImDrawList to render (for each active window) g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0; g.DrawDataBuilder.Clear(); if (!g.BackgroundDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList); 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.NavWindowingList : 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); 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; // (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) g.IO.RenderDrawListsFn(&g.DrawData); #endif } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; if (text == text_display_end) return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Round text_size.x = (float)(int)(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 programatically // 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; 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; // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches. if (hovered_window == NULL) hovered_window = window; if (hovered_window) break; } g.HoveredWindow = hovered_window; g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; } // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { ImGuiContext& g = *GImGui; // 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); return GImGui->IO.KeyMap[imgui_key]; } // Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]! bool ImGui::IsKeyDown(int user_key_index) { if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); return GImGui->IO.KeysDown[user_key_index]; } int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate) { if (t == 0.0f) return 1; if (t <= repeat_delay || repeat_rate <= 0.0f) return 0; const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate); return (count > 0) ? count : 0; } 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 CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, 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(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDown[button]; } 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; } bool ImGui::IsMouseClicked(int button, bool repeat) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) { // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold. int amount = CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.5f); if (amount > 0) return true; } return false; } bool ImGui::IsMouseReleased(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseReleased[button]; } bool ImGui::IsMouseDoubleClicked(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } bool ImGui::IsMouseDragging(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) return false; if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; } ImVec2 ImGui::GetMousePos() { return GImGui->IO.MousePos; } // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.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; } // 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(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { ImGuiContext& g = *GImGui; 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(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; } ImGuiMouseCursor ImGui::GetMouseCursor() { return GImGui->MouseCursor; } void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) { GImGui->MouseCursor = cursor_type; } void ImGui::CaptureKeyboardFromApp(bool capture) { GImGui->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)); } bool ImGui::IsItemFocused() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId) return false; return true; } bool ImGui::IsItemClicked(int mouse_button) { return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None); } 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); } static 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 = 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 a dummy 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(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss 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); } } } // 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(); } // Save and compare stack sizes on Begin()/End() to detect usage errors static void CheckStacksSize(ImGuiWindow* window, bool write) { // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) ImGuiContext& g = *GImGui; short* p_backup = &window->DC.StackSizesBackup[0]; { int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() { int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() { int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them. { int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() { int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() { int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } 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 ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; // 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->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); window->Pos = ImFloor(settings->Pos); window->Collapsed = settings->Collapsed; if (ImLengthSqr(settings->Size) > 0.00001f) size = ImFloor(settings->Size); } window->Size = window->SizeFull = ImFloor(size); 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 CalcSizeAfterConstraint(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 = ImFloor(new_size.x); new_size.y = ImFloor(new_size.y); } // Minimum size if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) { new_size = ImMax(new_size, g.Style.WindowMinSize); new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows } return new_size; } static ImVec2 CalcContentSize(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 = (float)(int)((window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x); sz.y = (float)(int)((window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y); return sz; } static ImVec2 CalcSizeAutoFit(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 = CalcSizeAfterConstraint(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 = CalcContentSize(window); return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents)); } static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) { ImGuiContext& g = *GImGui; ImVec2 scroll = window->Scroll; if (window->ScrollTarget.x < FLT_MAX) { float cr_x = window->ScrollTargetCenterRatio.x; float target_x = window->ScrollTarget.x; if (snap_on_edges && cr_x <= 0.0f && target_x <= window->WindowPadding.x) target_x = 0.0f; else if (snap_on_edges && cr_x >= 1.0f && target_x >= window->ContentSize.x + window->WindowPadding.x + GImGui->Style.ItemSpacing.x) target_x = window->ContentSize.x + window->WindowPadding.x * 2.0f; scroll.x = target_x - cr_x * window->InnerRect.GetWidth(); } if (window->ScrollTarget.y < FLT_MAX) { // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. float cr_y = window->ScrollTargetCenterRatio.y; float target_y = window->ScrollTarget.y; if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) target_y = 0.0f; if (snap_on_edges && cr_y >= 1.0f && target_y >= window->ContentSize.y + window->WindowPadding.y + g.Style.ItemSpacing.y) target_y = window->ContentSize.y + window->WindowPadding.y * 2.0f; scroll.y = target_y - cr_y * window->InnerRect.GetHeight(); } scroll = ImMax(scroll, ImVec2(0.0f, 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; } 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 = CalcSizeAfterConstraint(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 { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right }; 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(); } // Handle resize for: Resize Grips, Borders, Gamepad // Return true when using auto-fit (double click on resize grip) static bool ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; 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 = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); const float grip_hover_inner_size = (float)(int)(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; window->DC.NavLayerCurrentMask = (1 << 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((void*)(intptr_t)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 = CalcSizeAfterConstraint(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 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((void*)(intptr_t)(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 CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } PopID(); // 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)); 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 = CalcSizeAfterConstraint(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); } // Resize nav layer window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->Size = window->SizeFull; return ret_auto_fit; } static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding) { ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size; window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { ImGuiContext& g = *GImGui; float rounding = window->WindowRounding; float border_size = window->WindowBorderSize; 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) { 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 }; 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); } } 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; // 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)); float alpha = 1.0f; if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) alpha = g.NextWindowData.BgAlphaVal; if (alpha != 1.0f) 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); // 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; window->DC.NavLayerCurrentMask = (1 << 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.NavLayerCurrentMask = (1 << 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, (float)(int)(-g.FontSize * 0.25f)); RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r); } } 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.FrameScopeActive); // 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) { ImVec2 size_on_first_use = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. window = CreateNewWindow(name, size_on_first_use, 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); // 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->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)); // 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 = NULL; CheckStacksSize(window, true); 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; // Process SetNextWindow***() calls 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_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) UpdateWindowParentAndRootLinks(window, flags, parent_window); window->Active = true; window->HasCloseButton = (p_open != NULL); window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->IDStack.resize(1); // 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.NavWindowingList != 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 = CalcContentSize(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); } } // 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); 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 = CalcSizeAutoFit(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 = CalcSizeAfterConstraint(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 && !window_pos_set_by_api) 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, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * 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); // 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. ImRect viewport_rect(GetViewportRect()); if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) { if (g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); ClampWindowRect(window, viewport_rect, clamp_padding); } } window->Pos = ImFloor(window->Pos); // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; // 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] = { 0 }; const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4 const float resize_grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); if (!window->Collapsed) if (UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0])) 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 // - NavScrollToBringItemIntoView() // - 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 = (float)(int)(window->Size.x * 0.65f); else window->ItemWidthDefault = (float)(int)(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, true); window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); // DRAWING // Setup draw list and outer clipping rectangle window->DrawList->Clear(); 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; 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; // [LEGACY] Contents Region // FIXME-OBSOLETE: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. // Used by: // - Mouse wheel scrolling + many other things window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height; window->ContentsRegionRect.Max.x = window->ContentsRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x)); window->ContentsRegionRect.Max.y = window->ContentsRegionRect.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.NavHideHighlightOneFrame = false; window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f); window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; window->DC.MenuBarAppending = false; window->DC.ChildWindows.resize(0); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; window->DC.FocusCounterAll = window->DC.FocusCounterTab = -1; window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_; window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.ItemFlagsStack.resize(0); window->DC.ItemWidthStack.resize(0); window->DC.TextWrapPosStack.resize(0); window->DC.CurrentColumns = NULL; window->DC.TreeDepth = 0; window->DC.TreeStoreMayJumpToParentOnPop = 0x00; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags)) { window->DC.ItemFlags = parent_window->DC.ItemFlags; window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); } 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); // 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. window->DC.LastItemId = window->MoveId; window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; window->DC.LastItemRect = 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); } 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) if (first_begin_of_the_frame) window->WriteAccessed = false; window->BeginCount++; g.NextWindowData.ClearFlags(); 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 !skip_items; } // Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags) { // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file. if (size_first_use.x != 0.0f || size_first_use.y != 0.0f) SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver); // Old API feature: override the window background alpha with a parameter. if (bg_alpha_override >= 0.0f) SetNextWindowBgAlpha(bg_alpha_override); return Begin(name, p_open, flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS void ImGui::End() { ImGuiContext& g = *GImGui; if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow) { IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!"); return; // FIXME-ERRORHANDLING } IM_ASSERT(g.CurrentWindowStack.Size > 0); ImGuiWindow* window = g.CurrentWindow; 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(); CheckStacksSize(window, false); 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) 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.NavIdIsAlive = false; g.NavLayer = ImGuiNavLayer_Main; //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL); } // Close popups if any ClosePopupsOverWindow(window, false); // Passing NULL allow to disable keyboard focus if (!window) return; // Move the root window to the top of the pile if (window->RootWindow) window = window->RootWindow; // Steal focus on active widgets if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) ClearActiveID(); // Bring to front BringWindowToFocusFront(window); if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) BringWindowToDisplayFront(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::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 = GImGui->Style; const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); window->DC.ItemWidthStack.push_back(w_item_last); for (int i = 0; i < components-1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); 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 = (float)(int)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; } 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.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) { ImGuiWindow* window = GetCurrentWindow(); if (enabled) window->DC.ItemFlags |= option; else window->DC.ItemFlags &= ~option; window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); } void ImGui::PopItemFlag() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemFlagsStack.pop_back(); window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.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(); } // 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.ColorModifiers.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.ColorModifiers.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColorMod& backup = g.ColorModifiers.back(); g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorModifiers.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.StyleModifiers.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.StyleModifiers.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.StyleModifiers.back(); const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); void* data = info->GetVarPtr(&g.Style); if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } g.StyleModifiers.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"; } 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::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 programmaticaly. // 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::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x) { window->Scroll.x = new_scroll_x; } void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) { window->Scroll.y = new_scroll_y; } 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 = ImFloor(size.x); } else { window->AutoFitFramesX = 2; window->AutoFitOnlyGrows = false; } if (size.y > 0.0f) { window->AutoFitFramesY = 0; window->SizeFull.y = ImFloor(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::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::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; } // FIXME: This is in window space (not screen space!). We should try to obsolete all those functions. ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.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() { ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.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->ContentsRegionRect.Min - window->Pos; } ImVec2 ImGui::GetWindowContentRegionMax() { ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentsRegionRect.Max - window->Pos; } float ImGui::GetWindowContentRegionWidth() { ImGuiWindow* window = GImGui->CurrentWindow; return window->ContentsRegionRect.GetWidth(); } 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; } 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) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = window->Pos - window->Scroll + local_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } ImVec2 ImGui::GetCursorStartPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorStartPos - window->Pos; } ImVec2 ImGui::GetCursorScreenPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos; } void ImGui::SetCursorScreenPos(const ImVec2& pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } 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(float scroll_x) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.x = scroll_x; window->ScrollTargetCenterRatio.x = 0.0f; } void ImGui::SetScrollY(float scroll_y) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.y = scroll_y; window->ScrollTargetCenterRatio.y = 0.0f; } void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f); window->ScrollTarget.x = (float)(int)(local_x + window->Scroll.x); window->ScrollTargetCenterRatio.x = center_x_ratio; } void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); window->ScrollTargetCenterRatio.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) { ImGuiWindow* window = GetCurrentWindow(); float target_x = window->DC.LastItemRect.Min.x - window->Pos.x; // Left of last item, in window space float last_item_width = window->DC.LastItemRect.GetWidth(); target_x += (last_item_width * center_x_ratio) + (GImGui->Style.ItemSpacing.x * (center_x_ratio - 0.5f) * 2.0f); // Precisely aim before, in the middle or after the last item. SetScrollFromPosX(target_x, center_x_ratio); } // 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) { ImGuiWindow* window = GetCurrentWindow(); float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. SetScrollFromPosY(target_y, center_y_ratio); } void ImGui::ActivateItem(ImGuiID id) { ImGuiContext& g = *GImGui; g.NavNextActivateId = id; } 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.FocusRequestNextCounterAll = window->DC.FocusCounterAll + 1 + offset; g.FocusRequestNextCounterTab = 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) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(str_id)); } void ImGui::PushID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end)); } void ImGui::PushID(const void* ptr_id) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id)); } void ImGui::PushID(int int_id) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(int_id)); } // Push a given id value ignoring the ID stack as a seed. void ImGui::PushOverrideID(ImGuiID id) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(id); } void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; 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)); } // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) void ImGui::BeginGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.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 = GetCurrentWindow(); IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); 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) { window->DC.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(), 0.0f); 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 tests not symmetrical 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 && g.ActiveIdPreviousFrameIsAlive; 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; window->DC.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] } // Gets back to previous line and continue with horizontal layout // 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; } 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; } //----------------------------------------------------------------------------- // [SECTION] TOOLTIPS //----------------------------------------------------------------------------- void ImGui::BeginTooltip() { ImGuiContext& g = *GImGui; if (g.DragDropWithinSourceOrTarget) { // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor) // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor. // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do. //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale); 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 :( BeginTooltipEx(0, true); } else { BeginTooltipEx(0, false); } } // Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip) { ImGuiContext& g = *GImGui; char window_name[16]; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount); if (override_previous_tooltip) if (ImGuiWindow* window = 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) { ImGuiContext& g = *GImGui; if (g.DragDropWithinSourceOrTarget) BeginTooltip(); else BeginTooltipEx(0, true); 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 //----------------------------------------------------------------------------- bool ImGui::IsPopupOpen(ImGuiID id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; } bool ImGui::IsPopupOpen(const char* str_id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); } 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) { ImGuiContext& g = *GImGui; OpenPopupEx(g.CurrentWindow->GetID(str_id)); } // Mark popup as open (toggle toward open state). // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) void ImGui::OpenPopupEx(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; int current_stack_size = g.BeginPopupStack.Size; ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; 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("OpenPopupEx(0x%08X)\n", g.FrameCount, 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 g.OpenPopupStack.resize(current_stack_size + 1); g.OpenPopupStack[current_stack_size] = 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); } } bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) OpenPopupEx(id); return true; } return false; } void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.empty()) return; // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. // Don't close our own child popup windows. int 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 when popups are not direct descendant of the reference window (the reference window is often the NavWindow) bool popup_or_descendent_is_ref_window = false; for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++) if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window) if (popup_window->RootWindow == ref_window->RootWindow) popup_or_descendent_is_ref_window = true; if (!popup_or_descendent_is_ref_window) 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("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; IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); 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 == 0 && 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("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; } bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; if (!IsPopupOpen(id)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } char name[20]; if (extra_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 bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup); if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) EndPopup(); 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)) { g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values return false; } // Center modal windows by default // 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_Appearing, ImVec2(0.5f, 0.5f)); flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings; 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; IM_ASSERT(g.CurrentWindow->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. NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY); End(); } // This is a helper to handle the simplest case of associating one named popup to one given widget. // You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // You can pass a NULL str_id to use the identifier of the last item. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; if (window->SkipItems) return false; ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items) { if (!str_id) str_id = "window_context"; ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) { if (!str_id) str_id = "void_context"; ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } // 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; } } // Default popup policy 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; float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); if (avail_w < size.x || avail_h < size.y) 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; *last_dir = dir; return pos; } // Fallback, try to keep within display *last_dir = ImGuiDir_None; 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->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); 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); } 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); } 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. ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); if (window->AutoPosLastDirection == ImGuiDir_None) pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. return pos; } IM_ASSERT(0); return window->Pos; } //----------------------------------------------------------------------------- // [SECTION] KEYBOARD/GAMEPAD NAVIGATION //----------------------------------------------------------------------------- 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 directional navigation. Based on https://gist.github.com/rygorous/6981057 static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavLayer != window->DC.NavLayerCurrent) return false; const ImRect& curr = g.NavScoringRectScreen; // 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.Contains(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 (ImGui::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 = ImGui::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+ImGui::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 (ImGui::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 = ImGui::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 == 1 && !(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; } // 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) { result->ID = id; result->SelectScopeId = g.MultiSelectScopeId; result->Window = window; result->RectRel = nav_bb_rel; } 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)) { result = &g.NavMoveResultLocalVisibleSet; result->ID = id; result->SelectScopeId = g.MultiSelectScopeId; result->Window = window; result->RectRel = 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.NavIdIsAlive = true; g.NavIdTabCounter = window->DC.FocusCounterTab; 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); ImGui::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; if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0) return; IM_ASSERT(move_flags != 0); // No points calling this with no wrapping 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); } } // 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_window = nav_window; while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) parent_window = parent_window->ParentWindow; if (parent_window && parent_window != nav_window) parent_window->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) { return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window; } static void NavRestoreLayer(ImGuiNavLayer layer) { ImGuiContext& g = *GImGui; g.NavLayer = layer; if (layer == 0) g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow); if (layer == 0 && g.NavWindow->NavLastIds[0] != 0) ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]); else ImGui::NavInitWindow(g.NavWindow, 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; if (init_for_nav) { SetNavID(0, g.NavLayer); g.NavInitRequest = true; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; g.NavInitResultRectRel = ImRect(); NavUpdateAnyRequestFlag(); } else { g.NavId = window->NavLastIds[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 back-end 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)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f); if (mode == ImGuiInputReadMode_RepeatSlow) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f); if (mode == ImGuiInputReadMode_RepeatFast) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, 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; } // Scroll to keep newly navigated item fully into view // NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated. static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) { 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] if (window_rect.Contains(item_rect)) return; ImGuiContext& g = *GImGui; if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) { window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x; window->ScrollTargetCenterRatio.x = 0.0f; } else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) { window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x; window->ScrollTargetCenterRatio.x = 1.0f; } if (item_rect.Min.y < window_rect.Min.y) { window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y; window->ScrollTargetCenterRatio.y = 0.0f; } else if (item_rect.Max.y >= window_rect.Max.y) { window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y; window->ScrollTargetCenterRatio.y = 1.0f; } } static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; g.IO.WantSetMousePos = false; #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 before we map Keyboard (some features differs when used with Gamepad vs Keyboard) bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; if (nav_gamepad_active) if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f) g.NavInputSource = ImGuiInputSource_NavGamepad; // Update Keyboard->Nav inputs mapping if (nav_keyboard_active) { #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } 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_ ); NAV_MAP_KEY(ImGuiKey_Tab, ImGuiNavInput_KeyTab_ ); if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu. g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; #undef NAV_MAP_KEY } memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++) g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Process navigation init request (select first/default focus) // 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) if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove) && g.NavWindow) { // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) if (g.NavInitRequestFromMove) SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel); else SetNavID(g.NavInitResultId, g.NavLayer); g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; } 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 ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) { if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow) { g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos(); g.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 == 0) g.NavWindow->NavLastChildNavWindow = NULL; // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.) NavUpdateWindowing(); // Set output flags for user application g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL); // Process NavCancel input (to close a popup, get back to parent, clear focus) if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed)) { if (g.ActiveId != 0) { if (!(g.ActiveIdBlockNavInputFlags & (1 << 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); g.NavIdIsAlive = false; 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 != 0) { // 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 = 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 && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed); if (g.ActiveId == 0 && activate_pressed) g.NavActivateId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down) 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) && IsNavInputPressed(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 const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags; if (g.NavMoveRequestForward == ImGuiNavForward_None) { g.NavMoveDir = ImGuiDir_None; g.NavMoveRequestFlags = ImGuiNavMoveFlags_None; if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) { if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left; if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right; if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up; if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) 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); g.NavMoveRequestForward = ImGuiNavForward_ForwardActive; } // Update PageUp/PageDown scroll float nav_scoring_rect_offset_y = 0.0f; if (nav_keyboard_active) nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags); // 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.NavMoveDirLast = g.NavMoveDir; } if (g.NavMoveRequest && g.NavId == 0) { g.NavInitRequest = g.NavInitRequestFromMove = true; g.NavInitResultId = 0; 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 = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // 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) SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) SetWindowScrollY(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) { SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); g.NavMoveFromClampedRefRect = true; } if (scroll_dir.y != 0.0f) { SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); g.NavMoveFromClampedRefRect = true; } } // Reset search results g.NavMoveResultLocal.Clear(); g.NavMoveResultLocalVisibleSet.Clear(); g.NavMoveResultOther.Clear(); // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0) { 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])) { float pad = window->CalcFontSize() * 0.5f; window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel); g.NavId = 0; } g.NavMoveFromClampedRefRect = false; } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y); g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x); g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x; IM_ASSERT(!g.NavScoringRectScreen.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 } // 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 == 0) { ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); NavScrollToBringItemIntoView(result->Window, rect_abs); // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate() ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false); ImVec2 delta_scroll = result->Window->Scroll - next_scroll; result->RectRel.Translate(delta_scroll); // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy). if (result->Window->Flags & ImGuiWindowFlags_ChildWindow) NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); } 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.NavJustMovedToMultiSelectScopeId = result->SelectScopeId; } SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel); g.NavMoveFromClampedRefRect = false; } static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) { ImGuiContext& g = *GImGui; if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0) { ImGuiWindow* window = g.NavWindow; bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up)); bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down)); if (page_up_held != page_down_held) // 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(g.IO.KeyMap[ImGuiKey_PageUp], true)) SetWindowScrollY(window, window->Scroll.y - window->InnerRect.GetHeight()); else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) SetWindowScrollY(window, window->Scroll.y + window->InnerRect.GetHeight()); } else { const 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(g.IO.KeyMap[ImGuiKey_PageUp], true)) { nav_scoring_rect_offset_y = -page_offset_y; g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Up; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) { nav_scoring_rect_offset_y = +page_offset_y; g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Down; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } return nav_scoring_rect_offset_y; } } } return 0.0f; } 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(); if (modal_window != NULL) { g.NavWindowingTarget = NULL; return; } // 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 = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard); 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; 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)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(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 back-end clearing releases all keys on ALT-TAB if (IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed)) g.NavWindowingToggleLayer = true; if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputPressed(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 code variable framerate very well SetWindowPos(g.NavWindowingTarget->RootWindow, g.NavWindowingTarget->RootWindow->Pos + move_delta * move_speed, ImGuiCond_Always); g.NavDisableMouseHover = true; MarkIniSettingsDirty(g.NavWindowingTarget); } } // 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::NavUpdateWindowingList() { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindowingTarget != NULL); if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) return; if (g.NavWindowingList == NULL) g.NavWindowingList = 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] COLUMNS // In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. //----------------------------------------------------------------------------- void ImGui::NextColumn() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems || window->DC.CurrentColumns == NULL) return; ImGuiContext& g = *GImGui; ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) { window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); IM_ASSERT(columns->Current == 0); return; } PopItemWidth(); PopClipRect(); columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); if (++columns->Current < columns->Count) { // Columns 1+ cancel out IndentX // FIXME-COLUMNS: Unnecessary, could be locked? window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; window->DrawList->ChannelsSetCurrent(columns->Current + 1); } else { // New row/line window->DC.ColumnsOffset.x = 0.0f; window->DrawList->ChannelsSetCurrent(1); columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->DC.CursorPos.y = columns->LineMinY; window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrLineTextBaseOffset = 0.0f; PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite? // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. float offset_0 = GetColumnOffset(columns->Current); float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; } int ImGui::GetColumnIndex() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; } int ImGui::GetColumnsCount() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; } static float OffsetNormToPixels(const ImGuiColumns* columns, float offset_norm) { return offset_norm * (columns->OffMaxX - columns->OffMinX); } static float PixelsToOffsetNorm(const ImGuiColumns* columns, float offset) { return offset / (columns->OffMaxX - columns->OffMinX); } static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); return x; } float ImGui::GetColumnOffset(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); const float t = columns->Columns[column_index].OffsetNorm; const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); return x_offset; } static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false) { if (column_index < 0) column_index = columns->Current; float offset_norm; if (before_resize) offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; else offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; return OffsetNormToPixels(columns, offset_norm); } float ImGui::GetColumnWidth(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); } void ImGui::SetColumnOffset(int column_index, float offset) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1); const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->OffMinX); if (preserve_width) SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); } void ImGui::SetColumnWidth(int column_index, float width) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); } void ImGui::PushColumnClipRect(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; if (column_index < 0) column_index = columns->Current; ImGuiColumnData* column = &columns->Columns[column_index]; PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); } // Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) void ImGui::PushColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; window->DrawList->ChannelsSetCurrent(0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); IM_UNUSED(cmd_size); IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } void ImGui::PopColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; window->DrawList->ChannelsSetCurrent(columns->Current + 1); PopClipRect(); } ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) { // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. for (int n = 0; n < window->ColumnsStorage.Size; n++) if (window->ColumnsStorage[n].ID == id) return &window->ColumnsStorage[n]; window->ColumnsStorage.push_back(ImGuiColumns()); ImGuiColumns* columns = &window->ColumnsStorage.back(); columns->ID = id; return columns; } ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) { ImGuiWindow* window = GetCurrentWindow(); // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. PushID(0x11223347 + (str_id ? 0 : columns_count)); ImGuiID id = window->GetID(str_id ? str_id : "columns"); PopID(); return id; } void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported // Acquire storage for the columns set ImGuiID id = GetColumnsID(str_id, columns_count); ImGuiColumns* columns = FindOrCreateColumns(window, id); IM_ASSERT(columns->ID == id); columns->Current = 0; columns->Count = columns_count; columns->Flags = flags; window->DC.CurrentColumns = columns; // Set state for first column columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; columns->OffMaxX = ImMax(window->WorkRect.Max.x - window->Pos.x, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostClipRect = window->ClipRect; columns->HostWorkRect = window->WorkRect; columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Clear data if columns count changed if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) columns->Columns.resize(0); // Initialize default widths columns->IsFirstFrame = (columns->Columns.Size == 0); if (columns->Columns.Size == 0) { columns->Columns.reserve(columns_count + 1); for (int n = 0; n < columns_count + 1; n++) { ImGuiColumnData column; column.OffsetNorm = n / (float)columns_count; columns->Columns.push_back(column); } } for (int n = 0; n < columns_count; n++) { // Compute clipping rectangle ImGuiColumnData* column = &columns->Columns[n]; float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n)); float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); column->ClipRect.ClipWith(window->ClipRect); } if (columns->Count > 1) { window->DrawList->ChannelsSplit(1 + columns->Count); window->DrawList->ChannelsSetCurrent(1); PushColumnClipRect(0); } float offset_0 = GetColumnOffset(columns->Current); float offset_1 = GetColumnOffset(columns->Current + 1); float width = offset_1 - offset_0; PushItemWidth(width * 0.65f); window->WorkRect.Max.x = window->Pos.x + offset_1 - window->WindowPadding.x; } void ImGui::EndColumns() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); PopItemWidth(); if (columns->Count > 1) { PopClipRect(); window->DrawList->ChannelsMerge(); } const ImGuiColumnsFlags flags = columns->Flags; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = columns->LineMaxY; if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize)) window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent // Draw columns borders and handle resize // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy bool is_being_resized = false; if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) { // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); int dragging_column = -1; for (int n = 1; n < columns->Count; n++) { ImGuiColumnData* column = &columns->Columns[n]; float x = window->Pos.x + GetColumnOffset(n); const ImGuiID column_id = columns->ID + ImGuiID(n); const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); KeepAliveID(column_id); if (IsClippedEx(column_hit_rect, column_id, false)) continue; bool hovered = false, held = false; if (!(flags & ImGuiColumnsFlags_NoResize)) { ButtonBehavior(column_hit_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; if (held && !(column->Flags & ImGuiColumnsFlags_NoResize)) dragging_column = n; } // Draw column const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); const float xi = (float)(int)x; window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); } // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. if (dragging_column != -1) { if (!columns->IsBeingResized) for (int n = 0; n < columns->Count + 1; n++) columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; columns->IsBeingResized = is_being_resized = true; float x = GetDraggedColumnOffset(columns, dragging_column); SetColumnOffset(dragging_column, x); } } columns->IsBeingResized = is_being_resized; window->WorkRect = columns->HostWorkRect; window->DC.CurrentColumns = NULL; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); } // [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] void ImGui::Columns(int columns_count, const char* id, bool border) { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior ImGuiColumns* columns = window->DC.CurrentColumns; if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) return; if (columns != NULL) EndColumns(); if (columns_count != 1) BeginColumns(id, columns_count, flags); } //----------------------------------------------------------------------------- // [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; int mouse_button = 0; 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); } 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; } g.DragDropSourceFrameCount = g.FrameCount; g.DragDropWithinSourceOrTarget = 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.DragDropWithinSourceOrTarget && "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.DragDropWithinSourceOrTarget = 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; if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->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.DragDropWithinSourceOrTarget == false); g.DragDropTargetRect = bb; g.DragDropTargetId = id; g.DragDropWithinSourceOrTarget = 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; if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->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.DragDropWithinSourceOrTarget == false); g.DragDropTargetRect = display_rect; g.DragDropTargetId = id; g.DragDropWithinSourceOrTarget = 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.DragDropWithinSourceOrTarget); g.DragDropWithinSourceOrTarget = 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) vfprintf(g.LogFile, fmt, args); 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; LogBegin(ImGuiLogType_TTY, auto_open_depth); g.LogFile = stdout; } // 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; FILE* f = ImFileOpen(filename, "ab"); if (f == NULL) { 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: fflush(g.LogFile); break; case ImGuiLogType_File: fclose(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"); const bool log_to_tty = Button("Log To TTY"); SameLine(); const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); 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 //----------------------------------------------------------------------------- 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; g.SettingsWindows.push_back(ImGuiWindowSettings()); ImGuiWindowSettings* settings = &g.SettingsWindows.back(); settings->Name = ImStrdup(name); settings->ID = ImHashStr(name); return settings; } ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) { ImGuiContext& g = *GImGui; for (int i = 0; i != g.SettingsWindows.Size; i++) if (g.SettingsWindows[i].ID == id) return &g.SettingsWindows[i]; return NULL; } ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) { if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name))) return settings; return CreateNewWindowSettings(name); } 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); } 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; } // 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.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); char* buf = (char*)IM_ALLOC(ini_size + 1); char* buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); buf[ini_size] = 0; 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*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; if (!type_end || !name_start) { name_start = type_start; // Import legacy entries that have no type type_start = "Window"; } else { *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); } } IM_FREE(buf); g.SettingsLoaded = true; } 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); FILE* f = ImFileOpen(ini_filename, "wt"); if (!f) return; fwrite(ini_data, sizeof(char), ini_data_size, f); fclose(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* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); if (!settings) settings = ImGui::CreateNewWindowSettings(name); return (void*)settings; } static void SettingsHandlerWindow_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void* entry, const char* line) { ImGuiContext& g = *ctx; ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; float x, y; int i; if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } static void SettingsHandlerWindow_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->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID); if (!settings) { settings = ImGui::CreateNewWindowSettings(window->Name); window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); } IM_ASSERT(settings->ID == window->ID); settings->Pos = window->Pos; settings->Size = window->SizeFull; settings->Collapsed = window->Collapsed; } // Write to text buffer buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve for (int i = 0; i != g.SettingsWindows.Size; i++) { const ImGuiWindowSettings* settings = &g.SettingsWindows[i]; if (settings->Pos.x == FLT_MAX) continue; const char* name = settings->Name; if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() name = p; buf->appendf("[%s][%s]\n", handler->TypeName, name); buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); buf->appendf("Collapsed=%d\n", settings->Collapsed); buf->appendf("\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(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef __MINGW32__ #include <Windows.h> #else #include <windows.h> #endif #elif defined(__APPLE__) #include <TargetConditionals.h> #endif #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) #ifdef _MSC_VER #pragma comment(lib, "user32") #endif // Win32 clipboard implementation static const char* GetClipboardTextFn_DefaultImpl(void*) { static ImVector<char> buf_local; buf_local.clear(); if (!::OpenClipboard(NULL)) return NULL; HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) { ::CloseClipboard(); return NULL; } if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle)) { int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; buf_local.resize(buf_len); ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); } ::GlobalUnlock(wbuf_handle); ::CloseClipboard(); return buf_local.Data; } static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!::OpenClipboard(NULL)) return; const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); if (wbuf_handle == NULL) { ::CloseClipboard(); return; } ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle); ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); ::GlobalUnlock(wbuf_handle); ::EmptyClipboard(); if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL) ::GlobalFree(wbuf_handle); ::CloseClipboard(); } #elif defined(__APPLE__) && TARGET_OS_OSX && !defined(IMGUI_DISABLE_OSX_FUNCTIONS) #include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file static PasteboardRef main_clipboard = 0; // OSX clipboard implementation 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 (int 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) { static ImVector<char> clipboard_text; int length = (int)CFDataGetLength(cf_data); clipboard_text.resize(length + 1); CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)clipboard_text.Data); clipboard_text[length] = 0; CFRelease(cf_data); return clipboard_text.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.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin(); } static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { ImGuiContext& g = *GImGui; g.PrivateClipboard.clear(); const char* text_end = text + strlen(text); g.PrivateClipboard.resize((int)(text_end - text) + 1); memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text)); g.PrivateClipboard[(int)(text_end - text)] = 0; } #endif // Win32 API IME support (for Asian languages, etc.) #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_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 if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) if (HIMC himc = ::ImmGetContext(hwnd)) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = x; cf.ptCurrentPos.y = y; cf.dwStyle = CFS_FORCE_POSITION; ::ImmSetCompositionWindow(himc, &cf); ::ImmReleaseContext(hwnd, himc); } } #else static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} #endif //----------------------------------------------------------------------------- // [SECTION] METRICS/DEBUG WINDOW //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_METRICS_WINDOW void ImGui::ShowMetricsWindow(bool* p_open) { if (!ImGui::Begin("Dear ImGui Metrics", p_open)) { ImGui::End(); return; } enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Contents, WRT_ContentsRegionRect, WRT_Count }; // Windows Rect Type const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Contents", "ContentsRegionRect" }; static bool show_windows_begin_order = false; static bool show_windows_rects = false; static int show_windows_rect_type = WRT_WorkRect; static bool show_drawcmd_clip_rects = true; ImGuiIO& io = ImGui::GetIO(); ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows); ImGui::Text("%d active allocations", io.MetricsActiveAllocations); ImGui::Separator(); 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_Contents) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); } else if (rect_type == WRT_ContentsRegionRect) { return window->ContentsRegionRect; } IM_ASSERT(0); return ImRect(); } static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label) { bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); ImGui::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) ImGui::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; int elem_offset = 0; for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) { if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0) continue; if (pcmd->UserCallback) { ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); continue; } ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; char buf[300]; ImFormatString(buf, IM_ARRAYSIZE(buf), "Draw %4d triangles, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount/3, (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered()) { ImRect clip_rect = pcmd->ClipRect; ImRect vtxs_rect; for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,0,255,255)); vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,255,0,255)); } if (!pcmd_node_open) continue; // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. ImGui::Text("ElemCount: %d, ElemCount/3: %d, VtxOffset: +%d, IdxOffset: +%d", pcmd->ElemCount, pcmd->ElemCount/3, pcmd->VtxOffset, pcmd->IdxOffset); ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) { char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangles_pos[3]; for (int n = 0; n < 3; n++, idx_i++) { int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i; ImDrawVert& v = draw_list->VtxBuffer[vtx_i]; triangles_pos[n] = v.pos; buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "elem" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); } ImGui::Selectable(buf, false); if (fg_draw_list && ImGui::IsItemHovered()) { ImDrawListFlags backup_flags = fg_draw_list->Flags; fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles. fg_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f); fg_draw_list->Flags = backup_flags; } } ImGui::TreePop(); } ImGui::TreePop(); } static void NodeColumns(const ImGuiColumns* columns) { if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) return; ImGui::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++) ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm)); ImGui::TreePop(); } static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label) { if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) return; for (int i = 0; i < windows.Size; i++) Funcs::NodeWindow(windows[i], "Window"); ImGui::TreePop(); } static void NodeWindow(ImGuiWindow* window, const char* label) { if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) return; ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->DrawList, "DrawList"); ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y); ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, (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" : ""); ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y); ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); if (!window->NavRectRel[0].IsInverted()) ImGui::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 ImGui::BulletText("NavRectRel[0]: <None>"); if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow"); if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) { for (int n = 0; n < window->ColumnsStorage.Size; n++) NodeColumns(&window->ColumnsStorage[n]); ImGui::TreePop(); } ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); ImGui::TreePop(); } static void NodeTabBar(ImGuiTabBar* tab_bar) { // 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); ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : ""); if (ImGui::TreeNode(tab_bar, "%s", buf)) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; ImGui::PushID(tab); if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine(); ImGui::Text("%02d%c Tab 0x%08X", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID); ImGui::PopID(); } ImGui::TreePop(); } } }; // Access private state, we are going to display the draw lists from last frame ImGuiContext& g = *GImGui; Funcs::NodeWindows(g.Windows, "Windows"); if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) { for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++) Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList"); ImGui::TreePop(); } if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) { for (int i = 0; i < g.OpenPopupStack.Size; i++) { ImGuiWindow* window = g.OpenPopupStack[i].Window; ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); } ImGui::TreePop(); } if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size)) { for (int n = 0; n < g.TabBars.Data.Size; n++) Funcs::NodeTabBar(g.TabBars.GetByIndex(n)); ImGui::TreePop(); } if (ImGui::TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredId: 0x%08X/0x%08X (%.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 ImGui::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]); ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]); ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); ImGui::TreePop(); } if (ImGui::TreeNode("Tools")) { ImGui::Checkbox("Show windows begin order", &show_windows_begin_order); ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); show_windows_rects |= ImGui::Combo("##show_windows_rect_type", &show_windows_rect_type, wrt_rects_names, WRT_Count); if (show_windows_rects && g.NavWindow) { ImGui::BulletText("'%s':", g.NavWindow->Name); ImGui::Indent(); for (int rect_n = 0; rect_n < WRT_Count; rect_n++) { ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n); ImGui::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]); } ImGui::Unindent(); } ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects); ImGui::TreePop(); } if (show_windows_rects || show_windows_begin_order) { for (int n = 0; n < g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; if (!window->WasActive) continue; ImDrawList* draw_list = GetForegroundDrawList(window); if (show_windows_rects) { ImRect r = Funcs::GetWindowRect(window, show_windows_rect_type); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow)) { char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); float font_size = ImGui::GetFontSize(); draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf); } } } ImGui::End(); } #else void ImGui::ShowMetricsWindow(bool*) { } #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 //-----------------------------------------------------------------------------
[ "james98g@gmail.com" ]
james98g@gmail.com
80c3a17bdb01e7ea9aceac87452548b3c36359d7
894fb719f593632ad8c6ebcca0a49dd590e3810e
/comp/forgon.cpp
7689f03b353b914e6db1a63719197b4902df2be3
[]
no_license
Jayfaldu/CP
fa12dab444984af41142a50faeb13dbbf36213e5
230a557c412bb82cfbbf2143dfd6d92968713695
refs/heads/master
2020-07-10T00:06:05.036375
2019-08-24T05:52:20
2019-08-24T05:52:20
204,114,930
2
0
null
null
null
null
UTF-8
C++
false
false
730
cpp
#include<stdio.h> int main(){ int test; scanf("%d",&test); getchar(); for(int i=0;i<test;i++){ char s[99]; int j=0; char c=getchar(); while(c!='\n'){ s[j++]=c; c=getchar(); } char s1[99]; char s2[99]; //printf("%c \n",s[0]); for(int k=0;k<j;k++){ if(s[k]=='4'){ s1[k]=s[k]-1; } else{ s1[k]=s[k]; } s2[k]=s[k]-s1[k]+'0'; } //printf("%c he\n",s2[0]); s1[j]='\0'; s2[j]='\0'; printf("Case #%d: ",i+1); for(int k=0;k<j;k++){ printf("%c",s1[k]); } printf(" "); int k=0; while(s2[k]=='0'){ k++; } while(k<j){ printf("%c",s2[k++]); } printf("\n"); } }
[ "jdf.181co101@gmail.com" ]
jdf.181co101@gmail.com
88edd1071b572a19495ef90a1e91ebe5798ff4af
998b3d23f59b22255e232272d4796ef3e78cd11a
/include/load_ascii_20190205.h
a2cd7b88acba544bc22ed2522940a311934c5abe
[]
no_license
netxpto/QuantumMiningSMC
cc0ac6a9fe6471948762a1517c296a609a6e1254
95f8f042a378776299ac4a89d74f9a60f33ed66d
refs/heads/master
2020-04-29T23:29:50.404948
2019-03-19T09:44:33
2019-03-19T09:44:33
176,478,347
1
0
null
null
null
null
UTF-8
C++
false
false
1,414
h
# ifndef PROGRAM_LOAD_ASCII_H_ # define PROGRAM_LOAD_ASCII_H_ # include "netxpto_20180815.h" // Simulates a simple adding block enum class delimiter_type {CommaSeperatedValues, ConcatenatedValues}; class LoadAscii : public Block { public: LoadAscii(initializer_list<Signal *> InputSig, initializer_list<Signal *> OutputSig) :Block(InputSig, OutputSig) {}; void initialize(void); bool runBlock(void); void setSamplingPeriod(double sPeriod) { samplingPeriod = sPeriod; }; double const getSamplingPeriod(void) { return samplingPeriod; }; void setSymbolPeriod(double sPeriod) { symbolPeriod = sPeriod; }; double const getSymbolPeriod(void) { return symbolPeriod; }; void setDataType(signal_value_type dType) { dataType = dType; }; signal_value_type const getDataType(void) { return dataType; }; void setDelimiterType(delimiter_type delType) { delimiterType = delType; }; delimiter_type const getDelimiterType(void) { return delimiterType; }; void setAsciiFileName(string aFileName) { asciiFileName = aFileName; }; string const getAsciiFileName(void) { return asciiFileName; }; private: bool firstTime{ true }; int sizeOfFile{ 0 }; int ready{ 0 }; double samplingPeriod{ 1 }; double symbolPeriod{ 1 }; signal_value_type dataType{ signal_value_type::t_binary }; delimiter_type delimiterType{ delimiter_type::ConcatenatedValues }; string asciiFileName{ "InputFile.txt" }; }; # endif
[ "netxpto@gmail.com" ]
netxpto@gmail.com
42e5320e19fc877193da5d360810aaf05f2733f6
c1eb02f93814deb90d9cb2bd22cefbbd26755844
/WebinarWinAPI/Role.h
827b8d084e53f050b8c794daddcc6fae7ac67d3c
[]
no_license
Ajololr/Webinar-Win-API
7aef8db9f7398c6a8383e524b15d10facccab86e
97e482e3ac9ebcd293e2884f60caf8afb1b7396d
refs/heads/master
2023-02-03T19:57:54.576477
2020-12-21T11:45:35
2020-12-21T11:45:35
321,955,989
1
0
null
null
null
null
UTF-8
C++
false
false
118
h
#pragma once #include <string> enum Role { TEACHER, STUDENT }; extern Role userRole; extern std::string userName;
[ "ilya_androsov@icloud.com" ]
ilya_androsov@icloud.com
649d1f9311f0f3460474e676aa00a579604f8e2e
d66f95e3cbb7030b5c5b476a0cc50ac126ff64ad
/practice/week-01/dllist/dllist.cpp
ea16eca545d0ccb760e05c99cc07c3b94f16d941
[]
no_license
ceko98/sdp-kn-group2-2020
8f9d5de40668563440ffa22956bd1ec138b66b52
30e8007381d0c2051629c31f0f52dffa924764ad
refs/heads/main
2023-02-21T02:37:17.722468
2021-01-21T11:20:37
2021-01-21T11:20:37
302,458,162
1
0
null
null
null
null
UTF-8
C++
false
false
2,314
cpp
#ifndef __DLLIST_CPP #define __DLLIST_CPP #include "dllist.h" #include <iostream> template<class T> DLList<T>::DLList():first(nullptr) { } template<class T> DLList<T>::DLList(const DLList<T> &other) { copy(other); } template<class T> DLList<T>::~DLList() { clear(); } template<class T> void DLList<T>::clear() { DLList<T>::box *crr = first, *save; while (crr != nullptr) { save = crr; crr = crr->next; delete save; } } template<class T> DLList<T>& DLList<T>::operator= (const DLList<T> &other) { if (this != &other) { clear(); copy(other); } return *this; } template<class T> DLList<T> DLList<T>::operator+ (const T &x) const { DLList<T> result(*this); result += x; return result; } template<class T> DLList<T>& DLList<T>::operator+= (const T &x) { first = new DLList<T>::box {x,first,nullptr}; if (first->next != nullptr) { first->next->prev = first; } return *this; } template<class T> void DLList<T>::copy(const DLList<T> &other) { //ЗА ДОМАШНО!!! } template<class T> std::ostream& operator<< (std::ostream &out,const DLList<T> &list) { typename DLList<T>::box *crr = list.first; while (crr != nullptr) { out << crr->data << " "; crr=crr->next; } return out; } // problem 1 solution template<class T> int DLList<T>::length() { if (this->first == nullptr) { return 0; } int count = 0; DLList<T>::box *crr = this->first; while (crr != nullptr) { crr = crr->next; count++; } return count; } // problem 2 solution template<class T> void DLList<T>::insertAt(T value, int position) { if (this->first == nullptr) { this->first = new DLList<T>::box(); this->first->data = value; this->first->next = nullptr; this->first->prev = nullptr; } DLList<T>::box *crr = this->first; while (crr != nullptr && position != 0) { crr = crr->next; position--; } DLList<T>::box *tmp = crr->prev; DLList<T>::box *newBox = new DLList<T>::box(); newBox->data = value; // position = 0 // crr == first crr->prev = newBox; newBox->next = crr; newBox->prev = tmp; if (tmp != nullptr) { tmp->next = newBox; } if (crr == first) { first = first->prev; } } #endif
[ "ceko8998@gmail.com" ]
ceko8998@gmail.com
5e6849109de2f2ae8c8a114d3d404cdff293e967
ee01cd68cc9f393a219a2592594beb97bd3d7e99
/taller2_conjunto_sobre_abb/src/Conjunto.hpp
bf951d742dcd696f20b1f577cce2c791c44cdb6d
[]
no_license
mmaximiliano/algo2-talleres
41bf131c27b6fa8add5542803cdd20cff5405c92
3a4c9ead4e4e50484de69b0ffa580e5bd44c2d73
refs/heads/master
2020-05-07T09:08:59.274669
2019-04-09T12:52:20
2019-04-09T12:52:20
180,364,133
0
0
null
null
null
null
UTF-8
C++
false
false
5,927
hpp
template <class T> Conjunto<T>::Conjunto() { _raiz = NULL; } template <class T> Conjunto<T>::~Conjunto() { borrar(_raiz); } template <class T> void Conjunto<T>::borrar(Nodo* p) { if(p == NULL){ //caso base }else{ borrar(p->izq); borrar(p->der); delete p; } } template <class T> bool Conjunto<T>::pertenece(const T& clave) const { Nodo* p = _raiz; bool encontramos = false; while(p!=NULL && !encontramos){ if(p!=NULL && p->valor == clave){ encontramos = true; } if(p->valor < clave){ p = p->der; } else{ p = p->izq; } } return encontramos; } template <class T> void Conjunto<T>::insertar(const T& clave) { Nodo* nuevo = new Nodo(clave); if(_raiz == NULL){ _raiz = nuevo; } else{ if(!(pertenece(clave))){ Nodo* p = _raiz; Nodo* padre = NULL; while(p!=NULL){ padre = p; if(p->valor < clave){ p = p->der; } else{ p = p->izq; } } if(padre->valor > clave){ padre->izq = nuevo; } else{ padre->der = nuevo; } } else{ delete nuevo; } } } template <class T> typename Conjunto<T>::Nodo* Conjunto<T>::buscar(const T& clave) { Nodo *p = _raiz; while (p->valor != clave) { if (p->valor < clave) { p = p->der; } else { p = p->izq; } } return p; } template <class T> void Conjunto<T>::remover(const T& clave) { if(pertenece(clave)){ Nodo *padre = NULL; Nodo *p = _raiz; while (p->valor != clave) { padre = p; if (p->valor < clave) { p = p->der; } else { p = p->izq; } } if (p == _raiz ){ //Caso soy raiz if(p->izq == NULL && p->der==NULL) { // No tengo hijos _raiz = NULL; } else if(p->izq != NULL xor p->der !=NULL) { // Tengo un hijo if(p->der != NULL){ _raiz = p->der; } else { _raiz = p->izq; } } else { // Tengo dos hijos _raiz = p->der; Nodo* minDerecha = p->der; while (minDerecha->izq!=NULL){ minDerecha = minDerecha->izq; } minDerecha->izq = p->izq; } }else if(p->izq == NULL && p->der==NULL) { // Caso sin hijos. if (padre->valor < p->valor) { padre->der = NULL; } else { padre->izq = NULL; } } else if(p->izq != NULL xor p->der !=NULL){ // Caso un solo hijo. if(p->der != NULL){ if (padre->valor < p->valor) { padre->der = p->der; } else { padre->izq = p->der; } } else{ // Caso dos hijos if (padre->valor < p->valor) { padre->der = p->izq; } else { padre->izq = p->izq; } } } else if (p->der != NULL && p->izq != NULL && p != _raiz) { // Caso dos hijos y no soy raiz. if (padre->valor < p->valor) { padre->der = p->der; } else { padre->izq = p->der; } Nodo* minDerecha = p->der; while (minDerecha->izq!=NULL){ minDerecha = minDerecha->izq; } minDerecha->izq = p->izq; } delete p; } else { //NADA. } } template <class T> const T& Conjunto<T>::siguiente(const T& clave) { bool encontramos = false; Nodo *p = _raiz; Nodo *padre = p; stack<Nodo*> pila; while (!encontramos && p != NULL) { if (p->valor == clave) { encontramos = true; } else { padre = p; pila.push(padre); if (p->valor < clave) { p = p->der; } else { p = p->izq; } } } // Caso A if (p->der != NULL) { p = p->der; while (p->izq != NULL) { p = p->izq; } }else{ // Caso B1 if ((padre->izq)->valor = p->valor){ p = padre; }else{ // Caso B2 while(!(((pila.top())->izq)->valor = p->valor)){ p = pila.top(); pila.pop(); } } } return p->valor; } template <class T> const T& Conjunto<T>::minimo() const { Nodo* p = _raiz; while((p->izq) != NULL){ p = p->izq; } return p->valor; //assert(false); } template <class T> const T& Conjunto<T>::maximo() const { Nodo *p = _raiz; while((p->der) != NULL){ p = p->der; } return p->valor; //assert(false); } template <class T> unsigned int Conjunto<T>::cardinal() const { //assert(false); int cant = cardAux(_raiz); return cant; } template <class T> int Conjunto<T>::cardAux(Nodo* p) const{ int cant = 0; if(p != NULL){ cant = 1 + cardAux(p->izq) + cardAux(p->der); } return cant; } template <class T> void Conjunto<T>::mostrar(std::ostream&) const { assert(false); } template <class T> const T& Conjunto<T>::minimoSubArbol(Nodo* raiz) const { return minimo(); }
[ "31483803+mmaximiliano@users.noreply.github.com" ]
31483803+mmaximiliano@users.noreply.github.com
97d7e36b308a5c1a7248cb93cf3d4cefd5eaa0ee
c4aa092e45dc943ed3932a796a0870ce84714500
/SpyFindWindow/WndFinder.cpp
06912e6245253289de0719d4796c5444e7257016
[]
no_license
15831944/DevTools
d07897dd7a36afa6d287cac72a54589da15f968d
50723004dc9c705e8f095d6f503beeb4096e4987
refs/heads/master
2022-11-21T05:41:56.927474
2020-07-24T12:30:59
2020-07-24T12:30:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,360
cpp
#include "stdafx.h" #include "WndFinder.h" #include "Application.h" #include "utl/UI/Utilities.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CWndFinder::CWndFinder( void ) : m_appProcessId( 0 ) { ASSERT( IsWindow( AfxGetMainWnd()->GetSafeHwnd() ) ); ::GetWindowThreadProcessId( AfxGetMainWnd()->GetSafeHwnd(), &m_appProcessId ); ASSERT( m_appProcessId != 0 ); } bool CWndFinder::IsValidMatch( HWND hWnd ) const { // ignore windows belonging to this app's process if ( hWnd != NULL && IsWindow( hWnd ) ) { DWORD processId = 0; ::GetWindowThreadProcessId( hWnd, &processId ); if ( processId != m_appProcessId ) return true; } return false; } CWndSpot CWndFinder::WindowFromPoint( const CPoint& screenPos ) const { CWndSpot wndSpot( ::WindowFromPoint( screenPos ), screenPos ); if ( !wndSpot.IsValid() || !IsValidMatch( wndSpot.m_hWnd ) ) return CWndSpot( NULL, screenPos ); HWND hParentWnd = ::GetParent( wndSpot.m_hWnd ); CRect hitRect = wndSpot.GetWindowRect(); if ( wndSpot.IsChildWindow() ) { // search again for child windows (more accurate) CPoint clientPoint = screenPos; ::ScreenToClient( hParentWnd, &clientPoint ); int cwpFlags = CWP_ALL; if ( app::GetOptions()->m_ignoreHidden ) cwpFlags |= CWP_SKIPINVISIBLE; if ( app::GetOptions()->m_ignoreDisabled ) cwpFlags |= CWP_SKIPDISABLED; wndSpot.m_hWnd = ::ChildWindowFromPointEx( hParentWnd, clientPoint, cwpFlags ); ASSERT_PTR( wndSpot.m_hWnd ); hitRect = wndSpot.GetWindowRect(); wndSpot.m_hWnd = FindBestFitSibling( wndSpot.m_hWnd, hitRect, screenPos ); } ASSERT( wndSpot.IsValid() ); if ( HWND hChild = FindChildWindow( wndSpot.m_hWnd, hitRect, screenPos ) ) wndSpot.m_hWnd = hChild; return wndSpot; } HWND CWndFinder::FindBestFitSibling( HWND hWnd, const CRect& hitRect, const CPoint& screenPos ) const { ASSERT_PTR( hWnd ); bool foundAny = false; for ( HWND hSibling = ::GetWindow( hWnd, GW_HWNDFIRST ); hSibling != NULL; hSibling = ::GetWindow( hSibling, GW_HWNDNEXT ) ) if ( ContainsPoint( hSibling, screenPos ) ) { CRect siblingRect; ::GetWindowRect( hSibling, &siblingRect ); if ( ( siblingRect & hitRect ) == siblingRect ) { CRect windowRect; ::GetWindowRect( hWnd, &windowRect ); if ( !foundAny || GetRectArea( siblingRect ) < GetRectArea( windowRect ) ) { hWnd = hSibling; foundAny = true; } } } return hWnd; } HWND CWndFinder::FindChildWindow( HWND hWndParent, const CRect& hitRect, const CPoint& screenPos ) const { if ( HWND hChild = ::GetWindow( hWndParent, GW_CHILD ) ) { hChild = FindBestFitSibling( hChild, hitRect, screenPos ); if ( hChild != NULL ) if ( ContainsPoint( hChild, screenPos ) ) return hChild; } return hWndParent; } bool CWndFinder::ContainsPoint( HWND hWnd, const CPoint& screenPos ) const { ASSERT_PTR( hWnd ); if ( app::GetOptions()->m_ignoreDisabled && !::IsWindowEnabled( hWnd ) ) return false; if ( app::GetOptions()->m_ignoreHidden && !::IsWindowVisible( hWnd ) ) return false; else if ( !app::GetOptions()->m_ignoreHidden && HasFlag( ui::GetStyle( hWnd ), WS_CHILD ) ) if ( !::IsWindowVisible( ::GetParent( hWnd ) ) ) // allow hidden child windows only if parent is visible return false; CRect windowRect; ::GetWindowRect( hWnd, &windowRect ); return windowRect.PtInRect( screenPos ) != FALSE; }
[ "phc.2nd@gmail.com" ]
phc.2nd@gmail.com
95302c43198a7ff38e96469136bf80317c0f69bf
52531e83412e970301ed6072efa2a7de141c3d44
/Nakama/Source/Nakama/Private/NakamaSDK/NFriendBlockMessage.cpp
50d70312d760ba39cad2bdb8e5d479f9ce721d3d
[ "Apache-2.0" ]
permissive
FashGek/nakama-unreal
c8b55deca463b979abe6c0d2aabf4d5c170afab7
742163e83815c93ccb96b6524f980ef70c0339ee
refs/heads/master
2021-01-20T14:19:05.473936
2017-04-25T23:26:22
2017-05-05T14:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
956
cpp
/** * Copyright 2017 The Nakama Authors * * 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. */ #ifdef __UNREAL__ #include "Nakama/Private/NakamaPrivatePCH.h" #endif #include "NFriendBlockMessage.h" namespace Nakama { NFriendBlockMessage::NFriendBlockMessage(std::string id) { // set our default envelope.mutable_friend_block()->set_user_id(id); } NFriendBlockMessage NFriendBlockMessage::Default(std::string id) { return NFriendBlockMessage(id); } }
[ "chris@heroiclabs.com" ]
chris@heroiclabs.com
0685a3d6693b8d18a6d16142df058a95a6c92648
33a63a183246febbb4e3813441067038777c403d
/atlas-aapt/external/libcxx/include/experimental/any
a38397a99aed3b8e8f74bca2197d2162e149edaa
[ "NCSA", "MIT", "Apache-2.0" ]
permissive
wwjiang007/atlas
95117cc4d095d20e6988fc2134c0899cb54abcc9
afaa61796bb6b26fe373e31a4fc57fdd16fa0a44
refs/heads/master
2023-04-13T22:41:18.035080
2021-04-24T09:05:41
2021-04-24T09:05:41
115,571,324
0
0
Apache-2.0
2021-04-24T09:05:42
2017-12-28T01:21:17
Java
UTF-8
C++
false
false
14,994
// -*- C++ -*- //===------------------------------ any -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_EXPERIMENTAL_ANY #define _LIBCPP_EXPERIMENTAL_ANY /* experimental/any synopsis namespace std { namespace experimental { inline namespace fundamentals_v1 { class bad_any_cast : public bad_cast { public: virtual const char* what() const noexcept; }; class any { public: // 6.3.1 any construct/destruct any() noexcept; any(const any& other); any(any&& other) noexcept; template <class ValueType> any(ValueType&& value); ~any(); // 6.3.2 any assignments any& operator=(const any& rhs); any& operator=(any&& rhs) noexcept; template <class ValueType> any& operator=(ValueType&& rhs); // 6.3.3 any modifiers void clear() noexcept; void swap(any& rhs) noexcept; // 6.3.4 any observers bool empty() const noexcept; const type_info& type() const noexcept; }; // 6.4 Non-member functions void swap(any& x, any& y) noexcept; template<class ValueType> ValueType any_cast(const any& operand); template<class ValueType> ValueType any_cast(any& operand); template<class ValueType> ValueType any_cast(any&& operand); template<class ValueType> const ValueType* any_cast(const any* operand) noexcept; template<class ValueType> ValueType* any_cast(any* operand) noexcept; } // namespace fundamentals_v1 } // namespace experimental } // namespace std */ #include <experimental/__config> #include <memory> #include <new> #include <typeinfo> #include <type_traits> #include <cstdlib> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif _LIBCPP_BEGIN_NAMESPACE_LFTS class _LIBCPP_EXCEPTION_ABI bad_any_cast : public bad_cast { public: //TODO(EricWF) Enable or delete these. //bad_any_cast() _NOEXCEPT; //virtual ~bad_any_cast() _NOEXCEPT; virtual const char* what() const _NOEXCEPT; }; #if _LIBCPP_STD_VER > 11 // C++ > 11 _LIBCPP_NORETURN _LIBCPP_INLINE_VISIBILITY inline void __throw_bad_any_cast() { #ifndef _LIBCPP_NO_EXCEPTIONS throw bad_any_cast(); #else _VSTD::abort(); #endif } // Forward declarations class any; template <class _ValueType> typename add_pointer<typename add_const<_ValueType>::type>::type any_cast(any const *) _NOEXCEPT; template <class _ValueType> typename add_pointer<_ValueType>::type any_cast(any *) _NOEXCEPT; namespace __any_imp { typedef typename aligned_storage<3*sizeof(void*), alignment_of<void*>::value>::type _Buffer; template <class _Tp> struct _IsSmallObject : public integral_constant<bool , sizeof(_Tp) <= sizeof(_Buffer) && alignment_of<_Buffer>::value % alignment_of<_Tp>::value == 0 && is_nothrow_move_constructible<_Tp>::value > {}; enum class _Action { _Destroy, _Copy, _Move, _Get, _TypeInfo }; template <class _Tp> struct _SmallHandler; template <class _Tp> struct _LargeHandler; template <class _Tp> using _Handler = typename conditional<_IsSmallObject<_Tp>::value , _SmallHandler<_Tp> , _LargeHandler<_Tp> >::type; template <class _ValueType> using _EnableIfNotAny = typename enable_if< !is_same<typename decay<_ValueType>::type, any>::value >::type; } // namespace __any_imp class any { public: // 6.3.1 any construct/destruct _LIBCPP_INLINE_VISIBILITY any() _NOEXCEPT : __h(nullptr) {} _LIBCPP_INLINE_VISIBILITY any(any const & __other) : __h(nullptr) { if (__other.__h) __other.__call(_Action::_Copy, this); } _LIBCPP_INLINE_VISIBILITY any(any && __other) _NOEXCEPT : __h(nullptr) { if (__other.__h) __other.__call(_Action::_Move, this); } template < class _ValueType , class = __any_imp::_EnableIfNotAny<_ValueType> > any(_ValueType && __value); _LIBCPP_INLINE_VISIBILITY ~any() { this->clear(); } // 6.3.2 any assignments _LIBCPP_INLINE_VISIBILITY any & operator=(any const & __rhs) { any(__rhs).swap(*this); return *this; } _LIBCPP_INLINE_VISIBILITY any & operator=(any && __rhs) _NOEXCEPT { any(_VSTD::move(__rhs)).swap(*this); return *this; } template < class _ValueType , class = __any_imp::_EnableIfNotAny<_ValueType> > any & operator=(_ValueType && __rhs); // 6.3.3 any modifiers _LIBCPP_INLINE_VISIBILITY void clear() _NOEXCEPT { if (__h) this->__call(_Action::_Destroy); } void swap(any & __rhs) _NOEXCEPT; // 6.3.4 any observers _LIBCPP_INLINE_VISIBILITY bool empty() const _NOEXCEPT { return __h == nullptr; } #if !defined(_LIBCPP_NO_RTTI) _LIBCPP_INLINE_VISIBILITY const type_info & type() const _NOEXCEPT { if (__h) { return *static_cast<type_info const *>(this->__call(_Action::_TypeInfo)); } else { return typeid(void); } } #endif private: typedef __any_imp::_Action _Action; typedef void* (*_HandleFuncPtr)(_Action, any const *, any *, const type_info *); union _Storage { void * __ptr; __any_imp::_Buffer __buf; }; _LIBCPP_ALWAYS_INLINE void * __call(_Action __a, any * __other = nullptr, type_info const * __info = nullptr) const { return __h(__a, this, __other, __info); } _LIBCPP_ALWAYS_INLINE void * __call(_Action __a, any * __other = nullptr, type_info const * __info = nullptr) { return __h(__a, this, __other, __info); } template <class> friend struct __any_imp::_SmallHandler; template <class> friend struct __any_imp::_LargeHandler; template <class _ValueType> friend typename add_pointer<typename add_const<_ValueType>::type>::type any_cast(any const *) _NOEXCEPT; template <class _ValueType> friend typename add_pointer<_ValueType>::type any_cast(any *) _NOEXCEPT; _HandleFuncPtr __h; _Storage __s; }; namespace __any_imp { template <class _Tp> struct _LIBCPP_TYPE_VIS_ONLY _SmallHandler { _LIBCPP_INLINE_VISIBILITY static void* __handle(_Action __act, any const * __this, any * __other, type_info const * __info) { switch (__act) { case _Action::_Destroy: __destroy(const_cast<any &>(*__this)); return nullptr; case _Action::_Copy: __copy(*__this, *__other); return nullptr; case _Action::_Move: __move(const_cast<any &>(*__this), *__other); return nullptr; case _Action::_Get: return __get(const_cast<any &>(*__this), __info); case _Action::_TypeInfo: return __type_info(); } } template <class _Up> _LIBCPP_INLINE_VISIBILITY static void __create(any & __dest, _Up && __v) { ::new (static_cast<void*>(&__dest.__s.__buf)) _Tp(_VSTD::forward<_Up>(__v)); __dest.__h = &_SmallHandler::__handle; } private: _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void __destroy(any & __this) { _Tp & __value = *static_cast<_Tp *>(static_cast<void*>(&__this.__s.__buf)); __value.~_Tp(); __this.__h = nullptr; } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void __copy(any const & __this, any & __dest) { _SmallHandler::__create(__dest, *static_cast<_Tp const *>( static_cast<void const *>(&__this.__s.__buf))); } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void __move(any & __this, any & __dest) { _SmallHandler::__create(__dest, _VSTD::move( *static_cast<_Tp*>(static_cast<void*>(&__this.__s.__buf)))); __destroy(__this); } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void* __get(any & __this, type_info const * __info) { #if !defined(_LIBCPP_NO_RTTI) if (typeid(_Tp) == *__info) { return static_cast<void*>(&__this.__s.__buf); } return nullptr; #else return static_cast<void*>(&__this.__s.__buf); #endif } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void* __type_info() { #if !defined(_LIBCPP_NO_RTTI) return const_cast<void*>(static_cast<void const *>(&typeid(_Tp))); #else return nullptr; #endif } }; template <class _Tp> struct _LIBCPP_TYPE_VIS_ONLY _LargeHandler { _LIBCPP_INLINE_VISIBILITY static void* __handle(_Action __act, any const * __this, any * __other, type_info const * __info) { switch (__act) { case _Action::_Destroy: __destroy(const_cast<any &>(*__this)); return nullptr; case _Action::_Copy: __copy(*__this, *__other); return nullptr; case _Action::_Move: __move(const_cast<any &>(*__this), *__other); return nullptr; case _Action::_Get: return __get(const_cast<any &>(*__this), __info); case _Action::_TypeInfo: return __type_info(); } } template <class _Up> _LIBCPP_INLINE_VISIBILITY static void __create(any & __dest, _Up && __v) { typedef allocator<_Tp> _Alloc; typedef __allocator_destructor<_Alloc> _Dp; _Alloc __a; unique_ptr<_Tp, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); ::new ((void*)__hold.get()) _Tp(_VSTD::forward<_Up>(__v)); __dest.__s.__ptr = __hold.release(); __dest.__h = &_LargeHandler::__handle; } private: _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void __destroy(any & __this) { delete static_cast<_Tp*>(__this.__s.__ptr); __this.__h = nullptr; } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void __copy(any const & __this, any & __dest) { _LargeHandler::__create(__dest, *static_cast<_Tp const *>(__this.__s.__ptr)); } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void __move(any & __this, any & __dest) { __dest.__s.__ptr = __this.__s.__ptr; __dest.__h = &_LargeHandler::__handle; __this.__h = nullptr; } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void* __get(any & __this, type_info const * __info) { #if !defined(_LIBCPP_NO_RTTI) if (typeid(_Tp) == *__info) { return static_cast<void*>(__this.__s.__ptr); } return nullptr; #else return static_cast<void*>(__this.__s.__ptr); #endif } _LIBCPP_ALWAYS_INLINE _LIBCPP_INLINE_VISIBILITY static void* __type_info() { #if !defined(_LIBCPP_NO_RTTI) return const_cast<void*>(static_cast<void const *>(&typeid(_Tp))); #else return nullptr; #endif } }; } // namespace __any_imp template <class _ValueType, class> _LIBCPP_INLINE_VISIBILITY any::any(_ValueType && __v) : __h(nullptr) { typedef typename decay<_ValueType>::type _Tp; static_assert(is_copy_constructible<_Tp>::value, "_ValueType must be CopyConstructible."); typedef __any_imp::_Handler<_Tp> _HandlerType; _HandlerType::__create(*this, _VSTD::forward<_ValueType>(__v)); } template <class _ValueType, class> _LIBCPP_INLINE_VISIBILITY any & any::operator=(_ValueType && __v) { typedef typename decay<_ValueType>::type _Tp; static_assert(is_copy_constructible<_Tp>::value, "_ValueType must be CopyConstructible."); any(_VSTD::forward<_ValueType>(__v)).swap(*this); return *this; } inline _LIBCPP_INLINE_VISIBILITY void any::swap(any & __rhs) _NOEXCEPT { if (__h && __rhs.__h) { any __tmp; __rhs.__call(_Action::_Move, &__tmp); this->__call(_Action::_Move, &__rhs); __tmp.__call(_Action::_Move, this); } else if (__h) { this->__call(_Action::_Move, &__rhs); } else if (__rhs.__h) { __rhs.__call(_Action::_Move, this); } } // 6.4 Non-member functions inline _LIBCPP_INLINE_VISIBILITY void swap(any & __lhs, any & __rhs) _NOEXCEPT { __lhs.swap(__rhs); } template <class _ValueType> _LIBCPP_INLINE_VISIBILITY _ValueType any_cast(any const & __v) { static_assert( is_reference<_ValueType>::value || is_copy_constructible<_ValueType>::value, "_ValueType is required to be a reference or a CopyConstructible type."); typedef typename add_const<typename remove_reference<_ValueType>::type>::type _Tp; _Tp * __tmp = any_cast<_Tp>(&__v); if (__tmp == nullptr) __throw_bad_any_cast(); return *__tmp; } template <class _ValueType> _LIBCPP_INLINE_VISIBILITY _ValueType any_cast(any & __v) { static_assert( is_reference<_ValueType>::value || is_copy_constructible<_ValueType>::value, "_ValueType is required to be a reference or a CopyConstructible type."); typedef typename remove_reference<_ValueType>::type _Tp; _Tp * __tmp = any_cast<_Tp>(&__v); if (__tmp == nullptr) __throw_bad_any_cast(); return *__tmp; } template <class _ValueType> _LIBCPP_INLINE_VISIBILITY _ValueType any_cast(any && __v) { static_assert( is_reference<_ValueType>::value || is_copy_constructible<_ValueType>::value, "_ValueType is required to be a reference or a CopyConstructible type."); typedef typename remove_reference<_ValueType>::type _Tp; _Tp * __tmp = any_cast<_Tp>(&__v); if (__tmp == nullptr) __throw_bad_any_cast(); return *__tmp; } template <class _ValueType> inline _LIBCPP_INLINE_VISIBILITY typename add_pointer<typename add_const<_ValueType>::type>::type any_cast(any const * __any) _NOEXCEPT { static_assert(!is_reference<_ValueType>::value, "_ValueType may not be a reference."); return any_cast<_ValueType>(const_cast<any *>(__any)); } template <class _ValueType> _LIBCPP_INLINE_VISIBILITY typename add_pointer<_ValueType>::type any_cast(any * __any) _NOEXCEPT { using __any_imp::_Action; static_assert(!is_reference<_ValueType>::value, "_ValueType may not be a reference."); typedef typename add_pointer<_ValueType>::type _ReturnType; if (__any && __any->__h) { return static_cast<_ReturnType>( __any->__call(_Action::_Get, nullptr, #if !defined(_LIBCPP_NO_RTTI) &typeid(_ValueType) #else nullptr #endif )); } return nullptr; } #endif // _LIBCPP_STD_VER > 11 _LIBCPP_END_NAMESPACE_LFTS #endif // _LIBCPP_EXPERIMENTAL_ANY
[ "guanjie.yjf@taobao.com" ]
guanjie.yjf@taobao.com
94395b3d00550e7cf0aa371478b2f7e7e33102b0
1bd9e3cda029e15d43a2e537663495ff27e317e2
/buoyantPimpleFoam_timevaryingBC/buoyantCavity/system/sample
161e27e6886169b397db7ab1987933e37784b381
[]
no_license
tsam1307/OpenFoam_heatTrf
810b81164d3b67001bfce5ab9311d9b3d45b5c9d
799753d24862607a3383aa582a6d9e23840c3b15
refs/heads/main
2023-08-10T23:27:40.420639
2021-09-18T12:46:01
2021-09-18T12:46:01
382,377,763
1
0
null
null
null
null
UTF-8
C++
false
false
2,381
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2012 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "system"; object sample; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // type sets; libs (sampling); interpolationScheme cellPointFace; setFormat raw; sets ( y0.1 { type face; axis x; start (-1 0.218 0); end (1 0.218 0); } y0.2 { type face; axis x; start (-1 0.436 0); end (1 0.436 0); } y0.3 { type face; axis x; start (-1 0.654 0); end (1 0.654 0); } y0.4 { type face; axis x; start (-1 0.872 0); end (1 0.872 0); } y0.5 { type face; axis x; start (-1 1.09 0); end (1 1.09 0); } y0.6 { type face; axis x; start (-1 1.308 0); end (1 1.308 0); } y0.7 { type face; axis x; start (-1 1.526 0); end (1 1.526 0); } y0.8 { type face; axis x; start (-1 1.744 0); end (1 1.744 0); } y0.9 { type face; axis x; start (-1 1.962 0); end (1 1.962 0); } ); fields ( T U ); // ************************************************************************* //
[ "tsinghsamant@gmail.com" ]
tsinghsamant@gmail.com
96e2e8e80f84685d962c0f3bc94d16425129de89
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/chrome/browser/net/chrome_network_delegate.cc
05b17b07f2d114175a60dfb278da8e1df2bb3717
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
38,151
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 "chrome/browser/net/chrome_network_delegate.h" #include <stddef.h> #include <stdlib.h> #include <vector> #include "base/base_paths.h" #include "base/command_line.h" #include "base/debug/alias.h" #include "base/debug/dump_without_crashing.h" #include "base/debug/stack_trace.h" #include "base/logging.h" #include "base/macros.h" #include "base/metrics/user_metrics.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/task/post_task.h" #include "base/sequenced_task_runner.h" #include "base/time/time.h" #include "brave_src/browser/brave_tab_url_web_contents_observer.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" #include "chrome/browser/custom_handlers/protocol_handler_registry.h" #include "chrome/browser/net/blockers/blockers_worker.h" #include "chrome/browser/net/chrome_extensions_network_delegate.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/stats_updater.h" #include "chrome/browser/task_manager/task_manager_interface.h" #include "chrome/common/buildflags.h" #include "chrome/common/net/safe_search_util.h" #include "chrome/common/pref_names.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/variations/net/variations_http_headers.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/resource_request_info.h" #include "content/public/browser/websocket_handshake_request_info.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "content/public/common/resource_type.h" #include "extensions/buildflags/buildflags.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_options.h" #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "net/log/net_log.h" #include "net/log/net_log_event_type.h" #include "net/log/net_log_with_source.h" #include "net/url_request/url_request.h" #include "chrome/browser/net/blockers/shields_config.h" #if defined(OS_ANDROID) #include "base/android/path_utils.h" #include "chrome/browser/io_thread.h" #endif #if defined(OS_CHROMEOS) #include "base/system/sys_info.h" #include "chrome/common/chrome_switches.h" #endif #if BUILDFLAG(ENABLE_EXTENSIONS) #include "extensions/common/constants.h" #endif using content::BrowserThread; using content::RenderViewHost; using content::ResourceRequestInfo; #define TRANSPARENT1PXGIF "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" namespace { bool g_access_to_all_files_enabled = false; // Gets called when the extensions finish work on the URL. If the extensions // did not do a redirect (so |new_url| is empty) then we enforce the // SafeSearch parameters. Otherwise we will get called again after the // redirect and we enforce SafeSearch then. void ForceGoogleSafeSearchCallbackWrapper(net::CompletionOnceCallback callback, net::URLRequest* request, GURL* new_url, int rv) { if (rv == net::OK && new_url->is_empty()) safe_search_util::ForceGoogleSafeSearch(request->url(), new_url); std::move(callback).Run(rv); } bool IsAccessAllowedInternal(const base::FilePath& path, const base::FilePath& profile_path) { if (g_access_to_all_files_enabled) return true; #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) return true; #else std::vector<base::FilePath> whitelist; #if defined(OS_CHROMEOS) // Use a whitelist to only allow access to files residing in the list of // directories below. static const base::FilePath::CharType* const kLocalAccessWhiteList[] = { "/home/chronos/user/Downloads", "/home/chronos/user/log", "/home/chronos/user/WebRTC Logs", "/media", "/opt/oem", "/run/arc/sdcard/write/emulated/0", "/usr/share/chromeos-assets", "/var/log", }; base::FilePath temp_dir; if (base::PathService::Get(base::DIR_TEMP, &temp_dir)) whitelist.push_back(temp_dir); // The actual location of "/home/chronos/user/Xyz" is the Xyz directory under // the profile path ("/home/chronos/user' is a hard link to current primary // logged in profile.) For the support of multi-profile sessions, we are // switching to use explicit "$PROFILE_PATH/Xyz" path and here whitelist such // access. if (!profile_path.empty()) { const base::FilePath downloads = profile_path.AppendASCII("Downloads"); whitelist.push_back(downloads); const base::FilePath webrtc_logs = profile_path.AppendASCII("WebRTC Logs"); whitelist.push_back(webrtc_logs); } #elif defined(OS_ANDROID) // Access to files in external storage is allowed. base::FilePath external_storage_path; base::PathService::Get(base::DIR_ANDROID_EXTERNAL_STORAGE, &external_storage_path); if (external_storage_path.IsParent(path)) return true; auto all_download_dirs = base::android::GetAllPrivateDownloadsDirectories(); for (const auto& dir : all_download_dirs) whitelist.push_back(dir); // Whitelist of other allowed directories. static const base::FilePath::CharType* const kLocalAccessWhiteList[] = { "/sdcard", "/mnt/sdcard", }; #endif for (const auto* whitelisted_path : kLocalAccessWhiteList) whitelist.push_back(base::FilePath(whitelisted_path)); for (const auto& whitelisted_path : whitelist) { // base::FilePath::operator== should probably handle trailing separators. if (whitelisted_path == path.StripTrailingSeparators() || whitelisted_path.IsParent(path)) { return true; } } #if defined(OS_CHROMEOS) // Allow access to DriveFS logs. These reside in // $PROFILE_PATH/GCache/v2/<opaque id>/Logs. base::FilePath path_within_gcache_v2; if (profile_path.Append("GCache/v2") .AppendRelativePath(path, &path_within_gcache_v2)) { std::vector<std::string> components; path_within_gcache_v2.GetComponents(&components); if (components.size() > 1 && components[1] == "Logs") { return true; } } #endif // defined(OS_CHROMEOS) DVLOG(1) << "File access denied - " << path.value().c_str(); return false; #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID) } } // namespace class PendingRequests { public: void Insert(const uint64_t &request_identifier) { pending_requests_.insert(request_identifier); } void Destroy(const uint64_t &request_identifier) { pending_requests_.erase(request_identifier); } bool IsPendingAndAlive(const uint64_t &request_identifier) { bool isPending = pending_requests_.find(request_identifier) != pending_requests_.end(); return isPending; } private: std::set<uint64_t> pending_requests_; //no need synchronization, should be executed in the same thread content::BrowserThread::IO }; struct OnBeforeURLRequestContext { OnBeforeURLRequestContext(){} ~OnBeforeURLRequestContext(){} int adsBlocked = 0; int trackersBlocked = 0; int httpsUpgrades = 0; bool isGlobalBlockEnabled = true; bool blockAdsAndTracking = true; bool isAdBlockRegionalEnabled = true; bool isTPEnabled = true; bool isHTTPSEEnabled = true; bool isBlock3rdPartyCookies = true; bool shieldsSetExplicitly = false; bool needPerformAdBlock = false; bool needPerformTPBlock = false; bool needPerformHTTPSE = false; bool block = false; const ResourceRequestInfo* info = nullptr; bool isValidUrl = true; std::string firstparty_host = ""; bool check_httpse_redirect = true; GURL UrlCopy; std::string newURL; bool pendingAtLeastOnce = false; uint64_t request_identifier = 0; DISALLOW_COPY_AND_ASSIGN(OnBeforeURLRequestContext); }; ChromeNetworkDelegate::ChromeNetworkDelegate( extensions::EventRouterForwarder* event_router) : extensions_delegate_( ChromeExtensionsNetworkDelegate::Create(event_router)), profile_(nullptr), enable_httpse_(nullptr), enable_tracking_protection_(nullptr), enable_ad_block_(nullptr), enable_ad_block_regional_(nullptr), experimental_web_platform_features_enabled_( base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalWebPlatformFeatures)), reload_adblocker_(false), incognito_(false) { pending_requests_.reset(new PendingRequests()); } ChromeNetworkDelegate::~ChromeNetworkDelegate() {} void ChromeNetworkDelegate::set_extension_info_map( extensions::InfoMap* extension_info_map) { extensions_delegate_->set_extension_info_map(extension_info_map); } void ChromeNetworkDelegate::set_profile(void* profile) { profile_ = profile; extensions_delegate_->set_profile(profile); } void ChromeNetworkDelegate::set_cookie_settings( content_settings::CookieSettings* cookie_settings) { cookie_settings_ = cookie_settings; } void ChromeNetworkDelegate::set_blockers_worker( std::shared_ptr<net::blockers::BlockersWorker> blockers_worker) { blockers_worker_ = blockers_worker; } void ChromeNetworkDelegate::set_incognito(const bool &incognito) { incognito_ = incognito; } // static void ChromeNetworkDelegate::InitializePrefsOnUIThread( BooleanPrefMember* enable_httpse, BooleanPrefMember* enable_tracking_protection, BooleanPrefMember* enable_ad_block, BooleanPrefMember* enable_ad_block_regional, PrefService* pref_service) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (enable_httpse) { enable_httpse->Init(prefs::kHTTPSEEnabled, pref_service); enable_httpse->MoveToThread( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } if (enable_tracking_protection) { enable_tracking_protection->Init(prefs::kTrackingProtectionEnabled, pref_service); enable_tracking_protection->MoveToThread( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } if (enable_ad_block) { enable_ad_block->Init(prefs::kAdBlockEnabled, pref_service); enable_ad_block->MoveToThread( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } if (enable_ad_block_regional) { enable_ad_block_regional->Init(prefs::kAdBlockRegionalEnabled, pref_service); enable_ad_block_regional->MoveToThread( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } } int ChromeNetworkDelegate::OnBeforeURLRequest( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, bool call_callback) { std::shared_ptr<OnBeforeURLRequestContext> ctx(new OnBeforeURLRequestContext()); int rv = OnBeforeURLRequest_PreBlockersWork( request, std::move(callback), new_url, ctx); return rv; } int ChromeNetworkDelegate::OnBeforeURLRequest_PreBlockersWork( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); ctx->firstparty_host = ""; if (request) { ctx->firstparty_host = request->site_for_cookies().host(); ctx->request_identifier = request->identifier(); } // (TODO)find a better way to handle last first party if (0 == ctx->firstparty_host.length()) { ctx->firstparty_host = last_first_party_url_.host(); } else if (request) { last_first_party_url_ = request->site_for_cookies(); } // We want to block first party ads as well /*bool firstPartyUrl = false; if (request && (last_first_party_url_ == request->url())) { firstPartyUrl = true; }*/ // Ad Block and tracking protection ctx->isGlobalBlockEnabled = true; ctx->blockAdsAndTracking = true; ctx->isHTTPSEEnabled = true; ctx->isBlock3rdPartyCookies = true; ctx->shieldsSetExplicitly = false; net::blockers::ShieldsConfig* shieldsConfig = net::blockers::ShieldsConfig::getShieldsConfig(); if (request && nullptr != shieldsConfig) { std::string hostConfig = shieldsConfig->getHostSettings(incognito_, ctx->firstparty_host); // It is a length of ALL_SHIELDS_DEFAULT_MASK in ShieldsConfig.java if (hostConfig.length() == 11) { ctx->shieldsSetExplicitly = true; if ('0' == hostConfig[0]) { ctx->isGlobalBlockEnabled = false; } if (ctx->isGlobalBlockEnabled) { if ('0' == hostConfig[2]) { ctx->blockAdsAndTracking = false; } if ('0' == hostConfig[4]) { ctx->isHTTPSEEnabled = false; } if ('0' == hostConfig[8]) { ctx->isBlock3rdPartyCookies = false; } } } } else if (nullptr == shieldsConfig){ ctx->isGlobalBlockEnabled = false; } ctx->isValidUrl = true; if (request) { ctx->isValidUrl = request->url().is_valid(); std::string scheme = request->url().scheme(); if (scheme.length()) { std::transform(scheme.begin(), scheme.end(), scheme.begin(), ::tolower); if ("http" != scheme && "https" != scheme/* && "blob" != scheme*/) { ctx->isValidUrl = false; } } } ctx->isTPEnabled = true; ctx->block = false; if (enable_tracking_protection_ && !ctx->shieldsSetExplicitly) { ctx->isTPEnabled = enable_tracking_protection_->GetValue(); } ctx->adsBlocked = 0; ctx->trackersBlocked = 0; ctx->httpsUpgrades = 0; int rv = net::ERR_IO_PENDING; if (reload_adblocker_) { reload_adblocker_ = false; base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, base::Bind(&ChromeNetworkDelegate::GetIOThread, base::Unretained(this), base::Unretained(request), base::Passed(&callback), new_url, ctx)); if (nullptr != shieldsConfig) { shieldsConfig->resetUpdateAdBlockerFlag(); } ctx->pendingAtLeastOnce = true; pending_requests_->Insert(request->identifier()); } else { rv = OnBeforeURLRequest_TpBlockPreFileWork(request, std::move(callback), new_url, ctx); // Check do we need to reload adblocker. We will do that on next call base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, base::Bind(base::IgnoreResult(&ChromeNetworkDelegate::CheckAdBlockerReload), base::Unretained(this), shieldsConfig)); } return rv; } void ChromeNetworkDelegate::CheckAdBlockerReload(net::blockers::ShieldsConfig* shields_config) { if (nullptr == shields_config) { return; } reload_adblocker_ = shields_config->needUpdateAdBlocker(); } void ChromeNetworkDelegate::GetIOThread(net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { scoped_refptr<base::SequencedTaskRunner> task_runner = base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTask(FROM_HERE, base::Bind(&ChromeNetworkDelegate::ResetBlocker, base::Unretained(this), g_browser_process->io_thread(), base::Unretained(request), base::Passed(&callback), new_url, ctx)); } void ChromeNetworkDelegate::ResetBlocker(IOThread* io_thread, net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { blockers_worker_ = io_thread->ResetBlockersWorker(); base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO}, base::Bind(base::IgnoreResult(&ChromeNetworkDelegate::OnBeforeURLRequest_TpBlockPostFileWork), base::Unretained(this), base::Unretained(request), base::Passed(&callback), new_url, ctx) ); } int ChromeNetworkDelegate::OnBeforeURLRequest_TpBlockPreFileWork( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); ctx->needPerformTPBlock = false; if (request //&& !firstPartyUrl && ctx->isValidUrl && ctx->isGlobalBlockEnabled && ctx->blockAdsAndTracking && ctx->isTPEnabled) { ctx->needPerformTPBlock = true; if (!blockers_worker_->isTPInitialized() ) { scoped_refptr<base::SequencedTaskRunner> task_runner = base::CreateSequencedTaskRunnerWithTraits({base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTaskAndReply(FROM_HERE, base::Bind(&ChromeNetworkDelegate::OnBeforeURLRequest_TpBlockFileWork, base::Unretained(this)), base::Bind(base::IgnoreResult(&ChromeNetworkDelegate::OnBeforeURLRequest_TpBlockPostFileWork), base::Unretained(this), base::Unretained(request), base::Passed(&callback), new_url, ctx)); ctx->pendingAtLeastOnce = true; pending_requests_->Insert(request->identifier()); return net::ERR_IO_PENDING; } } int rv = OnBeforeURLRequest_TpBlockPostFileWork(request, std::move(callback), new_url, ctx); return rv; } void ChromeNetworkDelegate::OnBeforeURLRequest_TpBlockFileWork() { base::internal::AssertBlockingAllowed(); blockers_worker_->InitTP(); } int ChromeNetworkDelegate::OnBeforeURLRequest_TpBlockPostFileWork( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (PendedRequestIsDestroyedOrCancelled(ctx.get(), request)) { return net::OK; } if (ctx->needPerformTPBlock){ if (blockers_worker_->shouldTPBlockUrl( ctx->firstparty_host, request->url().host())) { ctx->block = true; ctx->trackersBlocked++; } } int rv = OnBeforeURLRequest_AdBlockPreFileWork(request, std::move(callback), new_url, ctx); return rv; } int ChromeNetworkDelegate::OnBeforeURLRequest_AdBlockPreFileWork( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); bool isAdBlockEnabled = true; if (enable_ad_block_ && !ctx->shieldsSetExplicitly) { isAdBlockEnabled = enable_ad_block_->GetValue(); } // Regional ad block flag ctx->isAdBlockRegionalEnabled = true; if (enable_ad_block_regional_ && !ctx->shieldsSetExplicitly) { ctx->isAdBlockRegionalEnabled = enable_ad_block_regional_->GetValue(); } ctx->info = ResourceRequestInfo::ForRequest(request); if (!ctx->block //&& !firstPartyUrl && ctx->isValidUrl && ctx->isGlobalBlockEnabled && ctx->blockAdsAndTracking && isAdBlockEnabled && request && ctx->info && content::RESOURCE_TYPE_MAIN_FRAME != ctx->info->GetResourceType()) { ctx->needPerformAdBlock = true; if (!blockers_worker_->isAdBlockerInitialized() || (ctx->isAdBlockRegionalEnabled && !blockers_worker_->isAdBlockerRegionalInitialized()) ) { scoped_refptr<base::SequencedTaskRunner> task_runner = base::CreateSequencedTaskRunnerWithTraits({base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTaskAndReply(FROM_HERE, base::Bind(&ChromeNetworkDelegate::OnBeforeURLRequest_AdBlockFileWork, base::Unretained(this), ctx), base::Bind(base::IgnoreResult(&ChromeNetworkDelegate::OnBeforeURLRequest_AdBlockPostFileWork), base::Unretained(this), base::Unretained(request), base::Passed(&callback), new_url, ctx)); ctx->pendingAtLeastOnce = true; pending_requests_->Insert(request->identifier()); return net::ERR_IO_PENDING; } } int rv = OnBeforeURLRequest_AdBlockPostFileWork(request, std::move(callback), new_url, ctx); return rv; } void ChromeNetworkDelegate::OnBeforeURLRequest_AdBlockFileWork(std::shared_ptr<OnBeforeURLRequestContext> ctx) { base::internal::AssertBlockingAllowed(); blockers_worker_->InitAdBlock(); if (ctx->isAdBlockRegionalEnabled && !blockers_worker_->isAdBlockerRegionalInitialized()) { blockers_worker_->InitAdBlockRegional(); } } int ChromeNetworkDelegate::OnBeforeURLRequest_AdBlockPostFileWork( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (PendedRequestIsDestroyedOrCancelled(ctx.get(), request)) { return net::OK; } if (ctx->needPerformAdBlock) { if (blockers_worker_->shouldAdBlockUrl( ctx->firstparty_host, request->url().spec(), (unsigned int)ctx->info->GetResourceType(), ctx->isAdBlockRegionalEnabled)) { ctx->block = true; ctx->adsBlocked++; } } ctx->check_httpse_redirect = true; if (ctx->block && ctx->info && content::RESOURCE_TYPE_IMAGE == ctx->info->GetResourceType()) { ctx->check_httpse_redirect = false; *new_url = GURL(TRANSPARENT1PXGIF); } int rv = OnBeforeURLRequest_HttpsePreFileWork(request, std::move(callback), new_url, ctx); return rv; } int ChromeNetworkDelegate::OnBeforeURLRequest_HttpsePreFileWork( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); ctx->needPerformHTTPSE = false; // HTTPSE work if (!ctx->block && request && ctx->isValidUrl && ctx->isGlobalBlockEnabled && ctx->isHTTPSEEnabled && ctx->check_httpse_redirect && (ctx->shieldsSetExplicitly || (enable_httpse_ && enable_httpse_->GetValue()))) { ctx->needPerformHTTPSE = true; } if (ctx->needPerformHTTPSE) { ctx->newURL = blockers_worker_->getHTTPSURLFromCacheOnly(&request->url(), request->identifier()); if (ctx->newURL == request->url().spec()) { ctx->UrlCopy = request->url(); scoped_refptr<base::SequencedTaskRunner> task_runner = base::CreateSequencedTaskRunnerWithTraits({base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}); task_runner->PostTaskAndReply(FROM_HERE, base::Bind(&ChromeNetworkDelegate::OnBeforeURLRequest_HttpseFileWork, base::Unretained(this), base::Unretained(request), ctx), base::Bind(base::IgnoreResult(&ChromeNetworkDelegate::OnBeforeURLRequest_HttpsePostFileWork), base::Unretained(this), base::Unretained(request), base::Passed(&callback), new_url, ctx)); ctx->pendingAtLeastOnce = true; pending_requests_->Insert(request->identifier()); return net::ERR_IO_PENDING; } } int rv = OnBeforeURLRequest_HttpsePostFileWork(request, std::move(callback), new_url, ctx); return rv; } void ChromeNetworkDelegate::OnBeforeURLRequest_HttpseFileWork(net::URLRequest* request, std::shared_ptr<OnBeforeURLRequestContext> ctx) { base::internal::AssertBlockingAllowed(); DCHECK(ctx->request_identifier != 0); ctx->newURL = blockers_worker_->getHTTPSURL(&ctx->UrlCopy, ctx->request_identifier); } int ChromeNetworkDelegate::OnBeforeURLRequest_HttpsePostFileWork(net::URLRequest* request,net::CompletionOnceCallback callback,GURL* new_url,std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); if (PendedRequestIsDestroyedOrCancelled(ctx.get(), request)) { return net::OK; } if (!ctx->newURL.empty() && ctx->needPerformHTTPSE && ctx->newURL != request->url().spec()) { *new_url = GURL(ctx->newURL); if (last_first_party_url_ != request->url()) { ctx->httpsUpgrades++; } } int rv = OnBeforeURLRequest_PostBlockers(request, std::move(callback), new_url, ctx); return rv; } int ChromeNetworkDelegate::OnBeforeURLRequest_PostBlockers( net::URLRequest* request, net::CompletionOnceCallback callback, GURL* new_url, std::shared_ptr<OnBeforeURLRequestContext> ctx) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); net::blockers::ShieldsConfig* shieldsConfig = net::blockers::ShieldsConfig::getShieldsConfig(); if (nullptr != shieldsConfig && (0 != ctx->trackersBlocked || 0 != ctx->adsBlocked || 0 != ctx->httpsUpgrades)) { shieldsConfig->setBlockedCountInfo(last_first_party_url_.spec() , ctx->trackersBlocked , ctx->adsBlocked , ctx->httpsUpgrades , 0 , 0); } if (ctx->block && (nullptr == ctx->info || content::RESOURCE_TYPE_IMAGE != ctx->info->GetResourceType())) { *new_url = GURL(""); if (ctx->pendingAtLeastOnce) { std::move(callback).Run(net::ERR_BLOCKED_BY_ADMINISTRATOR); } return net::ERR_BLOCKED_BY_ADMINISTRATOR; } extensions_delegate_->ForwardStartRequestStatus(request); ShouldBlockReferrer(ctx, request); // The non-redirect case is handled in GoogleURLLoaderThrottle. bool force_safe_search = (force_google_safe_search_ && force_google_safe_search_->GetValue() && request->is_redirecting()); net::CompletionOnceCallback wrapped_callback = std::move(callback); if (force_safe_search) { wrapped_callback = base::BindOnce( &ForceGoogleSafeSearchCallbackWrapper, std::move(wrapped_callback), base::Unretained(request), base::Unretained(new_url)); } int rv = extensions_delegate_->NotifyBeforeURLRequest( request, std::move(wrapped_callback), new_url, ctx->pendingAtLeastOnce); if (force_safe_search && rv == net::OK && new_url->is_empty()) safe_search_util::ForceGoogleSafeSearch(request->url(), new_url); return rv; } namespace { void SetCustomHeaders( net::URLRequest* request, net::HttpRequestHeaders* headers) { if (request && headers) { // Look for and setup custom headers std::string customHeaders = stats_updater::GetCustomHeadersForHost( request->url().host()); if (customHeaders.size()) { std::string key; std::string value; size_t pos = customHeaders.find("\n"); if (pos == std::string::npos) { key = customHeaders; value = ""; } else { key = customHeaders.substr(0, pos); value = customHeaders.substr(pos + 1); } if (key.size()) { headers->SetHeader(key, value); } } } } } // namespace int ChromeNetworkDelegate::OnBeforeStartTransaction( net::URLRequest* request, net::CompletionOnceCallback callback, net::HttpRequestHeaders* headers) { SetCustomHeaders(request, headers); return extensions_delegate_->NotifyBeforeStartTransaction( request, std::move(callback), headers); } void ChromeNetworkDelegate::OnStartTransaction( net::URLRequest* request, const net::HttpRequestHeaders& headers) { extensions_delegate_->NotifyStartTransaction(request, headers); } int ChromeNetworkDelegate::OnHeadersReceived( net::URLRequest* request, net::CompletionOnceCallback callback, const net::HttpResponseHeaders* original_response_headers, scoped_refptr<net::HttpResponseHeaders>* override_response_headers, GURL* allowed_unsafe_redirect_url) { return extensions_delegate_->NotifyHeadersReceived( request, std::move(callback), original_response_headers, override_response_headers, allowed_unsafe_redirect_url); } void ChromeNetworkDelegate::OnBeforeRedirect(net::URLRequest* request, const GURL& new_location) { extensions_delegate_->NotifyBeforeRedirect(request, new_location); variations::StripVariationHeaderIfNeeded(new_location, request); } void ChromeNetworkDelegate::OnResponseStarted(net::URLRequest* request, int net_error) { extensions_delegate_->NotifyResponseStarted(request, net_error); } void ChromeNetworkDelegate::OnNetworkBytesReceived(net::URLRequest* request, int64_t bytes_received) { #if !defined(OS_ANDROID) // Note: Currently, OnNetworkBytesReceived is only implemented for HTTP jobs, // not FTP or other types, so those kinds of bytes will not be reported here. task_manager::TaskManagerInterface::OnRawBytesRead(*request, bytes_received); #endif // !defined(OS_ANDROID) } void ChromeNetworkDelegate::OnNetworkBytesSent(net::URLRequest* request, int64_t bytes_sent) { #if !defined(OS_ANDROID) // Note: Currently, OnNetworkBytesSent is only implemented for HTTP jobs, // not FTP or other types, so those kinds of bytes will not be reported here. task_manager::TaskManagerInterface::OnRawBytesSent(*request, bytes_sent); #endif // !defined(OS_ANDROID) } void ChromeNetworkDelegate::OnCompleted(net::URLRequest* request, bool started, int net_error) { extensions_delegate_->NotifyCompleted(request, started, net_error); extensions_delegate_->ForwardDoneRequestStatus(request); } void ChromeNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) { extensions_delegate_->NotifyURLRequestDestroyed(request); pending_requests_->Destroy(request->identifier()); } net::NetworkDelegate::AuthRequiredResponse ChromeNetworkDelegate::OnAuthRequired(net::URLRequest* request, const net::AuthChallengeInfo& auth_info, AuthCallback callback, net::AuthCredentials* credentials) { return extensions_delegate_->NotifyAuthRequired( request, auth_info, std::move(callback), credentials); } namespace { // Taken from brave-core/components/brave_rewards/browser/net/network_delegate_helper.cc // TODO(alexeyb) remove when browser-android-tabs will be merged with brave-core void GetRenderFrameInfo(const net::URLRequest* request, int* render_frame_id, int* render_process_id, int* frame_tree_node_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); *render_frame_id = -1; *render_process_id = -1; *frame_tree_node_id = -1; // PlzNavigate requests have a frame_tree_node_id, but no render_process_id auto* request_info = content::ResourceRequestInfo::ForRequest(request); if (request_info) { *frame_tree_node_id = request_info->GetFrameTreeNodeId(); } if (!content::ResourceRequestInfo::GetRenderFrameForRequest( request, render_process_id, render_frame_id)) { const content::WebSocketHandshakeRequestInfo* websocket_info = content::WebSocketHandshakeRequestInfo::ForRequest(request); if (websocket_info) { *render_frame_id = websocket_info->GetRenderFrameId(); *render_process_id = websocket_info->GetChildId(); } } } GURL GetTabUrl(const net::URLRequest* request) { DCHECK(request); GURL tab_url; if (!request->site_for_cookies().is_empty()) { tab_url = request->site_for_cookies(); } else { int render_process_id; int render_frame_id; int frame_tree_node_id; GetRenderFrameInfo(request, &render_frame_id, &render_process_id, &frame_tree_node_id); // We can not always use site_for_cookies since it can be empty in certain // cases. See the comments in url_request.h tab_url = brave::BraveTabUrlWebContentsObserver:: GetTabURLFromRenderFrameInfo(render_process_id, render_frame_id, frame_tree_node_id).GetOrigin(); } return tab_url; } } // namespace bool ChromeNetworkDelegate::OnCanGetCookies(const net::URLRequest& request, const net::CookieList& cookie_list, bool allowed_from_caller) { // TODO(alexeyb): set cookie_settings_ for all requests if (allowed_from_caller && cookie_settings_) { GURL tab_url = GetTabUrl(&request); bool allowed_from_shields = cookie_settings_->IsCookieAccessAllowed( request.url(), tab_url); if (!allowed_from_shields) { return false; } } const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(&request); if (info) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&TabSpecificContentSettings::CookiesRead, info->GetWebContentsGetterForRequest(), request.url(), request.site_for_cookies(), cookie_list, !allowed_from_caller)); } return allowed_from_caller; } bool ChromeNetworkDelegate::OnCanSetCookie(const net::URLRequest& request, const net::CanonicalCookie& cookie, net::CookieOptions* options, bool allowed_from_caller) { // TODO(alexeyb): set cookie_settings_ for all requests if (allowed_from_caller && cookie_settings_) { GURL tab_url = GetTabUrl(&request); bool allowed_from_shields = cookie_settings_->IsCookieAccessAllowed( request.url(), tab_url); if (!allowed_from_shields) { return false; } } const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(&request); if (info) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&TabSpecificContentSettings::CookieChanged, info->GetWebContentsGetterForRequest(), request.url(), request.site_for_cookies(), cookie, !allowed_from_caller)); } return allowed_from_caller; } bool ChromeNetworkDelegate::OnCanAccessFile( const net::URLRequest& request, const base::FilePath& original_path, const base::FilePath& absolute_path) const { return IsAccessAllowed(original_path, absolute_path, profile_path_); } // static bool ChromeNetworkDelegate::IsAccessAllowed( const base::FilePath& path, const base::FilePath& profile_path) { return IsAccessAllowedInternal(path, profile_path); } // static bool ChromeNetworkDelegate::IsAccessAllowed( const base::FilePath& path, const base::FilePath& absolute_path, const base::FilePath& profile_path) { #if defined(OS_ANDROID) // Android's whitelist relies on symbolic links (ex. /sdcard is whitelisted // and commonly a symbolic link), thus do not check absolute paths. return IsAccessAllowedInternal(path, profile_path); #else return (IsAccessAllowedInternal(path, profile_path) && IsAccessAllowedInternal(absolute_path, profile_path)); #endif } // static void ChromeNetworkDelegate::EnableAccessToAllFilesForTesting(bool enabled) { g_access_to_all_files_enabled = enabled; } bool ChromeNetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader( const net::URLRequest& request, const GURL& target_url, const GURL& referrer_url) const { // These errors should be handled by the NetworkDelegate wrapper created by // the owning NetworkContext. NOTREACHED(); return true; } bool ChromeNetworkDelegate::OnCanQueueReportingReport( const url::Origin& origin) const { if (!cookie_settings_) return false; return cookie_settings_->IsCookieAccessAllowed(origin.GetURL(), origin.GetURL()); } void ChromeNetworkDelegate::OnCanSendReportingReports( std::set<url::Origin> origins, base::OnceCallback<void(std::set<url::Origin>)> result_callback) const { if (!reporting_permissions_checker_) { origins.clear(); std::move(result_callback).Run(std::move(origins)); return; } reporting_permissions_checker_->FilterReportingOrigins( std::move(origins), std::move(result_callback)); } bool ChromeNetworkDelegate::OnCanSetReportingClient( const url::Origin& origin, const GURL& endpoint) const { if (!cookie_settings_) return false; return cookie_settings_->IsCookieAccessAllowed(endpoint, origin.GetURL()); } bool ChromeNetworkDelegate::OnCanUseReportingClient( const url::Origin& origin, const GURL& endpoint) const { if (!cookie_settings_) return false; return cookie_settings_->IsCookieAccessAllowed(endpoint, origin.GetURL()); } bool ChromeNetworkDelegate::PendedRequestIsDestroyedOrCancelled(OnBeforeURLRequestContext* ctx, net::URLRequest* request) { if (ctx->pendingAtLeastOnce) { if ( !pending_requests_->IsPendingAndAlive(ctx->request_identifier) || request->status().status() == net::URLRequestStatus::CANCELED) { return true; } } return false; } void ChromeNetworkDelegate::ShouldBlockReferrer(std::shared_ptr<OnBeforeURLRequestContext> ctx, net::URLRequest* request) { /*if (!ctx || !request) { return; } GURL target_origin = GURL(request->url()).GetOrigin(); GURL tab_origin = request->site_for_cookies().GetOrigin(); bool allow_referrers = !ctx->isBlock3rdPartyCookies; bool shields_up = ctx->isGlobalBlockEnabled; std::string original_referrer(request->referrer()); content::Referrer new_referrer; if (net::blockers::BlockersWorker::ShouldSetReferrer(allow_referrers, shields_up, GURL(original_referrer), tab_origin, request->url(), target_origin, content::Referrer::NetReferrerPolicyToBlinkReferrerPolicy( request->referrer_policy()), &new_referrer)) { request->SetReferrer(new_referrer.url.spec()); }*/ }
[ "artem@brave.com" ]
artem@brave.com
a5e7ca50ca126f842df29b20f6f0059ac14b953e
470acbd6b3e1967186a4f66f2fad9e002d851e78
/deps/proxima/include/aitheta2/index_logger.h
ec1a0bc55b85d4a5eb51d771f1ded096a35387e1
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
chendianzhang/proximabilin
901d307efdc50815d3f3342215fd3463fce318ad
d539519d0c38aa07376746d473d45d3b8372b9f6
refs/heads/master
2023-09-04T11:45:53.194344
2021-11-02T02:27:12
2021-11-02T02:27:12
418,355,309
0
0
null
null
null
null
UTF-8
C++
false
false
4,878
h
/** * Copyright 2021 Alibaba, Inc. and its affiliates. 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. * \author Hechong.xyf * \date May 2018 * \brief Interface of AiTheta Index Logger */ #ifndef __AITHETA2_INDEX_LOGGER_H__ #define __AITHETA2_INDEX_LOGGER_H__ #include <cstdarg> #include <cstring> #include <memory> #include "index_module.h" #include "index_params.h" //! Log Debug Message #ifndef LOG_DEBUG #define LOG_DEBUG(format, ...) \ aitheta2::IndexLoggerBroker::Log(aitheta2::IndexLogger::LEVEL_DEBUG, \ __FILE__, __LINE__, format, ##__VA_ARGS__) #endif //! Log Information Message #ifndef LOG_INFO #define LOG_INFO(format, ...) \ aitheta2::IndexLoggerBroker::Log(aitheta2::IndexLogger::LEVEL_INFO, \ __FILE__, __LINE__, format, ##__VA_ARGS__) #endif //! Log Warn Message #ifndef LOG_WARN #define LOG_WARN(format, ...) \ aitheta2::IndexLoggerBroker::Log(aitheta2::IndexLogger::LEVEL_WARN, \ __FILE__, __LINE__, format, ##__VA_ARGS__) #endif //! Log Error Message #ifndef LOG_ERROR #define LOG_ERROR(format, ...) \ aitheta2::IndexLoggerBroker::Log(aitheta2::IndexLogger::LEVEL_ERROR, \ __FILE__, __LINE__, format, ##__VA_ARGS__) #endif //! Log Fatal Message #ifndef LOG_FATAL #define LOG_FATAL(format, ...) \ aitheta2::IndexLoggerBroker::Log(aitheta2::IndexLogger::LEVEL_FATAL, \ __FILE__, __LINE__, format, ##__VA_ARGS__) #endif namespace aitheta2 { /*! Index Logger */ struct IndexLogger : public IndexModule { //! Index Logger Pointer typedef std::shared_ptr<IndexLogger> Pointer; static const int LEVEL_DEBUG; static const int LEVEL_INFO; static const int LEVEL_WARN; static const int LEVEL_ERROR; static const int LEVEL_FATAL; //! Retrieve string of level static const char *LevelString(int level) { static const char *info[] = {"DEBUG", " INFO", " WARN", "ERROR", "FATAL"}; if (level < (int)(sizeof(info) / sizeof(info[0]))) { return info[level]; } return ""; } //! Retrieve symbol of level static char LevelSymbol(int level) { static const char info[5] = {'D', 'I', 'W', 'E', 'F'}; if (level < (int)(sizeof(info) / sizeof(info[0]))) { return info[level]; } return ' '; } //! Destructor virtual ~IndexLogger(void) {} //! Initialize Logger virtual int init(const IndexParams &params) = 0; //! Cleanup Logger virtual int cleanup(void) = 0; //! Log Message virtual void log(int level, const char *file, int line, const char *format, va_list args) = 0; }; /*! Index Logger Broker */ class IndexLoggerBroker { public: //! Register Logger static IndexLogger::Pointer Register(IndexLogger::Pointer logger) { IndexLogger::Pointer ret = std::move(logger_); logger_ = std::move(logger); return ret; } //! Register Logger with init params static int Register(IndexLogger::Pointer logger, const aitheta2::IndexParams &params) { //! Cleanup the previous, before initizlizing the new one if (logger_) { logger_->cleanup(); } logger_ = std::move(logger); return logger_->init(params); } //! Unregister Logger static void Unregister(void) { logger_ = nullptr; } //! Set Level of Logger static void SetLevel(int level) { logger_level_ = level; } //! Log Message __attribute__((format(printf, 4, 5))) static void Log( int level, const char *file, int line, const char *format, ...) { if (logger_level_ <= level && logger_) { va_list args; va_start(args, format); logger_->log(level, file, line, format, args); va_end(args); } } private: //! Disable them IndexLoggerBroker(void) = delete; IndexLoggerBroker(const IndexLoggerBroker &) = delete; IndexLoggerBroker(IndexLoggerBroker &&) = delete; //! Members static int logger_level_; static IndexLogger::Pointer logger_; }; } // namespace aitheta2 #endif // __AITHETA2_INDEX_LOGGER_H__
[ "hechong.xyf@alibaba-inc.com" ]
hechong.xyf@alibaba-inc.com
6ff7aceab19f6170f65df8e86014f6c105436efe
d0fb46aecc3b69983e7f6244331a81dff42d9595
/snsuapi/include/alibabacloud/snsuapi/model/BandStopSpeedUpResult.h
9466a17e019351a2c651389620ca4a2f85d4299c
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,536
h
/* * Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_SNSUAPI_MODEL_BANDSTOPSPEEDUPRESULT_H_ #define ALIBABACLOUD_SNSUAPI_MODEL_BANDSTOPSPEEDUPRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/snsuapi/SnsuapiExport.h> namespace AlibabaCloud { namespace Snsuapi { namespace Model { class ALIBABACLOUD_SNSUAPI_EXPORT BandStopSpeedUpResult : public ServiceResult { public: BandStopSpeedUpResult(); explicit BandStopSpeedUpResult(const std::string &payload); ~BandStopSpeedUpResult(); bool getResultModule()const; std::string getResultMessage()const; std::string getResultCode()const; protected: void parse(const std::string &payload); private: bool resultModule_; std::string resultMessage_; std::string resultCode_; }; } } } #endif // !ALIBABACLOUD_SNSUAPI_MODEL_BANDSTOPSPEEDUPRESULT_H_
[ "haowei.yao@alibaba-inc.com" ]
haowei.yao@alibaba-inc.com
954b926b2eb53d2651c7dc48baad5518c1195457
4c66fc839e375cdb2fc241c17a871e7e45009936
/libgestor/libgestor/libgestor.cpp
6321fbd0af77de1580158217734875fddf4c332e
[]
no_license
agluque62/svn-dev_ulises-sgm
2aa1fd1290be4139a248094b4ab1df71520206c7
3c5396c69f5b7250a55d7656cd6de52427734521
refs/heads/master
2022-07-08T20:20:23.944418
2021-09-02T11:12:46
2021-09-02T11:12:46
235,992,912
0
0
null
2021-01-29T20:44:59
2020-01-24T11:45:35
JavaScript
UTF-8
C++
false
false
13,594
cpp
// This is the main DLL file. // This is the main DLL file. #ifdef WIN32 #include "libgestor.h" #else #include <poll.h> #include "gestor.h" #endif namespace libgestor { #define TIEMPO_POLLING 20000 #define MAX_POLLING_SIN_RESPUESTA 3 void callback(int reason,Snmp *snmp,Pdu &pdu,SnmpTarget &target,void *cd); void callback1(int reason,Snmp *snmp,Pdu &pdu,SnmpTarget &target,void *cd); void callbackpolling(int reason,Snmp *snmp,Pdu &pdu,SnmpTarget &target,void *cd); #ifdef WIN32 int Gestor_Terminal(void *ptr) #else void *Gestor_Terminal(void *ptr) #endif { Def_Gestor_Terminal *gtr_term=(Def_Gestor_Terminal *)ptr; const int INTERVALO=1000; // intervalo en ms // Para Windows Snmp::socket_startup(); UdpAddress address(gtr_term->dirip_agente); address.set_port(gtr_term->puerto); CTarget ctarget(address); ctarget.set_version(version2c); gtr_term->mictarget=&ctarget; gtr_term->Inicializa(); // datos para respuestas asincronas int nfds; fd_set fdr,fdw,fde; struct timeval timeout; timeout.tv_sec=0; //timeout.tv_usec=50000; timeout.tv_usec=INTERVALO*1000; while(1) { // Siempre que no haya sesion trata de establecerla if (!gtr_term->misnmp) { printf("Trata de establecer sesion\n"); gtr_term->Inicializa(); } // Tratamiento de polling (solo entrara aqui si no se reciben traps // ni respuestas a solicitudes) if (gtr_term->t_rx>=TIEMPO_POLLING) { printf("Pide estado TOP\n"); // Pide estado TOP, siempre que haya sesion gtr_term->Polling(); gtr_term->t_rx=0; } // Configura la espera de respuestas/traps gtr_term->misnmp->eventListHolder->SNMPGetFdSets(nfds,fdr,fdw,fde); struct timeval timeout_int=timeout; if (select(nfds,&fdr,NULL,NULL,&timeout_int)!=0) gtr_term->misnmp->eventListHolder->SNMPProcessPendingEvents(); #ifdef WIN32 Sleep(INTERVALO); #endif gtr_term->t_rx+=INTERVALO; } // Para Windows Snmp::socket_cleanup(); } Def_Gestor_Terminal::Def_Gestor_Terminal( char *recurso_in, char *dirip_agente_in, int puerto_in, char *dirip_gestor_in, int puerto_traps_in, char *oidRaiz_in, char *oidMax_in, char *oidPolling_in, #ifdef WIN32 void *(*Funcion_Aviso)(bool,String ^,int,array<Def_Dato ^> ^) #else void *(*Funcion_Aviso)(bool,char *,int,Def_Dato *) #endif ) { misnmp=NULL; mictarget=NULL; strcpy(recurso,recurso_in); strcpy(dirip_agente,dirip_agente_in); strcpy(dirip_gestor,dirip_gestor_in); puerto=puerto_in; puerto_traps=puerto_traps_in; strcpy(oidRaiz,oidRaiz_in); strcpy(oidMax,oidMax_in); strcpy(oidPolling,oidPolling_in); t_rx=0; cont_polling=0; conectado=FALSE; Aviso=Funcion_Aviso; // Aqui deberia lanzar hilo que se encargara de interrogar peridicamente // al agente para determinar si aun sigue vivo #ifdef WIN32 DWORD tid; res=0; if (CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&Gestor_Terminal,this,0,&tid)==NULL) { res=-1; return; } #else pthread_t tid; res=pthread_create(&tid,NULL,Gestor_Terminal,this); if (res==0) pthread_detach(tid); #endif #ifdef WIN32 Sleep(1000); #else poll(NULL,0,50); #endif if (status!=SNMP_CLASS_SUCCESS) res=-1; } void Def_Gestor_Terminal::Inicializa() { misnmp=new Snmp(status); if (status!=SNMP_CLASS_SUCCESS) { misnmp=NULL; return; } #ifdef WIN32 Sleep(10000); #endif // PARA RECOGER TRAPS if (puerto_traps>0) { misnmp->notify_set_listen_port(puerto_traps); OidCollection coloids; TargetCollection coltargets; misnmp->notify_register(coloids,coltargets,callback,this); // Indica al agente que quiere recoger traps Traps(TRUE); } Inicializa_Datos(); } void Def_Gestor_Terminal::Inicializa_Datos() { // Lee todas las variables del terminal Pdu pdu; Vb vb; vb.set_oid(oidRaiz); pdu+=vb; // Para preguntar de forma asincrona (es la libreria la que // controla) // Manda como argumento la propia estructura del gestor int res1=misnmp->get_bulk(pdu,*mictarget,0,50,callback,this); if (res1!=SNMP_CLASS_SUCCESS) printf("Error en GET ASINC%s\n",misnmp->error_msg(status)); } void Def_Gestor_Terminal::Polling() { if (!misnmp) return; // Control de polling enviados sin respuesta (ya que cada vez que se RX // una se resetea contador) if (++cont_polling>MAX_POLLING_SIN_RESPUESTA) { // Si cambia estado de conexion con agente anota y avisa if (conectado) { conectado=FALSE; if (Aviso) { #ifdef WIN32 String ^srecurso=gcnew String(recurso); Aviso(conectado,srecurso,0,nullptr); #else Aviso(conectado,recurso,0,NULL); #endif } } cont_polling=0; } // Genera y envia solicitud del estado del TOP para el agente Pdu pdu; Vb vb; vb.set_oid(oidPolling); pdu+=vb; // Para preguntar de forma asincrona (es la libreria la que // controla) // Manda como argumento la propia estructura del gestor int res1=misnmp->get(pdu,*mictarget,callbackpolling,this); if (res1!=SNMP_CLASS_SUCCESS) printf("Error en GET ASINC%s\n",misnmp->error_msg(res)); } void Def_Gestor_Terminal::Traps(bool suscripcion) { if (!misnmp) return; Pdu pdu; Vb vb; char cadena[50]; sprintf(cadena,"%s/%d",dirip_gestor,puerto_traps); vb.set_oid(oidDirTraps); vb.set_syntax(sNMP_SYNTAX_OCTETS); OctetStr octetstr(cadena); vb.set_value(octetstr); pdu+=vb; vb.set_oid(oidTraps); vb.set_syntax(sNMP_SYNTAX_INT); vb.set_value((long)suscripcion); pdu+=vb; // Para preguntar de forma asincrona (es la libreria la que // controla) // Manda como argumento la propia estructura del gestor // Lo hace sincrono ya que no interesa la respuesta que no se va // a comunicar al padre #ifndef WIN32 int res=misnmp->set(pdu,*mictarget,callback1,this); #else int res1=misnmp->set(pdu,*mictarget); #endif if (res1!=SNMP_CLASS_SUCCESS) printf("Error en SET ASINC%s\n",misnmp->error_msg(res)); } #ifdef WIN32 using namespace System::Runtime::InteropServices; void Def_Gestor_Terminal::Cambia(int num,array<Def_Dato ^> ^datos) #else void Def_Gestor_Terminal::Cambia(int num,Def_Dato *datos) #endif { if (!misnmp) return; Pdu pdu; Vb vb; for (int i=0;i<num;i++) { #ifdef WIN32 char *cadena_oid=(char *)(void *)Marshal::StringToHGlobalAnsi(datos[i]->oid); vb.set_oid(cadena_oid); Marshal::FreeHGlobal((System::IntPtr)cadena_oid); if (datos[i]->cadena) { vb.set_syntax(sNMP_SYNTAX_OCTETS); char *cadena_cadena=(char *)(void *)Marshal::StringToHGlobalAnsi(datos[i]->cadena); OctetStr octetstr(cadena_cadena); vb.set_value(octetstr); Marshal::FreeHGlobal((System::IntPtr)cadena_cadena); } else { vb.set_syntax(sNMP_SYNTAX_INT); vb.set_value((long)datos[i]->valor); } #else vb.set_oid(datos[i].oid); vb.set_syntax(sNMP_SYNTAX_OCTETS); if (datos[i].cadena) { OctetStr octetstr(datos[i].cadena); vb.set_value(octetstr); } else { vb.set_syntax(sNMP_SYNTAX_INT); vb.set_value((long)datos[i].valor); } #endif pdu+=vb; } // Manda como argumento la propia estructura del gestor // Lo hace sincrono, ya que el cambio llegara por trap que mande agente // y si no se hace asi llegaria dos veces #ifndef WIN32 int res1=misnmp->set(pdu,*mictarget,callback1,this); #else int res1=misnmp->set(pdu,*mictarget); #endif if (res1!=SNMP_CLASS_SUCCESS) printf("Error en SET SINC%s\n",misnmp->error_msg(res)); } Def_Gestor_Terminal::~Def_Gestor_Terminal() { Snmp::socket_cleanup(); } void callback(int reason,Snmp *snmp,Pdu &pdu,SnmpTarget &target,void *cd) { Def_Gestor_Terminal *gtr_term=(Def_Gestor_Terminal *)cd; if (reason==SNMP_CLASS_TIMEOUT) return; if (reason==SNMP_CLASS_SESSION_DESTROYED) { // OJOOOOO Tiene que informar al padre de este cambio printf("FIN SESION\n"); gtr_term->misnmp=NULL; return; } // Ha recibido algo por lo que inicializa y si estaba desconectado // anota nuevo estado y avisa del cambio gtr_term->t_rx=0; gtr_term->cont_polling=0; if (!gtr_term->conectado) { gtr_term->conectado=TRUE; // Indica al agente que quiere rx traps y sus datos gtr_term->Traps(TRUE); // Solicita de nuevo todos los datos del terminal gtr_term->Inicializa_Datos(); if (gtr_term->Aviso) { #ifdef WIN32 String ^recurso=gcnew String(gtr_term->recurso); gtr_term->Aviso(gtr_term->conectado,recurso,0,nullptr); #else gtr_term->Aviso(gtr_term->conectado,gtr_term->recurso,0,NULL); #endif } } #ifdef WIN32 array<Def_Dato ^> ^datos=gcnew array<Def_Dato ^>(pdu.get_vb_count()); #else Def_Dato *datos=new Def_Dato[pdu.get_vb_count()]; #endif int ind=0; Vb vb; Oid oidraiz(gtr_term->oidRaiz); Oid oidmax(gtr_term->oidMax); for (int i=0;i<pdu.get_vb_count();i++) { #ifdef WIN32 datos[ind]=gcnew Def_Dato(); #endif pdu.get_vb(vb,i); Oid oid=vb.get_oid(); // Solo se ocupa de los de MIB de terminales que no sean de tipo // interno if (oid.nCompare(oidraiz.len(),oidraiz)==0 && oid.nCompare(oidmax.len(),oidmax)<0) { printf("%s OID %s VALOR %s\n", reason==SNMP_CLASS_NOTIFICATION ? "TRAP" : "RESPUESTA", vb.get_printable_oid(), vb.get_printable_value()); if (!vb.get_printable_value()) continue; #ifdef WIN32 datos[ind]->oid=gcnew String(vb.get_printable_oid()); #else datos[ind].oid=new char[strlen(vb.get_printable_oid())+1]; strcpy(datos[ind].oid,vb.get_printable_oid()); #endif SmiUINT32 tipo=vb.get_syntax(); if (tipo==sNMP_SYNTAX_OCTETS) { #ifdef WIN32 datos[ind++]->cadena=gcnew String(vb.get_printable_value()); #else datos[ind].cadena=new char[strlen(vb.get_printable_value())+1]; strcpy(datos[ind++].cadena,vb.get_printable_value()); #endif } else if (tipo==sNMP_SYNTAX_INT) { int valor; vb.get_value(valor); #ifdef WIN32 datos[ind++]->valor=valor; #else datos[ind++].valor=valor; #endif } else if (tipo==sNMP_SYNTAX_TIMETICKS) { unsigned long valor; vb.get_value(valor); #ifdef WIN32 datos[ind]->cadena=gcnew String(vb.get_printable_value()); datos[ind++]->valor=valor; #else datos[ind].cadena=new char[strlen(vb.get_printable_value())+1]; strcpy(datos[ind].cadena,vb.get_printable_value()); datos[ind++].valor=valor; #endif } } else printf("OTROOOO OID %s VALOR %s\n",vb.get_printable_oid(),vb.get_printable_value()); } if (gtr_term->Aviso && ind>0) { #ifdef WIN32 String ^recurso=gcnew String(gtr_term->recurso); gtr_term->Aviso(gtr_term->conectado,recurso,ind,datos); #else gtr_term->Aviso(gtr_term->conectado,gtr_term->recurso,ind,datos); #endif } #ifndef WIN32 else delete []datos; #endif } // Para respuestas a set ( no tiene que avisar a nadie, ya que el cambio de // estado llegara por trap=>llamada a callback) // Solo sirven para determinar que sigue vivo agente void callback1(int reason,Snmp *snmp,Pdu &pdu,SnmpTarget &target,void *cd) { Def_Gestor_Terminal *gtr_term=(Def_Gestor_Terminal *)cd; if (reason==SNMP_CLASS_TIMEOUT) return; if (reason==SNMP_CLASS_SESSION_DESTROYED) { // OJOOOOO Tiene que informar al padre de este cambio printf("FIN SESION\n"); gtr_term->misnmp=NULL; return; } // Ha recibido algo por lo que inicializa y si estaba desconectado // anota nuevo estado y avisa del cambio gtr_term->t_rx=0; gtr_term->cont_polling=0; if (!gtr_term->conectado) { gtr_term->conectado=TRUE; // Indica al agente que quiere rx traps y sus datos gtr_term->Traps(TRUE); // Solicita de nuevo todos los datos del agente gtr_term->Inicializa_Datos(); if (gtr_term->Aviso) { #ifdef WIN32 String ^recurso=gcnew String(gtr_term->recurso); gtr_term->Aviso(gtr_term->conectado,recurso,0,nullptr); #else gtr_term->Aviso(gtr_term->conectado,gtr_term->recurso,0,NULL); #endif } } } void callbackpolling(int reason,Snmp *snmp,Pdu &pdu,SnmpTarget &target,void *cd) { Def_Gestor_Terminal *gtr_term=(Def_Gestor_Terminal *)cd; static int valorpolling=-1; if (reason==SNMP_CLASS_TIMEOUT) return; if (reason==SNMP_CLASS_SESSION_DESTROYED) { // OJOOOOO Tiene que informar al padre de este cambio printf("FIN SESION\n"); gtr_term->misnmp=NULL; return; } Vb vb; pdu.get_vb(vb,0); if (!vb.get_printable_value()) printf("RESPONDE MAL\n"); // Ha recibido algo por lo que inicializa y si estaba desconectado // anota nuevo estado y avisa del cambio gtr_term->t_rx=0; gtr_term->cont_polling=0; if (!gtr_term->conectado) { gtr_term->conectado=TRUE; // Indica al agente que quiere rx traps y sus datos gtr_term->Traps(TRUE); // Solicita de nuevo todos los datos del terminal gtr_term->Inicializa_Datos(); if (gtr_term->Aviso) { #ifdef WIN32 String ^recurso=gcnew String(gtr_term->recurso); gtr_term->Aviso(gtr_term->conectado,recurso,0,nullptr); #else gtr_term->Aviso(gtr_term->conectado,gtr_term->recurso,0,NULL); #endif } } #ifdef WIN32 array<Def_Dato ^> ^datos=gcnew array<Def_Dato ^>(1); #else Def_Dato *datos=new Def_Dato[1]; #endif int ind=0; #ifdef WIN32 datos[ind]=gcnew Def_Dato(); #endif pdu.get_vb(vb,0); if (vb.get_printable_value()) { int valor; vb.get_value(valor); if (valor!=valorpolling) { valorpolling=valor; #ifdef WIN32 datos[ind]->oid=gcnew String(vb.get_printable_oid()); datos[ind++]->valor=valor; #else datos[ind].oid=new char[strlen(vb.get_printable_oid())+1]; strcpy(datos[ind].oid,vb.get_printable_oid()); datos[ind++].valor=valor; #endif } } if (gtr_term->Aviso && ind>0) { #ifdef WIN32 String ^recurso=gcnew String(gtr_term->recurso); gtr_term->Aviso(gtr_term->conectado,recurso,ind,datos); #else gtr_term->Aviso(gtr_term->conectado,gtr_term->recurso,ind,datos); #endif } #ifndef WIN32 else delete []datos; #endif } } // fin namespace libgestor
[ "arturo.garcia.luque@gmail.com" ]
arturo.garcia.luque@gmail.com
3e3d2d9355d5906f486e0039cbb32b137c0e9604
bd97e81281b55b7ae2c2d64c1855a86c1b769f78
/chipannotator.cpp
27496c66f2f5ef9b61c23c266403f4d46388e2db
[]
no_license
WuFan1992/ChipAnnotator
51809b6bb06c2c851b22a65143dfcc98a1da7a5d
1d646a711e7ddcb4290648de0d9ef7d874b6158d
refs/heads/master
2021-08-12T08:26:01.015692
2017-11-14T16:00:03
2017-11-14T16:00:03
109,732,084
0
0
null
null
null
null
UTF-8
C++
false
false
11,639
cpp
#include "chipannotator.h" #include <QStatusBar> #include <QCloseEvent> #include <QFileDialog> #include <QMenuBar> #include <QMessageBox> #include <QMouseEvent> #include <QPointF> #include <QDebug> #include <QString> #include <QDataStream> #include <QList> #define TOTAL_TYPE 18 ChipAnnotator::ChipAnnotator(QWidget* parent) { setAnnotatorScene(); setAnnotatorView(); layout = new QHBoxLayout; layout->addWidget(m_annotaview); m_colorlayout = new ColorLayout; Utils::preColorLayout(m_annotateur,m_colorlayout); mouseActionControle(); //connect(m_annotateur, &MainWindow::modified, this, &MainWindow::onAnnotationModified); prePaintGrid(); connect (m_annotateur,&AnnotatorScene::gridOn,this,&ChipAnnotator::PaintGrid); connect(m_annotateur,&AnnotatorScene::annotationSignal,this,&ChipAnnotator::showAnnotation); } void ChipAnnotator::setAnnotatorScene() { m_annotateur = new AnnotatorScene; m_annotateur->setSceneRect(QRectF(0, 0, 800, 564)); } void ChipAnnotator::setAnnotatorView() { m_annotaview = new AnnotatorView(m_annotateur); m_annotaview->fitInView(0,0,800,564); m_annotaview->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); } void ChipAnnotator::mouseActionControle() { connect(m_annotaview,&AnnotatorView::mouseMoveSignal,this,&ChipAnnotator::mouseMoveFunction); connect(m_annotaview,&AnnotatorView::mousePressSignal,this,&ChipAnnotator::mousePressFunction); connect(m_annotaview,&AnnotatorView::mouseReleaseSignal,this,&ChipAnnotator::mouseReleaseFunction); connect(m_annotaview,&AnnotatorView::leaveView,this,&ChipAnnotator::leaveViewFunction); } void ChipAnnotator::mouseMoveFunction( boost::optional<AnnotatorScene::Region> m_current_region) { if (m_annotateur->m_current_class ==0) { if((m_current_region->x()< AnnotatorScene::c_annotation_resolution.width())&&(m_current_region->x()>0)&& (m_current_region->y()> 0)&& (m_current_region->y()< AnnotatorScene::c_annotation_resolution.height())) { m_colorlayout->RAS.at(m_annotaview->m_previous_region->y()* m_annotateur->m_result->width()+m_annotaview->m_previous_region->x())->setVisible(false); m_colorlayout->RAS.at(m_current_region->y()* m_annotateur->m_result->width()+m_current_region->x())->setVisible(true); showRectType(m_current_region); m_annotaview->m_previous_region = m_current_region; } } if(m_annotaview->m_current_button_pressed) processClick(*m_current_region); update(); } void ChipAnnotator::mousePressFunction(AnnotatorScene::Region mousePressPos) { processClick(mousePressPos); } void ChipAnnotator::mouseReleaseFunction(AnnotatorScene::Region mouseReleasePos) { processClick(mouseReleasePos); } void ChipAnnotator::leaveViewFunction() { m_colorlayout->RAS.at(m_annotaview->m_previous_region->y()* m_annotateur->m_result->width()+m_annotaview->m_previous_region->x())->setVisible(false); } void ChipAnnotator::processClick(const AnnotatorScene::Region& pos) { m_colorlayout->RAS.at(m_annotaview->m_previous_region->y()* m_annotateur->m_result->width()+m_annotaview->m_previous_region->x())->setVisible(false); assert(m_annotaview->m_current_button_pressed); switch(*m_annotaview->m_current_button_pressed) { case AnnotatorView::Button::Left: tagRegion(pos); return; case AnnotatorView::Button::Right: tagRegion(pos, 0); return; /* case Button::Wheel: const auto class_id = classAtPosition(*m_current_region); emit selectClass(class_id); return; */ } } void ChipAnnotator::tagRegion(const AnnotatorScene::Region& region, boost::optional<quint8> classes) { if(!classes) { classes = m_annotateur->m_current_class; if(region.x() >= 0 && region.x() < m_annotateur->m_result->width() && region.y() >= 0 && region.y() < m_annotateur->m_result->height()) { if (*classes !=0) {for (int i= 0 ;i<*classes-1;i++) m_colorlayout->TotalList.at(i).at(region.y()* m_annotateur->m_result->width()+region.x())->setVisible(false); for (int j= *classes;j<TOTAL_TYPE;j++) m_colorlayout->TotalList.at(j).at(region.y()* m_annotateur->m_result->width()+region.x())->setVisible(false); m_colorlayout->TotalList.at(*classes-1).at(region.y()* m_annotateur->m_result->width()+region.x())->setVisible(true); emit modified(); } } } else { if(region.x() >= 0 && region.x() < m_annotateur->m_result->width() && region.y() >= 0 && region.y() < m_annotateur->m_result->height()) { for (int k = 0; k<TOTAL_TYPE;k++) m_colorlayout->TotalList.at(k).at(region.y()* m_annotateur->m_result->width()+region.x())->setVisible(false); emit modified(); } } } void ChipAnnotator::showAnnotation(bool m_display_annotation) { int RectIndex; if(m_display_annotation) { QFile file("temp.dat"); file.open(QIODevice::WriteOnly); QDataStream out(&file); for(int y=0;y<AnnotatorScene::c_annotation_resolution.height();y++) { for(int x=0;x<AnnotatorScene::c_annotation_resolution.width();x++) { RectIndex =0; for (int i = 0; i<TOTAL_TYPE; i++) { bool ifvisible=m_colorlayout->TotalList.at(i).at(y*m_annotateur->c_annotation_resolution.width()+x)->isVisible(); if(ifvisible) {RectIndex = i+1; m_colorlayout->TotalList.at(i).at(y*m_annotateur->c_annotation_resolution.width()+x)->setVisible(false); } } out <<QString("x"); out<<(qint32)x; out<<QString("y"); out<<(qint32)y; out<<QString("RectType"); out<<RectIndex; } } file.close(); } else { QFile file("temp.dat"); file.open(QIODevice::ReadOnly); QDataStream in(&file); QString str_x,str_y,str_rectindex; qint32 rectindex; for(qint32 y=0;y<AnnotatorScene::c_annotation_resolution.height();y++) { for(qint32 x=0;x<AnnotatorScene::c_annotation_resolution.width();x++) { in>>str_x>>x>>str_y>>y>>str_rectindex>>rectindex; if(rectindex!=0) m_colorlayout->TotalList.at(rectindex-1).at(y*m_annotateur->c_annotation_resolution.width()+x)->setVisible(true); } } file.close(); } } void ChipAnnotator::displayAnnotation(QString &annoation) { if(!annoation.isEmpty()) { auto output_file_path = annoation; QFile file(output_file_path); file.open(QIODevice::ReadOnly); QDataStream in(&file); QString str_x,str_y,str_rectindex; qint32 rectindex; for(qint32 y=0;y<AnnotatorScene::c_annotation_resolution.height();y++) { for(qint32 x=0;x<AnnotatorScene::c_annotation_resolution.width();x++) { in>>str_x>>x>>str_y>>y>>str_rectindex>>rectindex; if(rectindex!=0) m_colorlayout->TotalList.at(rectindex-1).at(y*m_annotateur->c_annotation_resolution.width()+x)->setVisible(true); } } } } void ChipAnnotator::displayGrid() { for (int x = 0; x < AnnotatorScene::c_annotation_resolution.width();x++) m_horizonline_list.at(x)->setVisible(true); for (int y = 0; y < AnnotatorScene::c_annotation_resolution.height();y++) m_verticalline_list.at(y)->setVisible(true); } void ChipAnnotator::prePaintGrid() { int block_width = AnnotatorScene::c_image_resolution.width()/AnnotatorScene::c_annotation_resolution.width(); int block_height = AnnotatorScene::c_image_resolution.height()/AnnotatorScene::c_annotation_resolution.height(); for (int x = 0; x < AnnotatorScene::c_annotation_resolution.width();x++) { QGraphicsLineItem *horizon_line = m_annotateur->addLine((x+1)*block_width,0,(x+1)*block_width,AnnotatorScene::c_image_resolution.height(),QPen(QColor(255,0,0))); m_horizonline_list.append(horizon_line); horizon_line->setVisible(false); } for (int y = 0; y < AnnotatorScene::c_annotation_resolution.height();y++) { QGraphicsLineItem *vertical_line = m_annotateur->addLine(0,(y+1)*block_height,AnnotatorScene::c_image_resolution.width(),(y+1)*block_height,QPen(QColor(255,0,0))); m_verticalline_list.append(vertical_line); vertical_line->setVisible(false); } } void ChipAnnotator::Reset() { for(int y=0;y<AnnotatorScene::c_annotation_resolution.height();y++) { for(int x=0;x<AnnotatorScene::c_annotation_resolution.width();x++) { for (int i = 0; i<TOTAL_TYPE; i++) { m_colorlayout->TotalList.at(i).at(y*m_annotateur->c_annotation_resolution.width()+x)->setVisible(false); } } } } bool ChipAnnotator::hasImagesLoaded() const { return m_annotateur->m_images.size() == 3 && !m_annotateur->m_images.front().isNull(); } quint8 ChipAnnotator::classAtPosition(const AnnotatorScene::Region& pos) const { return qRed(m_annotateur->m_result->toImage().pixel(pos.x(), pos.y())); ; } void ChipAnnotator::PaintGrid(bool m_display_grid) { for (int x = 0; x < AnnotatorScene::c_annotation_resolution.width();x++) m_horizonline_list.at(x)->setVisible(!m_display_grid); for (int y = 0; y < AnnotatorScene::c_annotation_resolution.height();y++) m_verticalline_list.at(y)->setVisible(!m_display_grid); update(); } void ChipAnnotator::sceneScaleChanged(const QString &scale) { double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100.0; QMatrix oldMatrix = m_annotaview->matrix(); m_annotaview->resetMatrix(); m_annotaview->translate(oldMatrix.dx(), oldMatrix.dy()); m_annotaview->scale(newScale, newScale); } void ChipAnnotator::saveAnnotation(QString& output_file_path) { int RectIndex; QFile file(output_file_path); file.open(QIODevice::WriteOnly); QDataStream out(&file); for(int y=0;y<AnnotatorScene::c_annotation_resolution.height();y++) { for(int x=0;x<AnnotatorScene::c_annotation_resolution.width();x++) { RectIndex =0; for (int i = 0; i<TOTAL_TYPE; i++) { bool ifvisible=m_colorlayout->TotalList.at(i).at(y*m_annotateur->c_annotation_resolution.width()+x)->isVisible(); if(ifvisible) {RectIndex = i+1; } } out <<QString("x"); out<<(qint32)x; out<<QString("y"); out<<(qint32)y; out<<QString("RectType"); out<<RectIndex; } } file.close(); } void ChipAnnotator::showRectType(boost::optional<AnnotatorScene::Region> m_current_region) { //auto* b = statusBar(); for (int k = 0; k<TOTAL_TYPE;k++) {bool visible =m_colorlayout->TotalList.at(k).at(m_current_region->y()* m_annotateur->m_result->width()+m_current_region->x())->isVisible(); if (visible) { // b->showMessage(Classes::s_classes.at(k+1).name()); emit statusType(Classes::s_classes.at(k+1).name()); return; } } //b->showMessage("RAS"); emit statusType("RAS"); }
[ "fanwuchine@gmail.com" ]
fanwuchine@gmail.com
b9178213a669e9e601e4f64c11df3192ea7b962e
26d0ef40085d17454242606a03b308a14ac29312
/wrapper/CSharp/CsPipelineLayoutFlags.h
59940a6e668c2392b8db8c9e144991a17c998334
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Krypton-Dev/LLGL
1c21bc663a710d8bde48873ea581d51f957d75a1
b1817bea26b81d26246a6e840caaecf839ace573
refs/heads/master
2020-07-24T06:01:34.671771
2019-09-10T01:51:29
2019-09-10T01:51:29
207,821,662
0
0
NOASSERTION
2019-09-11T13:38:55
2019-09-11T13:38:54
null
UTF-8
C++
false
false
1,397
h
/* * CsPipelineLayoutFlags.h * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #pragma once #include <vcclr.h> #include "CsRenderSystemChilds.h" #include "CsShaderFlags.h" #using <System.dll> #using <System.Core.dll> #using <System.Runtime.InteropServices.dll> namespace SharpLLGL { /* ----- Structures ----- */ public ref class BindingDescriptor { public: BindingDescriptor(); BindingDescriptor(ResourceType type, BindFlags bindFlags, StageFlags stageFlags, unsigned int slot); BindingDescriptor(ResourceType type, BindFlags bindFlags, StageFlags stageFlags, unsigned int slot, unsigned int arraySize); BindingDescriptor(ResourceType type, BindFlags bindFlags, StageFlags stageFlags, unsigned int slot, unsigned int arraySize, String^ name); property ResourceType Type; property BindFlags BindFlags; property StageFlags StageFlags; property unsigned int Slot; property unsigned int ArraySize; property String^ Name; }; public ref class PipelineLayoutDescriptor { public: PipelineLayoutDescriptor(); property List<BindingDescriptor^>^ Bindings; }; } // /namespace SharpLLGL // ================================================================================
[ "lukas.hermanns90@gmail.com" ]
lukas.hermanns90@gmail.com
b93a7b098ae559f47d2868f35139b1c20cca730a
83a39153b29b5cc056992e2bbee86c27e25cedf9
/scintilla/win32/PlatWin.cxx
1f8981507d9d38c7d655f89c0625ec12004fedcf
[ "LicenseRef-scancode-scintilla" ]
permissive
Loreia/UDL2
474d150145300b43d90fb6a4968769d75d2755b2
3f866b9683090d76ffa03f85e87989ba11112f14
refs/heads/master
2016-09-05T20:49:28.202215
2012-10-17T13:25:23
2012-10-17T13:25:23
3,355,994
2
0
null
null
null
null
UTF-8
C++
false
false
67,614
cxx
// Scintilla source code edit control /** @file PlatWin.cxx ** Implementation of platform facilities on Windows. **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <time.h> #include <limits.h> #undef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #include <windows.h> #include <commctrl.h> #include <richedit.h> #include <windowsx.h> #include "Platform.h" #include "UniConversion.h" #include "XPM.h" #include "FontQuality.h" // We want to use multi monitor functions, but via LoadLibrary etc // Luckily microsoft has done the heavy lifting for us, so we'll just use their stub functions! #if defined(_MSC_VER) && (_MSC_VER > 1200) #define COMPILE_MULTIMON_STUBS #include <MultiMon.h> #endif #ifndef IDC_HAND #define IDC_HAND MAKEINTRESOURCE(32649) #endif // Take care of 32/64 bit pointers #ifdef GetWindowLongPtr static void *PointerFromWindow(HWND hWnd) { return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0)); } static void SetWindowPointer(HWND hWnd, void *ptr) { ::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr)); } #else static void *PointerFromWindow(HWND hWnd) { return reinterpret_cast<void *>(::GetWindowLong(hWnd, 0)); } static void SetWindowPointer(HWND hWnd, void *ptr) { ::SetWindowLong(hWnd, 0, reinterpret_cast<LONG>(ptr)); } #ifndef GWLP_USERDATA #define GWLP_USERDATA GWL_USERDATA #endif #ifndef GWLP_WNDPROC #define GWLP_WNDPROC GWL_WNDPROC #endif #ifndef LONG_PTR #define LONG_PTR LONG #endif static LONG_PTR SetWindowLongPtr(HWND hWnd, int nIndex, LONG_PTR dwNewLong) { return ::SetWindowLong(hWnd, nIndex, dwNewLong); } static LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex) { return ::GetWindowLong(hWnd, nIndex); } #endif typedef BOOL (WINAPI *AlphaBlendSig)(HDC, int, int, int, int, HDC, int, int, int, int, BLENDFUNCTION); static CRITICAL_SECTION crPlatformLock; static HINSTANCE hinstPlatformRes = 0; static bool onNT = false; static HMODULE hDLLImage = 0; static AlphaBlendSig AlphaBlendFn = 0; static HCURSOR reverseArrowCursor = NULL; bool IsNT() { return onNT; } #ifdef SCI_NAMESPACE using namespace Scintilla; #endif Point Point::FromLong(long lpoint) { return Point(static_cast<short>(LOWORD(lpoint)), static_cast<short>(HIWORD(lpoint))); } static RECT RectFromPRectangle(PRectangle prc) { RECT rc = {prc.left, prc.top, prc.right, prc.bottom}; return rc; } Palette::Palette() { used = 0; allowRealization = false; hpal = 0; size = 100; entries = new ColourPair[size]; } Palette::~Palette() { Release(); delete []entries; entries = 0; } void Palette::Release() { used = 0; if (hpal) ::DeleteObject(hpal); hpal = 0; delete []entries; size = 100; entries = new ColourPair[size]; } /** * This method either adds a colour to the list of wanted colours (want==true) * or retrieves the allocated colour back to the ColourPair. * This is one method to make it easier to keep the code for wanting and retrieving in sync. */ void Palette::WantFind(ColourPair &cp, bool want) { if (want) { for (int i=0; i < used; i++) { if (entries[i].desired == cp.desired) return; } if (used >= size) { int sizeNew = size * 2; ColourPair *entriesNew = new ColourPair[sizeNew]; for (int j=0; j<size; j++) { entriesNew[j] = entries[j]; } delete []entries; entries = entriesNew; size = sizeNew; } entries[used].desired = cp.desired; entries[used].allocated.Set(cp.desired.AsLong()); used++; } else { for (int i=0; i < used; i++) { if (entries[i].desired == cp.desired) { cp.allocated = entries[i].allocated; return; } } cp.allocated.Set(cp.desired.AsLong()); } } void Palette::Allocate(Window &) { if (hpal) ::DeleteObject(hpal); hpal = 0; if (allowRealization) { char *pal = new char[sizeof(LOGPALETTE) + (used-1) * sizeof(PALETTEENTRY)]; LOGPALETTE *logpal = reinterpret_cast<LOGPALETTE *>(pal); logpal->palVersion = 0x300; logpal->palNumEntries = static_cast<WORD>(used); for (int iPal=0;iPal<used;iPal++) { ColourDesired desired = entries[iPal].desired; logpal->palPalEntry[iPal].peRed = static_cast<BYTE>(desired.GetRed()); logpal->palPalEntry[iPal].peGreen = static_cast<BYTE>(desired.GetGreen()); logpal->palPalEntry[iPal].peBlue = static_cast<BYTE>(desired.GetBlue()); entries[iPal].allocated.Set( PALETTERGB(desired.GetRed(), desired.GetGreen(), desired.GetBlue())); // PC_NOCOLLAPSE means exact colours allocated even when in background this means other windows // are less likely to get their colours and also flashes more when switching windows logpal->palPalEntry[iPal].peFlags = PC_NOCOLLAPSE; // 0 allows approximate colours when in background, yielding moe colours to other windows //logpal->palPalEntry[iPal].peFlags = 0; } hpal = ::CreatePalette(logpal); delete []pal; } } #ifndef CLEARTYPE_QUALITY #define CLEARTYPE_QUALITY 5 #endif static BYTE Win32MapFontQuality(int extraFontFlag) { switch (extraFontFlag & SC_EFF_QUALITY_MASK) { case SC_EFF_QUALITY_NON_ANTIALIASED: return NONANTIALIASED_QUALITY; case SC_EFF_QUALITY_ANTIALIASED: return ANTIALIASED_QUALITY; case SC_EFF_QUALITY_LCD_OPTIMIZED: return CLEARTYPE_QUALITY; default: return SC_EFF_QUALITY_DEFAULT; } } static void SetLogFont(LOGFONTA &lf, const char *faceName, int characterSet, int size, bool bold, bool italic, int extraFontFlag) { memset(&lf, 0, sizeof(lf)); // The negative is to allow for leading lf.lfHeight = -(abs(size)); lf.lfWeight = bold ? FW_BOLD : FW_NORMAL; lf.lfItalic = static_cast<BYTE>(italic ? 1 : 0); lf.lfCharSet = static_cast<BYTE>(characterSet); lf.lfQuality = Win32MapFontQuality(extraFontFlag); strncpy(lf.lfFaceName, faceName, sizeof(lf.lfFaceName)); } /** * Create a hash from the parameters for a font to allow easy checking for identity. * If one font is the same as another, its hash will be the same, but if the hash is the * same then they may still be different. */ static int HashFont(const char *faceName, int characterSet, int size, bool bold, bool italic, int extraFontFlag) { return size ^ (characterSet << 10) ^ ((extraFontFlag & SC_EFF_QUALITY_MASK) << 9) ^ (bold ? 0x10000000 : 0) ^ (italic ? 0x20000000 : 0) ^ faceName[0]; } class FontCached : Font { FontCached *next; int usage; LOGFONTA lf; int hash; FontCached(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_); ~FontCached() {} bool SameAs(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_); virtual void Release(); static FontCached *first; public: static FontID FindOrCreate(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_); static void ReleaseId(FontID fid_); }; FontCached *FontCached::first = 0; FontCached::FontCached(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_) : next(0), usage(0), hash(0) { SetLogFont(lf, faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); hash = HashFont(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); fid = ::CreateFontIndirectA(&lf); usage = 1; } bool FontCached::SameAs(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_) { return (lf.lfHeight == -(abs(size_))) && (lf.lfWeight == (bold_ ? FW_BOLD : FW_NORMAL)) && (lf.lfItalic == static_cast<BYTE>(italic_ ? 1 : 0)) && (lf.lfCharSet == characterSet_) && (lf.lfQuality == Win32MapFontQuality(extraFontFlag_)) && 0 == strcmp(lf.lfFaceName,faceName_); } void FontCached::Release() { if (fid) ::DeleteObject(fid); fid = 0; } FontID FontCached::FindOrCreate(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_, int extraFontFlag_) { FontID ret = 0; ::EnterCriticalSection(&crPlatformLock); int hashFind = HashFont(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); for (FontCached *cur=first; cur; cur=cur->next) { if ((cur->hash == hashFind) && cur->SameAs(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_)) { cur->usage++; ret = cur->fid; } } if (ret == 0) { FontCached *fc = new FontCached(faceName_, characterSet_, size_, bold_, italic_, extraFontFlag_); if (fc) { fc->next = first; first = fc; ret = fc->fid; } } ::LeaveCriticalSection(&crPlatformLock); return ret; } void FontCached::ReleaseId(FontID fid_) { ::EnterCriticalSection(&crPlatformLock); FontCached **pcur=&first; for (FontCached *cur=first; cur; cur=cur->next) { if (cur->fid == fid_) { cur->usage--; if (cur->usage == 0) { *pcur = cur->next; cur->Release(); cur->next = 0; delete cur; } break; } pcur=&cur->next; } ::LeaveCriticalSection(&crPlatformLock); } Font::Font() { fid = 0; } Font::~Font() { } #define FONTS_CACHED void Font::Create(const char *faceName, int characterSet, int size, bool bold, bool italic, int extraFontFlag) { Release(); #ifndef FONTS_CACHED LOGFONT lf; SetLogFont(lf, faceName, characterSet, size, bold, italic, extraFontFlag); fid = ::CreateFontIndirect(&lf); #else if (faceName) fid = FontCached::FindOrCreate(faceName, characterSet, size, bold, italic, extraFontFlag); #endif } void Font::Release() { #ifndef FONTS_CACHED if (fid) ::DeleteObject(fid); #else if (fid) FontCached::ReleaseId(fid); #endif fid = 0; } #ifdef SCI_NAMESPACE namespace Scintilla { #endif class SurfaceImpl : public Surface { bool unicodeMode; HDC hdc; bool hdcOwned; HPEN pen; HPEN penOld; HBRUSH brush; HBRUSH brushOld; HFONT font; HFONT fontOld; HBITMAP bitmap; HBITMAP bitmapOld; HPALETTE paletteOld; int maxWidthMeasure; int maxLenText; int codePage; // If 9x OS and current code page is same as ANSI code page. bool win9xACPSame; void BrushColor(ColourAllocated back); void SetFont(Font &font_); // Private so SurfaceImpl objects can not be copied SurfaceImpl(const SurfaceImpl &); SurfaceImpl &operator=(const SurfaceImpl &); public: SurfaceImpl(); virtual ~SurfaceImpl(); void Init(WindowID wid); void Init(SurfaceID sid, WindowID wid); void InitPixMap(int width, int height, Surface *surface_, WindowID wid); void Release(); bool Initialised(); void PenColour(ColourAllocated fore); int LogPixelsY(); int DeviceHeightFont(int points); void MoveTo(int x_, int y_); void LineTo(int x_, int y_); void Polygon(Point *pts, int npts, ColourAllocated fore, ColourAllocated back); void RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back); void FillRectangle(PRectangle rc, ColourAllocated back); void FillRectangle(PRectangle rc, Surface &surfacePattern); void RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back); void AlphaRectangle(PRectangle rc, int cornerSize, ColourAllocated fill, int alphaFill, ColourAllocated outline, int alphaOutline, int flags); void Ellipse(PRectangle rc, ColourAllocated fore, ColourAllocated back); void Copy(PRectangle rc, Point from, Surface &surfaceSource); void DrawTextCommon(PRectangle rc, Font &font_, int ybase, const char *s, int len, UINT fuOptions); void DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back); void DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back); void DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore); void MeasureWidths(Font &font_, const char *s, int len, int *positions); int WidthText(Font &font_, const char *s, int len); int WidthChar(Font &font_, char ch); int Ascent(Font &font_); int Descent(Font &font_); int InternalLeading(Font &font_); int ExternalLeading(Font &font_); int Height(Font &font_); int AverageCharWidth(Font &font_); int SetPalette(Palette *pal, bool inBackGround); void SetClip(PRectangle rc); void FlushCachedState(); void SetUnicodeMode(bool unicodeMode_); void SetDBCSMode(int codePage_); }; #ifdef SCI_NAMESPACE } //namespace Scintilla #endif SurfaceImpl::SurfaceImpl() : unicodeMode(false), hdc(0), hdcOwned(false), pen(0), penOld(0), brush(0), brushOld(0), font(0), fontOld(0), bitmap(0), bitmapOld(0), paletteOld(0) { // Windows 9x has only a 16 bit coordinate system so break after 30000 pixels maxWidthMeasure = IsNT() ? INT_MAX : 30000; // There appears to be a 16 bit string length limit in GDI on NT and a limit of // 8192 characters on Windows 95. maxLenText = IsNT() ? 65535 : 8192; codePage = 0; win9xACPSame = false; } SurfaceImpl::~SurfaceImpl() { Release(); } void SurfaceImpl::Release() { if (penOld) { ::SelectObject(reinterpret_cast<HDC>(hdc), penOld); ::DeleteObject(pen); penOld = 0; } pen = 0; if (brushOld) { ::SelectObject(reinterpret_cast<HDC>(hdc), brushOld); ::DeleteObject(brush); brushOld = 0; } brush = 0; if (fontOld) { // Fonts are not deleted as they are owned by a Font object ::SelectObject(reinterpret_cast<HDC>(hdc), fontOld); fontOld = 0; } font = 0; if (bitmapOld) { ::SelectObject(reinterpret_cast<HDC>(hdc), bitmapOld); ::DeleteObject(bitmap); bitmapOld = 0; } bitmap = 0; if (paletteOld) { // Palettes are not deleted as they are owned by a Palette object ::SelectPalette(reinterpret_cast<HDC>(hdc), reinterpret_cast<HPALETTE>(paletteOld), TRUE); paletteOld = 0; } if (hdcOwned) { ::DeleteDC(reinterpret_cast<HDC>(hdc)); hdc = 0; hdcOwned = false; } } bool SurfaceImpl::Initialised() { return hdc != 0; } void SurfaceImpl::Init(WindowID) { Release(); hdc = ::CreateCompatibleDC(NULL); hdcOwned = true; ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE); } void SurfaceImpl::Init(SurfaceID sid, WindowID) { Release(); hdc = reinterpret_cast<HDC>(sid); ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE); } void SurfaceImpl::InitPixMap(int width, int height, Surface *surface_, WindowID) { Release(); hdc = ::CreateCompatibleDC(static_cast<SurfaceImpl *>(surface_)->hdc); hdcOwned = true; bitmap = ::CreateCompatibleBitmap(static_cast<SurfaceImpl *>(surface_)->hdc, width, height); bitmapOld = static_cast<HBITMAP>(::SelectObject(hdc, bitmap)); ::SetTextAlign(reinterpret_cast<HDC>(hdc), TA_BASELINE); } void SurfaceImpl::PenColour(ColourAllocated fore) { if (pen) { ::SelectObject(hdc, penOld); ::DeleteObject(pen); pen = 0; penOld = 0; } pen = ::CreatePen(0,1,fore.AsLong()); penOld = static_cast<HPEN>(::SelectObject(reinterpret_cast<HDC>(hdc), pen)); } void SurfaceImpl::BrushColor(ColourAllocated back) { if (brush) { ::SelectObject(hdc, brushOld); ::DeleteObject(brush); brush = 0; brushOld = 0; } // Only ever want pure, non-dithered brushes ColourAllocated colourNearest = ::GetNearestColor(hdc, back.AsLong()); brush = ::CreateSolidBrush(colourNearest.AsLong()); brushOld = static_cast<HBRUSH>(::SelectObject(hdc, brush)); } void SurfaceImpl::SetFont(Font &font_) { if (font_.GetID() != font) { if (fontOld) { ::SelectObject(hdc, font_.GetID()); } else { fontOld = static_cast<HFONT>(::SelectObject(hdc, font_.GetID())); } font = reinterpret_cast<HFONT>(font_.GetID()); } } int SurfaceImpl::LogPixelsY() { return ::GetDeviceCaps(hdc, LOGPIXELSY); } int SurfaceImpl::DeviceHeightFont(int points) { return ::MulDiv(points, LogPixelsY(), 72); } void SurfaceImpl::MoveTo(int x_, int y_) { ::MoveToEx(hdc, x_, y_, 0); } void SurfaceImpl::LineTo(int x_, int y_) { ::LineTo(hdc, x_, y_); } void SurfaceImpl::Polygon(Point *pts, int npts, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::Polygon(hdc, reinterpret_cast<POINT *>(pts), npts); } void SurfaceImpl::RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::Rectangle(hdc, rc.left, rc.top, rc.right, rc.bottom); } void SurfaceImpl::FillRectangle(PRectangle rc, ColourAllocated back) { // Using ExtTextOut rather than a FillRect ensures that no dithering occurs. // There is no need to allocate a brush either. RECT rcw = RectFromPRectangle(rc); ::SetBkColor(hdc, back.AsLong()); ::ExtTextOut(hdc, rc.left, rc.top, ETO_OPAQUE, &rcw, TEXT(""), 0, NULL); } void SurfaceImpl::FillRectangle(PRectangle rc, Surface &surfacePattern) { HBRUSH br; if (static_cast<SurfaceImpl &>(surfacePattern).bitmap) br = ::CreatePatternBrush(static_cast<SurfaceImpl &>(surfacePattern).bitmap); else // Something is wrong so display in red br = ::CreateSolidBrush(RGB(0xff, 0, 0)); RECT rcw = RectFromPRectangle(rc); ::FillRect(hdc, &rcw, br); ::DeleteObject(br); } void SurfaceImpl::RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::RoundRect(hdc, rc.left + 1, rc.top, rc.right - 1, rc.bottom, 8, 8); } // Plot a point into a DWORD buffer symetrically to all 4 qudrants static void AllFour(DWORD *pixels, int width, int height, int x, int y, DWORD val) { pixels[y*width+x] = val; pixels[y*width+width-1-x] = val; pixels[(height-1-y)*width+x] = val; pixels[(height-1-y)*width+width-1-x] = val; } #ifndef AC_SRC_OVER #define AC_SRC_OVER 0x00 #endif #ifndef AC_SRC_ALPHA #define AC_SRC_ALPHA 0x01 #endif static DWORD dwordFromBGRA(byte b, byte g, byte r, byte a) { union { byte pixVal[4]; DWORD val; } converter; converter.pixVal[0] = b; converter.pixVal[1] = g; converter.pixVal[2] = r; converter.pixVal[3] = a; return converter.val; } void SurfaceImpl::AlphaRectangle(PRectangle rc, int cornerSize, ColourAllocated fill, int alphaFill, ColourAllocated outline, int alphaOutline, int /* flags*/ ) { if (AlphaBlendFn && rc.Width() > 0) { HDC hMemDC = ::CreateCompatibleDC(reinterpret_cast<HDC>(hdc)); int width = rc.Width(); int height = rc.Height(); // Ensure not distorted too much by corners when small cornerSize = Platform::Minimum(cornerSize, (Platform::Minimum(width, height) / 2) - 2); BITMAPINFO bpih = {sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0}; void *image = 0; HBITMAP hbmMem = CreateDIBSection(reinterpret_cast<HDC>(hMemDC), &bpih, DIB_RGB_COLORS, &image, NULL, 0); HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem); DWORD valEmpty = dwordFromBGRA(0,0,0,0); DWORD valFill = dwordFromBGRA( static_cast<byte>(GetBValue(fill.AsLong()) * alphaFill / 255), static_cast<byte>(GetGValue(fill.AsLong()) * alphaFill / 255), static_cast<byte>(GetRValue(fill.AsLong()) * alphaFill / 255), static_cast<byte>(alphaFill)); DWORD valOutline = dwordFromBGRA( static_cast<byte>(GetBValue(outline.AsLong()) * alphaOutline / 255), static_cast<byte>(GetGValue(outline.AsLong()) * alphaOutline / 255), static_cast<byte>(GetRValue(outline.AsLong()) * alphaOutline / 255), static_cast<byte>(alphaOutline)); DWORD *pixels = reinterpret_cast<DWORD *>(image); for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { if ((x==0) || (x==width-1) || (y == 0) || (y == height-1)) { pixels[y*width+x] = valOutline; } else { pixels[y*width+x] = valFill; } } } for (int c=0;c<cornerSize; c++) { for (int x=0;x<c+1; x++) { AllFour(pixels, width, height, x, c-x, valEmpty); } } for (int x=1;x<cornerSize; x++) { AllFour(pixels, width, height, x, cornerSize-x, valOutline); } BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA }; AlphaBlendFn(reinterpret_cast<HDC>(hdc), rc.left, rc.top, width, height, hMemDC, 0, 0, width, height, merge); SelectBitmap(hMemDC, hbmOld); ::DeleteObject(hbmMem); ::DeleteDC(hMemDC); } else { BrushColor(outline); RECT rcw = RectFromPRectangle(rc); FrameRect(hdc, &rcw, brush); } } void SurfaceImpl::Ellipse(PRectangle rc, ColourAllocated fore, ColourAllocated back) { PenColour(fore); BrushColor(back); ::Ellipse(hdc, rc.left, rc.top, rc.right, rc.bottom); } void SurfaceImpl::Copy(PRectangle rc, Point from, Surface &surfaceSource) { ::BitBlt(hdc, rc.left, rc.top, rc.Width(), rc.Height(), static_cast<SurfaceImpl &>(surfaceSource).hdc, from.x, from.y, SRCCOPY); } // Buffer to hold strings and string position arrays without always allocating on heap. // May sometimes have string too long to allocate on stack. So use a fixed stack-allocated buffer // when less than safe size otherwise allocate on heap and free automatically. template<typename T, int lengthStandard> class VarBuffer { T bufferStandard[lengthStandard]; public: T *buffer; VarBuffer(size_t length) : buffer(0) { if (length > lengthStandard) { buffer = new T[length]; } else { buffer = bufferStandard; } } ~VarBuffer() { if (buffer != bufferStandard) { delete []buffer; buffer = 0; } } }; const int stackBufferLength = 10000; class TextWide : public VarBuffer<wchar_t, stackBufferLength> { public: int tlen; TextWide(const char *s, int len, bool unicodeMode, int codePage=0) : VarBuffer<wchar_t, stackBufferLength>(len) { if (unicodeMode) { tlen = UTF16FromUTF8(s, len, buffer, len); } else { // Support Asian string display in 9x English tlen = ::MultiByteToWideChar(codePage, 0, s, len, buffer, len); } } }; typedef VarBuffer<int, stackBufferLength> TextPositions; void SurfaceImpl::DrawTextCommon(PRectangle rc, Font &font_, int ybase, const char *s, int len, UINT fuOptions) { SetFont(font_); RECT rcw = RectFromPRectangle(rc); SIZE sz={0,0}; int pos = 0; int x = rc.left; // Text drawing may fail if the text is too big. // If it does fail, slice up into segments and draw each segment. const int maxSegmentLength = 0x200; if ((!unicodeMode) && (IsNT() || (codePage==0) || win9xACPSame)) { // Use ANSI calls int lenDraw = Platform::Minimum(len, maxLenText); if (!::ExtTextOutA(hdc, x, ybase, fuOptions, &rcw, s, lenDraw, NULL)) { while (lenDraw > pos) { int seglen = Platform::Minimum(maxSegmentLength, lenDraw - pos); if (!::ExtTextOutA(hdc, x, ybase, fuOptions, &rcw, s+pos, seglen, NULL)) { PLATFORM_ASSERT(false); return; } ::GetTextExtentPoint32A(hdc, s+pos, seglen, &sz); x += sz.cx; pos += seglen; } } } else { // Use Unicode calls const TextWide tbuf(s, len, unicodeMode, codePage); if (!::ExtTextOutW(hdc, x, ybase, fuOptions, &rcw, tbuf.buffer, tbuf.tlen, NULL)) { while (tbuf.tlen > pos) { int seglen = Platform::Minimum(maxSegmentLength, tbuf.tlen - pos); if (!::ExtTextOutW(hdc, x, ybase, fuOptions, &rcw, tbuf.buffer+pos, seglen, NULL)) { PLATFORM_ASSERT(false); return; } ::GetTextExtentPoint32W(hdc, tbuf.buffer+pos, seglen, &sz); x += sz.cx; pos += seglen; } } } } void SurfaceImpl::DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back) { ::SetTextColor(hdc, fore.AsLong()); ::SetBkColor(hdc, back.AsLong()); DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE); } void SurfaceImpl::DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back) { ::SetTextColor(hdc, fore.AsLong()); ::SetBkColor(hdc, back.AsLong()); DrawTextCommon(rc, font_, ybase, s, len, ETO_OPAQUE | ETO_CLIPPED); } void SurfaceImpl::DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore) { // Avoid drawing spaces in transparent mode for (int i=0;i<len;i++) { if (s[i] != ' ') { ::SetTextColor(hdc, fore.AsLong()); ::SetBkMode(hdc, TRANSPARENT); DrawTextCommon(rc, font_, ybase, s, len, 0); ::SetBkMode(hdc, OPAQUE); return; } } } int SurfaceImpl::WidthText(Font &font_, const char *s, int len) { SetFont(font_); SIZE sz={0,0}; if ((!unicodeMode) && (IsNT() || (codePage==0) || win9xACPSame)) { ::GetTextExtentPoint32A(hdc, s, Platform::Minimum(len, maxLenText), &sz); } else { const TextWide tbuf(s, len, unicodeMode, codePage); ::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &sz); } return sz.cx; } void SurfaceImpl::MeasureWidths(Font &font_, const char *s, int len, int *positions) { SetFont(font_); SIZE sz={0,0}; int fit = 0; if (unicodeMode) { const TextWide tbuf(s, len, unicodeMode, codePage); TextPositions poses(tbuf.tlen); fit = tbuf.tlen; if (!::GetTextExtentExPointW(hdc, tbuf.buffer, tbuf.tlen, maxWidthMeasure, &fit, poses.buffer, &sz)) { // Likely to have failed because on Windows 9x where function not available // So measure the character widths by measuring each initial substring // Turns a linear operation into a qudratic but seems fast enough on test files for (int widthSS=0; widthSS < tbuf.tlen; widthSS++) { ::GetTextExtentPoint32W(hdc, tbuf.buffer, widthSS+1, &sz); poses.buffer[widthSS] = sz.cx; } } // Map the widths given for UTF-16 characters back onto the UTF-8 input string int ui=0; const unsigned char *us = reinterpret_cast<const unsigned char *>(s); int i=0; while (ui<fit) { unsigned char uch = us[i]; unsigned int lenChar = 1; if (uch >= (0x80 + 0x40 + 0x20 + 0x10)) { lenChar = 4; ui++; } else if (uch >= (0x80 + 0x40 + 0x20)) { lenChar = 3; } else if (uch >= (0x80)) { lenChar = 2; } for (unsigned int bytePos=0; (bytePos<lenChar) && (i<len); bytePos++) { positions[i++] = poses.buffer[ui]; } ui++; } int lastPos = 0; if (i > 0) lastPos = positions[i-1]; while (i<len) { positions[i++] = lastPos; } } else if (IsNT() || (codePage==0) || win9xACPSame) { // Zero positions to avoid random behaviour on failure. memset(positions, 0, len * sizeof(*positions)); // len may be larger than platform supports so loop over segments small enough for platform int startOffset = 0; while (len > 0) { int lenBlock = Platform::Minimum(len, maxLenText); if (!::GetTextExtentExPointA(hdc, s, lenBlock, maxWidthMeasure, &fit, positions, &sz)) { // Eeek - a NULL DC or other foolishness could cause this. return; } else if (fit < lenBlock) { // For some reason, such as an incomplete DBCS character // Not all the positions are filled in so make them equal to end. for (int i=fit;i<lenBlock;i++) positions[i] = positions[fit-1]; } else if (startOffset > 0) { for (int i=0;i<lenBlock;i++) positions[i] += startOffset; } startOffset = positions[lenBlock-1]; len -= lenBlock; positions += lenBlock; s += lenBlock; } } else { // Support Asian string display in 9x English const TextWide tbuf(s, len, unicodeMode, codePage); TextPositions poses(tbuf.tlen); for (int widthSS=0; widthSS<tbuf.tlen; widthSS++) { ::GetTextExtentPoint32W(hdc, tbuf.buffer, widthSS+1, &sz); poses.buffer[widthSS] = sz.cx; } int ui = 0; for (int i=0;i<len;) { if (::IsDBCSLeadByteEx(codePage, s[i])) { positions[i] = poses.buffer[ui]; positions[i+1] = poses.buffer[ui]; i += 2; } else { positions[i] = poses.buffer[ui]; i++; } ui++; } } } int SurfaceImpl::WidthChar(Font &font_, char ch) { SetFont(font_); SIZE sz; ::GetTextExtentPoint32A(hdc, &ch, 1, &sz); return sz.cx; } int SurfaceImpl::Ascent(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmAscent; } int SurfaceImpl::Descent(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmDescent; } int SurfaceImpl::InternalLeading(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmInternalLeading; } int SurfaceImpl::ExternalLeading(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmExternalLeading; } int SurfaceImpl::Height(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmHeight; } int SurfaceImpl::AverageCharWidth(Font &font_) { SetFont(font_); TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); return tm.tmAveCharWidth; } int SurfaceImpl::SetPalette(Palette *pal, bool inBackGround) { if (paletteOld) { ::SelectPalette(hdc, paletteOld, TRUE); } paletteOld = 0; int changes = 0; if (pal->allowRealization) { paletteOld = ::SelectPalette(hdc, reinterpret_cast<HPALETTE>(pal->hpal), inBackGround); changes = ::RealizePalette(hdc); } return changes; } void SurfaceImpl::SetClip(PRectangle rc) { ::IntersectClipRect(hdc, rc.left, rc.top, rc.right, rc.bottom); } void SurfaceImpl::FlushCachedState() { pen = 0; brush = 0; font = 0; } void SurfaceImpl::SetUnicodeMode(bool unicodeMode_) { unicodeMode=unicodeMode_; } void SurfaceImpl::SetDBCSMode(int codePage_) { // No action on window as automatically handled by system. codePage = codePage_; win9xACPSame = !IsNT() && ((unsigned int)codePage == ::GetACP()); } Surface *Surface::Allocate() { return new SurfaceImpl; } Window::~Window() { } void Window::Destroy() { if (wid) ::DestroyWindow(reinterpret_cast<HWND>(wid)); wid = 0; } bool Window::HasFocus() { return ::GetFocus() == wid; } PRectangle Window::GetPosition() { RECT rc; ::GetWindowRect(reinterpret_cast<HWND>(wid), &rc); return PRectangle(rc.left, rc.top, rc.right, rc.bottom); } void Window::SetPosition(PRectangle rc) { ::SetWindowPos(reinterpret_cast<HWND>(wid), 0, rc.left, rc.top, rc.Width(), rc.Height(), SWP_NOZORDER|SWP_NOACTIVATE); } void Window::SetPositionRelative(PRectangle rc, Window w) { LONG style = ::GetWindowLong(reinterpret_cast<HWND>(wid), GWL_STYLE); if (style & WS_POPUP) { POINT ptOther = {0, 0}; ::ClientToScreen(reinterpret_cast<HWND>(w.GetID()), &ptOther); rc.Move(ptOther.x, ptOther.y); // This #ifdef is for VC 98 which has problems with MultiMon.h under some conditions. #ifdef MONITOR_DEFAULTTONULL // We're using the stub functionality of MultiMon.h to decay gracefully on machines // (ie, pre Win2000, Win95) that do not support the newer functions. RECT rcMonitor; memcpy(&rcMonitor, &rc, sizeof(rcMonitor)); // RECT and Rectangle are the same really. MONITORINFO mi = {0}; mi.cbSize = sizeof(mi); HMONITOR hMonitor = ::MonitorFromRect(&rcMonitor, MONITOR_DEFAULTTONEAREST); // If hMonitor is NULL, that's just the main screen anyways. ::GetMonitorInfo(hMonitor, &mi); // Now clamp our desired rectangle to fit inside the work area // This way, the menu will fit wholly on one screen. An improvement even // if you don't have a second monitor on the left... Menu's appears half on // one screen and half on the other are just U.G.L.Y.! if (rc.right > mi.rcWork.right) rc.Move(mi.rcWork.right - rc.right, 0); if (rc.bottom > mi.rcWork.bottom) rc.Move(0, mi.rcWork.bottom - rc.bottom); if (rc.left < mi.rcWork.left) rc.Move(mi.rcWork.left - rc.left, 0); if (rc.top < mi.rcWork.top) rc.Move(0, mi.rcWork.top - rc.top); #endif } SetPosition(rc); } PRectangle Window::GetClientPosition() { RECT rc={0,0,0,0}; if (wid) ::GetClientRect(reinterpret_cast<HWND>(wid), &rc); return PRectangle(rc.left, rc.top, rc.right, rc.bottom); } void Window::Show(bool show) { if (show) ::ShowWindow(reinterpret_cast<HWND>(wid), SW_SHOWNOACTIVATE); else ::ShowWindow(reinterpret_cast<HWND>(wid), SW_HIDE); } void Window::InvalidateAll() { ::InvalidateRect(reinterpret_cast<HWND>(wid), NULL, FALSE); } void Window::InvalidateRectangle(PRectangle rc) { RECT rcw = RectFromPRectangle(rc); ::InvalidateRect(reinterpret_cast<HWND>(wid), &rcw, FALSE); } static LRESULT Window_SendMessage(Window *w, UINT msg, WPARAM wParam=0, LPARAM lParam=0) { return ::SendMessage(reinterpret_cast<HWND>(w->GetID()), msg, wParam, lParam); } void Window::SetFont(Font &font) { Window_SendMessage(this, WM_SETFONT, reinterpret_cast<WPARAM>(font.GetID()), 0); } static void FlipBitmap(HBITMAP bitmap, int width, int height) { HDC hdc = ::CreateCompatibleDC(NULL); if (hdc != NULL) { HGDIOBJ prevBmp = ::SelectObject(hdc, bitmap); ::StretchBlt(hdc, width - 1, 0, -width, height, hdc, 0, 0, width, height, SRCCOPY); ::SelectObject(hdc, prevBmp); ::DeleteDC(hdc); } } static HCURSOR GetReverseArrowCursor() { if (reverseArrowCursor != NULL) return reverseArrowCursor; ::EnterCriticalSection(&crPlatformLock); HCURSOR cursor = reverseArrowCursor; if (cursor == NULL) { cursor = ::LoadCursor(NULL, IDC_ARROW); ICONINFO info; if (::GetIconInfo(cursor, &info)) { BITMAP bmp; if (::GetObject(info.hbmMask, sizeof(bmp), &bmp)) { FlipBitmap(info.hbmMask, bmp.bmWidth, bmp.bmHeight); if (info.hbmColor != NULL) FlipBitmap(info.hbmColor, bmp.bmWidth, bmp.bmHeight); info.xHotspot = (DWORD)bmp.bmWidth - 1 - info.xHotspot; reverseArrowCursor = ::CreateIconIndirect(&info); if (reverseArrowCursor != NULL) cursor = reverseArrowCursor; } ::DeleteObject(info.hbmMask); if (info.hbmColor != NULL) ::DeleteObject(info.hbmColor); } } ::LeaveCriticalSection(&crPlatformLock); return cursor; } void Window::SetCursor(Cursor curs) { switch (curs) { case cursorText: ::SetCursor(::LoadCursor(NULL,IDC_IBEAM)); break; case cursorUp: ::SetCursor(::LoadCursor(NULL,IDC_UPARROW)); break; case cursorWait: ::SetCursor(::LoadCursor(NULL,IDC_WAIT)); break; case cursorHoriz: ::SetCursor(::LoadCursor(NULL,IDC_SIZEWE)); break; case cursorVert: ::SetCursor(::LoadCursor(NULL,IDC_SIZENS)); break; case cursorHand: ::SetCursor(::LoadCursor(NULL,IDC_HAND)); break; case cursorReverseArrow: ::SetCursor(GetReverseArrowCursor()); break; case cursorArrow: case cursorInvalid: // Should not occur, but just in case. ::SetCursor(::LoadCursor(NULL,IDC_ARROW)); break; } } void Window::SetTitle(const char *s) { ::SetWindowTextA(reinterpret_cast<HWND>(wid), s); } /* Returns rectangle of monitor pt is on, both rect and pt are in Window's coordinates */ PRectangle Window::GetMonitorRect(Point pt) { #ifdef MONITOR_DEFAULTTONULL // MonitorFromPoint and GetMonitorInfo are not available on Windows 95 so are not used. // There could be conditional code and dynamic loading in a future version // so this would work on those platforms where they are available. PRectangle rcPosition = GetPosition(); POINT ptDesktop = {pt.x + rcPosition.left, pt.y + rcPosition.top}; HMONITOR hMonitor = ::MonitorFromPoint(ptDesktop, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = {0}; memset(&mi, 0, sizeof(mi)); mi.cbSize = sizeof(mi); if (::GetMonitorInfo(hMonitor, &mi)) { PRectangle rcMonitor( mi.rcWork.left - rcPosition.left, mi.rcWork.top - rcPosition.top, mi.rcWork.right - rcPosition.left, mi.rcWork.bottom - rcPosition.top); return rcMonitor; } else { return PRectangle(); } #else return PRectangle(); #endif } struct ListItemData { const char *text; int pixId; }; #define _ROUND2(n,pow2) \ ( ( (n) + (pow2) - 1) & ~((pow2) - 1) ) class LineToItem { char *words; int wordsCount; int wordsSize; ListItemData *data; int len; int count; private: void FreeWords() { delete []words; words = NULL; wordsCount = 0; wordsSize = 0; } char *AllocWord(const char *word); public: LineToItem() : words(NULL), wordsCount(0), wordsSize(0), data(NULL), len(0), count(0) { } ~LineToItem() { Clear(); } void Clear() { FreeWords(); delete []data; data = NULL; len = 0; count = 0; } ListItemData *Append(const char *text, int value); ListItemData Get(int index) const { if (index >= 0 && index < count) { return data[index]; } else { ListItemData missing = {"", -1}; return missing; } } int Count() const { return count; } ListItemData *AllocItem(); void SetWords(char *s) { words = s; // N.B. will be deleted on destruction } }; char *LineToItem::AllocWord(const char *text) { int chars = strlen(text) + 1; int newCount = wordsCount + chars; if (newCount > wordsSize) { wordsSize = _ROUND2(newCount * 2, 8192); char *wordsNew = new char[wordsSize]; memcpy(wordsNew, words, wordsCount); int offset = wordsNew - words; for (int i=0; i<count; i++) data[i].text += offset; delete []words; words = wordsNew; } char *s = &words[wordsCount]; wordsCount = newCount; strncpy(s, text, chars); return s; } ListItemData *LineToItem::AllocItem() { if (count >= len) { int lenNew = _ROUND2((count+1) * 2, 1024); ListItemData *dataNew = new ListItemData[lenNew]; memcpy(dataNew, data, count * sizeof(ListItemData)); delete []data; data = dataNew; len = lenNew; } ListItemData *item = &data[count]; count++; return item; } ListItemData *LineToItem::Append(const char *text, int imageIndex) { ListItemData *item = AllocItem(); item->text = AllocWord(text); item->pixId = imageIndex; return item; } const TCHAR ListBoxX_ClassName[] = TEXT("ListBoxX"); ListBox::ListBox() { } ListBox::~ListBox() { } class ListBoxX : public ListBox { int lineHeight; FontID fontCopy; XPMSet xset; LineToItem lti; HWND lb; bool unicodeMode; int desiredVisibleRows; unsigned int maxItemCharacters; unsigned int aveCharWidth; Window *parent; int ctrlID; CallBackAction doubleClickAction; void *doubleClickActionData; const char *widestItem; unsigned int maxCharWidth; int resizeHit; PRectangle rcPreSize; Point dragOffset; Point location; // Caret location at which the list is opened HWND GetHWND() const; void AppendListItem(const char *startword, const char *numword); void AdjustWindowRect(PRectangle *rc) const; int ItemHeight() const; int MinClientWidth() const; int TextOffset() const; Point GetClientExtent() const; POINT MinTrackSize() const; POINT MaxTrackSize() const; void SetRedraw(bool on); void OnDoubleClick(); void ResizeToCursor(); void StartResize(WPARAM); int NcHitTest(WPARAM, LPARAM) const; void CentreItem(int); void Paint(HDC); static LRESULT PASCAL ControlWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); static const Point ItemInset; // Padding around whole item static const Point TextInset; // Padding around text static const Point ImageInset; // Padding around image public: ListBoxX() : lineHeight(10), fontCopy(0), lb(0), unicodeMode(false), desiredVisibleRows(5), maxItemCharacters(0), aveCharWidth(8), parent(NULL), ctrlID(0), doubleClickAction(NULL), doubleClickActionData(NULL), widestItem(NULL), maxCharWidth(1), resizeHit(0) { } virtual ~ListBoxX() { if (fontCopy) { ::DeleteObject(fontCopy); fontCopy = 0; } } virtual void SetFont(Font &font); virtual void Create(Window &parent, int ctrlID, Point location_, int lineHeight_, bool unicodeMode_); virtual void SetAverageCharWidth(int width); virtual void SetVisibleRows(int rows); virtual int GetVisibleRows() const; virtual PRectangle GetDesiredRect(); virtual int CaretFromEdge(); virtual void Clear(); virtual void Append(char *s, int type = -1); virtual int Length(); virtual void Select(int n); virtual int GetSelection(); virtual int Find(const char *prefix); virtual void GetValue(int n, char *value, int len); virtual void RegisterImage(int type, const char *xpm_data); virtual void ClearRegisteredImages(); virtual void SetDoubleClickAction(CallBackAction action, void *data) { doubleClickAction = action; doubleClickActionData = data; } virtual void SetList(const char *list, char separator, char typesep); void Draw(DRAWITEMSTRUCT *pDrawItem); LRESULT WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); static LRESULT PASCAL StaticWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam); }; const Point ListBoxX::ItemInset(0, 0); const Point ListBoxX::TextInset(2, 0); const Point ListBoxX::ImageInset(1, 0); ListBox *ListBox::Allocate() { ListBoxX *lb = new ListBoxX(); return lb; } void ListBoxX::Create(Window &parent_, int ctrlID_, Point location_, int lineHeight_, bool unicodeMode_) { parent = &parent_; ctrlID = ctrlID_; location = location_; lineHeight = lineHeight_; unicodeMode = unicodeMode_; HWND hwndParent = reinterpret_cast<HWND>(parent->GetID()); HINSTANCE hinstanceParent = GetWindowInstance(hwndParent); // Window created as popup so not clipped within parent client area wid = ::CreateWindowEx( WS_EX_WINDOWEDGE, ListBoxX_ClassName, TEXT(""), WS_POPUP | WS_THICKFRAME, 100,100, 150,80, hwndParent, NULL, hinstanceParent, this); ::MapWindowPoints(hwndParent, NULL, reinterpret_cast<POINT*>(&location), 1); } void ListBoxX::SetFont(Font &font) { LOGFONT lf; if (0 != ::GetObject(font.GetID(), sizeof(lf), &lf)) { if (fontCopy) { ::DeleteObject(fontCopy); fontCopy = 0; } fontCopy = ::CreateFontIndirect(&lf); ::SendMessage(lb, WM_SETFONT, reinterpret_cast<WPARAM>(fontCopy), 0); } } void ListBoxX::SetAverageCharWidth(int width) { aveCharWidth = width; } void ListBoxX::SetVisibleRows(int rows) { desiredVisibleRows = rows; } int ListBoxX::GetVisibleRows() const { return desiredVisibleRows; } HWND ListBoxX::GetHWND() const { return reinterpret_cast<HWND>(GetID()); } PRectangle ListBoxX::GetDesiredRect() { PRectangle rcDesired = GetPosition(); int rows = Length(); if ((rows == 0) || (rows > desiredVisibleRows)) rows = desiredVisibleRows; rcDesired.bottom = rcDesired.top + ItemHeight() * rows; int width = MinClientWidth(); HDC hdc = ::GetDC(lb); HFONT oldFont = SelectFont(hdc, fontCopy); SIZE textSize = {0, 0}; int len = widestItem ? strlen(widestItem) : 0; if (unicodeMode) { const TextWide tbuf(widestItem, len, unicodeMode); ::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &textSize); } else { ::GetTextExtentPoint32A(hdc, widestItem, len, &textSize); } TEXTMETRIC tm; ::GetTextMetrics(hdc, &tm); maxCharWidth = tm.tmMaxCharWidth; SelectFont(hdc, oldFont); ::ReleaseDC(lb, hdc); int widthDesired = Platform::Maximum(textSize.cx, (len + 1) * tm.tmAveCharWidth); if (width < widthDesired) width = widthDesired; rcDesired.right = rcDesired.left + TextOffset() + width + (TextInset.x * 2); if (Length() > rows) rcDesired.right += ::GetSystemMetrics(SM_CXVSCROLL); AdjustWindowRect(&rcDesired); return rcDesired; } int ListBoxX::TextOffset() const { int pixWidth = const_cast<XPMSet*>(&xset)->GetWidth(); return pixWidth == 0 ? ItemInset.x : ItemInset.x + pixWidth + (ImageInset.x * 2); } int ListBoxX::CaretFromEdge() { PRectangle rc; AdjustWindowRect(&rc); return TextOffset() + TextInset.x + (0 - rc.left) - 1; } void ListBoxX::Clear() { ::SendMessage(lb, LB_RESETCONTENT, 0, 0); maxItemCharacters = 0; widestItem = NULL; lti.Clear(); } void ListBoxX::Append(char *s, int type) { int index = ::SendMessage(lb, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(s)); if (index < 0) return; ListItemData *newItem = lti.Append(s, type); unsigned int len = static_cast<unsigned int>(strlen(s)); if (maxItemCharacters < len) { maxItemCharacters = len; widestItem = newItem->text; } } int ListBoxX::Length() { return lti.Count(); } void ListBoxX::Select(int n) { // We are going to scroll to centre on the new selection and then select it, so disable // redraw to avoid flicker caused by a painting new selection twice in unselected and then // selected states SetRedraw(false); CentreItem(n); ::SendMessage(lb, LB_SETCURSEL, n, 0); SetRedraw(true); } int ListBoxX::GetSelection() { return ::SendMessage(lb, LB_GETCURSEL, 0, 0); } // This is not actually called at present int ListBoxX::Find(const char *) { return LB_ERR; } void ListBoxX::GetValue(int n, char *value, int len) { ListItemData item = lti.Get(n); strncpy(value, item.text, len); value[len-1] = '\0'; } void ListBoxX::RegisterImage(int type, const char *xpm_data) { xset.Add(type, xpm_data); } void ListBoxX::ClearRegisteredImages() { xset.Clear(); } void ListBoxX::Draw(DRAWITEMSTRUCT *pDrawItem) { if ((pDrawItem->itemAction == ODA_SELECT) || (pDrawItem->itemAction == ODA_DRAWENTIRE)) { RECT rcBox = pDrawItem->rcItem; rcBox.left += TextOffset(); if (pDrawItem->itemState & ODS_SELECTED) { RECT rcImage = pDrawItem->rcItem; rcImage.right = rcBox.left; // The image is not highlighted ::FillRect(pDrawItem->hDC, &rcImage, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1)); ::FillRect(pDrawItem->hDC, &rcBox, reinterpret_cast<HBRUSH>(COLOR_HIGHLIGHT+1)); ::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHT)); ::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_HIGHLIGHTTEXT)); } else { ::FillRect(pDrawItem->hDC, &pDrawItem->rcItem, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1)); ::SetBkColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOW)); ::SetTextColor(pDrawItem->hDC, ::GetSysColor(COLOR_WINDOWTEXT)); } ListItemData item = lti.Get(pDrawItem->itemID); int pixId = item.pixId; const char *text = item.text; int len = strlen(text); RECT rcText = rcBox; ::InsetRect(&rcText, TextInset.x, TextInset.y); if (unicodeMode) { const TextWide tbuf(text, len, unicodeMode); ::DrawTextW(pDrawItem->hDC, tbuf.buffer, tbuf.tlen, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP); } else { ::DrawTextA(pDrawItem->hDC, text, len, &rcText, DT_NOPREFIX|DT_END_ELLIPSIS|DT_SINGLELINE|DT_NOCLIP); } if (pDrawItem->itemState & ODS_SELECTED) { ::DrawFocusRect(pDrawItem->hDC, &rcBox); } // Draw the image, if any XPM *pxpm = xset.Get(pixId); if (pxpm) { Surface *surfaceItem = Surface::Allocate(); if (surfaceItem) { surfaceItem->Init(pDrawItem->hDC, pDrawItem->hwndItem); //surfaceItem->SetUnicodeMode(unicodeMode); //surfaceItem->SetDBCSMode(codePage); int left = pDrawItem->rcItem.left + ItemInset.x + ImageInset.x; PRectangle rcImage(left, pDrawItem->rcItem.top, left + xset.GetWidth(), pDrawItem->rcItem.bottom); pxpm->Draw(surfaceItem, rcImage); delete surfaceItem; ::SetTextAlign(pDrawItem->hDC, TA_TOP); } } } } void ListBoxX::AppendListItem(const char *startword, const char *numword) { ListItemData *item = lti.AllocItem(); item->text = startword; if (numword) { int pixId = 0; char ch; while ((ch = *++numword) != '\0') { pixId = 10 * pixId + (ch - '0'); } item->pixId = pixId; } else { item->pixId = -1; } unsigned int len = static_cast<unsigned int>(strlen(item->text)); if (maxItemCharacters < len) { maxItemCharacters = len; widestItem = item->text; } } void ListBoxX::SetList(const char *list, char separator, char typesep) { // Turn off redraw while populating the list - this has a significant effect, even if // the listbox is not visible. SetRedraw(false); Clear(); int size = strlen(list) + 1; char *words = new char[size]; lti.SetWords(words); memcpy(words, list, size); char *startword = words; char *numword = NULL; int i = 0; for (; words[i]; i++) { if (words[i] == separator) { words[i] = '\0'; if (numword) *numword = '\0'; AppendListItem(startword, numword); startword = words + i + 1; numword = NULL; } else if (words[i] == typesep) { numword = words + i; } } if (startword) { if (numword) *numword = '\0'; AppendListItem(startword, numword); } // Finally populate the listbox itself with the correct number of items int count = lti.Count(); ::SendMessage(lb, LB_INITSTORAGE, count, 0); for (int j=0; j<count; j++) { ::SendMessage(lb, LB_ADDSTRING, 0, j+1); } SetRedraw(true); } void ListBoxX::AdjustWindowRect(PRectangle *rc) const { ::AdjustWindowRectEx(reinterpret_cast<RECT*>(rc), WS_THICKFRAME, false, WS_EX_WINDOWEDGE); } int ListBoxX::ItemHeight() const { int itemHeight = lineHeight + (TextInset.y * 2); int pixHeight = const_cast<XPMSet*>(&xset)->GetHeight() + (ImageInset.y * 2); if (itemHeight < pixHeight) { itemHeight = pixHeight; } return itemHeight; } int ListBoxX::MinClientWidth() const { return 12 * (aveCharWidth+aveCharWidth/3); } POINT ListBoxX::MinTrackSize() const { PRectangle rc(0, 0, MinClientWidth(), ItemHeight()); AdjustWindowRect(&rc); POINT ret = {rc.Width(), rc.Height()}; return ret; } POINT ListBoxX::MaxTrackSize() const { PRectangle rc(0, 0, maxCharWidth * maxItemCharacters + TextInset.x * 2 + TextOffset() + ::GetSystemMetrics(SM_CXVSCROLL), ItemHeight() * lti.Count()); AdjustWindowRect(&rc); POINT ret = {rc.Width(), rc.Height()}; return ret; } void ListBoxX::SetRedraw(bool on) { ::SendMessage(lb, WM_SETREDRAW, static_cast<BOOL>(on), 0); if (on) ::InvalidateRect(lb, NULL, TRUE); } void ListBoxX::ResizeToCursor() { PRectangle rc = GetPosition(); Point pt; ::GetCursorPos(reinterpret_cast<POINT*>(&pt)); pt.x += dragOffset.x; pt.y += dragOffset.y; switch (resizeHit) { case HTLEFT: rc.left = pt.x; break; case HTRIGHT: rc.right = pt.x; break; case HTTOP: rc.top = pt.y; break; case HTTOPLEFT: rc.top = pt.y; rc.left = pt.x; break; case HTTOPRIGHT: rc.top = pt.y; rc.right = pt.x; break; case HTBOTTOM: rc.bottom = pt.y; break; case HTBOTTOMLEFT: rc.bottom = pt.y; rc.left = pt.x; break; case HTBOTTOMRIGHT: rc.bottom = pt.y; rc.right = pt.x; break; } POINT ptMin = MinTrackSize(); POINT ptMax = MaxTrackSize(); // We don't allow the left edge to move at present, but just in case rc.left = Platform::Maximum(Platform::Minimum(rc.left, rcPreSize.right - ptMin.x), rcPreSize.right - ptMax.x); rc.top = Platform::Maximum(Platform::Minimum(rc.top, rcPreSize.bottom - ptMin.y), rcPreSize.bottom - ptMax.y); rc.right = Platform::Maximum(Platform::Minimum(rc.right, rcPreSize.left + ptMax.x), rcPreSize.left + ptMin.x); rc.bottom = Platform::Maximum(Platform::Minimum(rc.bottom, rcPreSize.top + ptMax.y), rcPreSize.top + ptMin.y); SetPosition(rc); } void ListBoxX::StartResize(WPARAM hitCode) { rcPreSize = GetPosition(); POINT cursorPos; ::GetCursorPos(&cursorPos); switch (hitCode) { case HTRIGHT: case HTBOTTOM: case HTBOTTOMRIGHT: dragOffset.x = rcPreSize.right - cursorPos.x; dragOffset.y = rcPreSize.bottom - cursorPos.y; break; case HTTOPRIGHT: dragOffset.x = rcPreSize.right - cursorPos.x; dragOffset.y = rcPreSize.top - cursorPos.y; break; // Note that the current hit test code prevents the left edge cases ever firing // as we don't want the left edge to be moveable case HTLEFT: case HTTOP: case HTTOPLEFT: dragOffset.x = rcPreSize.left - cursorPos.x; dragOffset.y = rcPreSize.top - cursorPos.y; break; case HTBOTTOMLEFT: dragOffset.x = rcPreSize.left - cursorPos.x; dragOffset.y = rcPreSize.bottom - cursorPos.y; break; default: return; } ::SetCapture(GetHWND()); resizeHit = hitCode; } int ListBoxX::NcHitTest(WPARAM wParam, LPARAM lParam) const { int hit = ::DefWindowProc(GetHWND(), WM_NCHITTEST, wParam, lParam); // There is an apparent bug in the DefWindowProc hit test code whereby it will // return HTTOPXXX if the window in question is shorter than the default // window caption height + frame, even if one is hovering over the bottom edge of // the frame, so workaround that here if (hit >= HTTOP && hit <= HTTOPRIGHT) { int minHeight = GetSystemMetrics(SM_CYMINTRACK); PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition(); int yPos = GET_Y_LPARAM(lParam); if ((rc.Height() < minHeight) && (yPos > ((rc.top + rc.bottom)/2))) { hit += HTBOTTOM - HTTOP; } } // Nerver permit resizing that moves the left edge. Allow movement of top or bottom edge // depending on whether the list is above or below the caret switch (hit) { case HTLEFT: case HTTOPLEFT: case HTBOTTOMLEFT: hit = HTERROR; break; case HTTOP: case HTTOPRIGHT: { PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition(); // Valid only if caret below list if (location.y < rc.top) hit = HTERROR; } break; case HTBOTTOM: case HTBOTTOMRIGHT: { PRectangle rc = const_cast<ListBoxX*>(this)->GetPosition(); // Valid only if caret above list if (rc.bottom < location.y) hit = HTERROR; } break; } return hit; } void ListBoxX::OnDoubleClick() { if (doubleClickAction != NULL) { doubleClickAction(doubleClickActionData); } } Point ListBoxX::GetClientExtent() const { PRectangle rc = const_cast<ListBoxX*>(this)->GetClientPosition(); return Point(rc.Width(), rc.Height()); } void ListBoxX::CentreItem(int n) { // If below mid point, scroll up to centre, but with more items below if uneven if (n >= 0) { Point extent = GetClientExtent(); int visible = extent.y/ItemHeight(); if (visible < Length()) { int top = ::SendMessage(lb, LB_GETTOPINDEX, 0, 0); int half = (visible - 1) / 2; if (n > (top + half)) ::SendMessage(lb, LB_SETTOPINDEX, n - half , 0); } } } // Performs a double-buffered paint operation to avoid flicker void ListBoxX::Paint(HDC hDC) { Point extent = GetClientExtent(); HBITMAP hBitmap = ::CreateCompatibleBitmap(hDC, extent.x, extent.y); HDC bitmapDC = ::CreateCompatibleDC(hDC); HBITMAP hBitmapOld = SelectBitmap(bitmapDC, hBitmap); // The list background is mainly erased during painting, but can be a small // unpainted area when at the end of a non-integrally sized list with a // vertical scroll bar RECT rc = { 0, 0, extent.x, extent.y }; ::FillRect(bitmapDC, &rc, reinterpret_cast<HBRUSH>(COLOR_WINDOW+1)); // Paint the entire client area and vertical scrollbar ::SendMessage(lb, WM_PRINT, reinterpret_cast<WPARAM>(bitmapDC), PRF_CLIENT|PRF_NONCLIENT); ::BitBlt(hDC, 0, 0, extent.x, extent.y, bitmapDC, 0, 0, SRCCOPY); // Select a stock brush to prevent warnings from BoundsChecker ::SelectObject(bitmapDC, GetStockFont(WHITE_BRUSH)); SelectBitmap(bitmapDC, hBitmapOld); ::DeleteDC(bitmapDC); ::DeleteObject(hBitmap); } LRESULT PASCAL ListBoxX::ControlWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { try { switch (uMsg) { case WM_ERASEBKGND: return TRUE; case WM_PAINT: { PAINTSTRUCT ps; HDC hDC = ::BeginPaint(hWnd, &ps); ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd))); if (lbx) lbx->Paint(hDC); ::EndPaint(hWnd, &ps); } return 0; case WM_MOUSEACTIVATE: // This prevents the view activating when the scrollbar is clicked return MA_NOACTIVATE; case WM_LBUTTONDOWN: { // We must take control of selection to prevent the ListBox activating // the popup LRESULT lResult = ::SendMessage(hWnd, LB_ITEMFROMPOINT, 0, lParam); int item = LOWORD(lResult); if (HIWORD(lResult) == 0 && item >= 0) { ::SendMessage(hWnd, LB_SETCURSEL, item, 0); } } return 0; case WM_LBUTTONUP: return 0; case WM_LBUTTONDBLCLK: { ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(::GetParent(hWnd))); if (lbx) { lbx->OnDoubleClick(); } } return 0; } WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (prevWndProc) { return ::CallWindowProc(prevWndProc, hWnd, uMsg, wParam, lParam); } else { return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } } catch (...) { } return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } LRESULT ListBoxX::WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) { switch (iMessage) { case WM_CREATE: { HINSTANCE hinstanceParent = GetWindowInstance(reinterpret_cast<HWND>(parent->GetID())); // Note that LBS_NOINTEGRALHEIGHT is specified to fix cosmetic issue when resizing the list // but has useful side effect of speeding up list population significantly lb = ::CreateWindowEx( 0, TEXT("listbox"), TEXT(""), WS_CHILD | WS_VSCROLL | WS_VISIBLE | LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOINTEGRALHEIGHT, 0, 0, 150,80, hWnd, reinterpret_cast<HMENU>(ctrlID), hinstanceParent, 0); WNDPROC prevWndProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(lb, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(ControlWndProc))); ::SetWindowLongPtr(lb, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(prevWndProc)); } break; case WM_SIZE: if (lb) { SetRedraw(false); ::SetWindowPos(lb, 0, 0,0, LOWORD(lParam), HIWORD(lParam), SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOMOVE); // Ensure the selection remains visible CentreItem(GetSelection()); SetRedraw(true); } break; case WM_PAINT: { PAINTSTRUCT ps; ::BeginPaint(hWnd, &ps); ::EndPaint(hWnd, &ps); } break; case WM_COMMAND: // This is not actually needed now - the registered double click action is used // directly to action a choice from the list. ::SendMessage(reinterpret_cast<HWND>(parent->GetID()), iMessage, wParam, lParam); break; case WM_MEASUREITEM: { MEASUREITEMSTRUCT *pMeasureItem = reinterpret_cast<MEASUREITEMSTRUCT *>(lParam); pMeasureItem->itemHeight = static_cast<unsigned int>(ItemHeight()); } break; case WM_DRAWITEM: Draw(reinterpret_cast<DRAWITEMSTRUCT *>(lParam)); break; case WM_DESTROY: lb = 0; ::SetWindowLong(hWnd, 0, 0); return ::DefWindowProc(hWnd, iMessage, wParam, lParam); case WM_ERASEBKGND: // To reduce flicker we can elide background erasure since this window is // completely covered by its child. return TRUE; case WM_GETMINMAXINFO: { MINMAXINFO *minMax = reinterpret_cast<MINMAXINFO*>(lParam); minMax->ptMaxTrackSize = MaxTrackSize(); minMax->ptMinTrackSize = MinTrackSize(); } break; case WM_MOUSEACTIVATE: return MA_NOACTIVATE; case WM_NCHITTEST: return NcHitTest(wParam, lParam); case WM_NCLBUTTONDOWN: // We have to implement our own window resizing because the DefWindowProc // implementation insists on activating the resized window StartResize(wParam); return 0; case WM_MOUSEMOVE: { if (resizeHit == 0) { return ::DefWindowProc(hWnd, iMessage, wParam, lParam); } else { ResizeToCursor(); } } break; case WM_LBUTTONUP: case WM_CANCELMODE: if (resizeHit != 0) { resizeHit = 0; ::ReleaseCapture(); } return ::DefWindowProc(hWnd, iMessage, wParam, lParam); default: return ::DefWindowProc(hWnd, iMessage, wParam, lParam); } return 0; } LRESULT PASCAL ListBoxX::StaticWndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam) { if (iMessage == WM_CREATE) { CREATESTRUCT *pCreate = reinterpret_cast<CREATESTRUCT *>(lParam); SetWindowPointer(hWnd, pCreate->lpCreateParams); } // Find C++ object associated with window. ListBoxX *lbx = reinterpret_cast<ListBoxX *>(PointerFromWindow(hWnd)); if (lbx) { return lbx->WndProc(hWnd, iMessage, wParam, lParam); } else { return ::DefWindowProc(hWnd, iMessage, wParam, lParam); } } static bool ListBoxX_Register() { WNDCLASSEX wndclassc; wndclassc.cbSize = sizeof(wndclassc); // We need CS_HREDRAW and CS_VREDRAW because of the ellipsis that might be drawn for // truncated items in the list and the appearance/disappearance of the vertical scroll bar. // The list repaint is double-buffered to avoid the flicker this would otherwise cause. wndclassc.style = CS_GLOBALCLASS | CS_HREDRAW | CS_VREDRAW; wndclassc.cbClsExtra = 0; wndclassc.cbWndExtra = sizeof(ListBoxX *); wndclassc.hInstance = hinstPlatformRes; wndclassc.hIcon = NULL; wndclassc.hbrBackground = NULL; wndclassc.lpszMenuName = NULL; wndclassc.lpfnWndProc = ListBoxX::StaticWndProc; wndclassc.hCursor = ::LoadCursor(NULL, IDC_ARROW); wndclassc.lpszClassName = ListBoxX_ClassName; wndclassc.hIconSm = 0; return ::RegisterClassEx(&wndclassc) != 0; } bool ListBoxX_Unregister() { return ::UnregisterClass(ListBoxX_ClassName, hinstPlatformRes) != 0; } Menu::Menu() : mid(0) { } void Menu::CreatePopUp() { Destroy(); mid = ::CreatePopupMenu(); } void Menu::Destroy() { if (mid) ::DestroyMenu(reinterpret_cast<HMENU>(mid)); mid = 0; } void Menu::Show(Point pt, Window &w) { ::TrackPopupMenu(reinterpret_cast<HMENU>(mid), 0, pt.x - 4, pt.y, 0, reinterpret_cast<HWND>(w.GetID()), NULL); Destroy(); } static bool initialisedET = false; static bool usePerformanceCounter = false; static LARGE_INTEGER frequency; ElapsedTime::ElapsedTime() { if (!initialisedET) { usePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0; initialisedET = true; } if (usePerformanceCounter) { LARGE_INTEGER timeVal; ::QueryPerformanceCounter(&timeVal); bigBit = timeVal.HighPart; littleBit = timeVal.LowPart; } else { bigBit = clock(); } } double ElapsedTime::Duration(bool reset) { double result; long endBigBit; long endLittleBit; if (usePerformanceCounter) { LARGE_INTEGER lEnd; ::QueryPerformanceCounter(&lEnd); endBigBit = lEnd.HighPart; endLittleBit = lEnd.LowPart; LARGE_INTEGER lBegin; lBegin.HighPart = bigBit; lBegin.LowPart = littleBit; double elapsed = lEnd.QuadPart - lBegin.QuadPart; result = elapsed / static_cast<double>(frequency.QuadPart); } else { endBigBit = clock(); endLittleBit = 0; double elapsed = endBigBit - bigBit; result = elapsed / CLOCKS_PER_SEC; } if (reset) { bigBit = endBigBit; littleBit = endLittleBit; } return result; } class DynamicLibraryImpl : public DynamicLibrary { protected: HMODULE h; public: DynamicLibraryImpl(const char *modulePath) { h = ::LoadLibraryA(modulePath); } virtual ~DynamicLibraryImpl() { if (h != NULL) ::FreeLibrary(h); } // Use GetProcAddress to get a pointer to the relevant function. virtual Function FindFunction(const char *name) { if (h != NULL) { // C++ standard doesn't like casts betwen function pointers and void pointers so use a union union { FARPROC fp; Function f; } fnConv; fnConv.fp = ::GetProcAddress(h, name); return fnConv.f; } else return NULL; } virtual bool IsValid() { return h != NULL; } }; DynamicLibrary *DynamicLibrary::Load(const char *modulePath) { return static_cast<DynamicLibrary *>(new DynamicLibraryImpl(modulePath)); } ColourDesired Platform::Chrome() { return ::GetSysColor(COLOR_3DFACE); } ColourDesired Platform::ChromeHighlight() { return ::GetSysColor(COLOR_3DHIGHLIGHT); } const char *Platform::DefaultFont() { return "Verdana"; } int Platform::DefaultFontSize() { return 8; } unsigned int Platform::DoubleClickTime() { return ::GetDoubleClickTime(); } bool Platform::MouseButtonBounce() { return false; } void Platform::DebugDisplay(const char *s) { ::OutputDebugStringA(s); } bool Platform::IsKeyDown(int key) { return (::GetKeyState(key) & 0x80000000) != 0; } long Platform::SendScintilla(WindowID w, unsigned int msg, unsigned long wParam, long lParam) { return ::SendMessage(reinterpret_cast<HWND>(w), msg, wParam, lParam); } long Platform::SendScintillaPointer(WindowID w, unsigned int msg, unsigned long wParam, void *lParam) { return ::SendMessage(reinterpret_cast<HWND>(w), msg, wParam, reinterpret_cast<LPARAM>(lParam)); } bool Platform::IsDBCSLeadByte(int codePage, char ch) { return ::IsDBCSLeadByteEx(codePage, ch) != 0; } int Platform::DBCSCharLength(int codePage, const char *s) { return (::IsDBCSLeadByteEx(codePage, s[0]) != 0) ? 2 : 1; } int Platform::DBCSCharMaxLength() { return 2; } // These are utility functions not really tied to a platform int Platform::Minimum(int a, int b) { if (a < b) return a; else return b; } int Platform::Maximum(int a, int b) { if (a > b) return a; else return b; } //#define TRACE #ifdef TRACE void Platform::DebugPrintf(const char *format, ...) { char buffer[2000]; va_list pArguments; va_start(pArguments, format); vsprintf(buffer,format,pArguments); va_end(pArguments); Platform::DebugDisplay(buffer); } #else void Platform::DebugPrintf(const char *, ...) { } #endif static bool assertionPopUps = true; bool Platform::ShowAssertionPopUps(bool assertionPopUps_) { bool ret = assertionPopUps; assertionPopUps = assertionPopUps_; return ret; } void Platform::Assert(const char *c, const char *file, int line) { char buffer[2000]; sprintf(buffer, "Assertion [%s] failed at %s %d", c, file, line); if (assertionPopUps) { int idButton = ::MessageBoxA(0, buffer, "Assertion failure", MB_ABORTRETRYIGNORE|MB_ICONHAND|MB_SETFOREGROUND|MB_TASKMODAL); if (idButton == IDRETRY) { ::DebugBreak(); } else if (idButton == IDIGNORE) { // all OK } else { abort(); } } else { strcat(buffer, "\r\n"); Platform::DebugDisplay(buffer); ::DebugBreak(); abort(); } } int Platform::Clamp(int val, int minVal, int maxVal) { if (val > maxVal) val = maxVal; if (val < minVal) val = minVal; return val; } void Platform_Initialise(void *hInstance) { OSVERSIONINFO osv = {sizeof(OSVERSIONINFO),0,0,0,0,TEXT("")}; ::GetVersionEx(&osv); onNT = osv.dwPlatformId == VER_PLATFORM_WIN32_NT; ::InitializeCriticalSection(&crPlatformLock); hinstPlatformRes = reinterpret_cast<HINSTANCE>(hInstance); // This may be called from DllMain, in which case the call to LoadLibrary // is bad because it can upset the DLL load order. if (!hDLLImage) { hDLLImage = ::LoadLibrary(TEXT("Msimg32")); } if (hDLLImage) { AlphaBlendFn = (AlphaBlendSig)::GetProcAddress(hDLLImage, "AlphaBlend"); } ListBoxX_Register(); } void Platform_Finalise() { if (reverseArrowCursor != NULL) ::DestroyCursor(reverseArrowCursor); ListBoxX_Unregister(); ::DeleteCriticalSection(&crPlatformLock); }
[ "loreia@net.hr" ]
loreia@net.hr
84d6583611a2a9801b90ffe34507c14adf0ac952
d2432b6336ae059c5d8af0c3988aa8cbdde19171
/modules/14_from_c_to_cpp/construction_and_destruction.cpp
495a5bff07d0af3bd3916f11508cdf28001cb41e
[]
no_license
ecotner/learning-c
37ccee5701c4f3723487aeb23c5d7c14fee1d9eb
c4647b161df769d67b5d27f7636aed5958fe47b1
refs/heads/master
2022-12-19T06:35:38.931305
2020-09-12T22:57:52
2020-09-12T22:57:52
294,571,474
0
1
null
2020-10-02T01:36:53
2020-09-11T02:17:28
C
UTF-8
C++
false
false
772
cpp
#include <stdio.h> struct Connection { int SomeState; // this defines a "constructor" that is called whenever the object is initialized Connection() { SomeState = 0; printf("Connection constructor\n"); } void Open(char * filename) { this->SomeState = 1; } void Execute(char * statement) { } void Close() { SomeState = 0; } // this defines a "destructor" that is called whenever the object goes out of scope ~Connection() { Close(); printf("Connection destructor\n"); } }; int main() { Connection db; db.Open("C:\\temp\\stuff.db"); db.Execute("CREATE TABLE Hens (ID int, Name test)"); // db.Close(); // don't need this anymore because of destructor }
[ "2.71828cotner@gmail.com" ]
2.71828cotner@gmail.com
4205f20050bba341ca90ebc443c6bd9a7897b950
cbae96bf211b9cb33ce16553ce53f600b3b45beb
/DxImageLoader/compress_interface.cpp
acb7a5005af3f38db371044f3c7a0e97d0ea6dfd
[ "MIT" ]
permissive
superowner/ImageViewer
5c6d9de1a2d533ae23e7110fcab88fffb57edc65
4e4a8c1c06726af8eb5e32960bf9198d0e7c4200
refs/heads/master
2023-07-02T04:18:50.176383
2021-07-27T12:15:49
2021-07-27T12:15:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,469
cpp
#include "pch.h" #include "compress_interface.h" #include "../dependencies/compressonator/cmp_compressonatorlib/compressonator.h" #include <thread> #include <stdexcept> #include "interface.h" #include <algorithm> struct ExFormatInfo { bool useDxt1Alpha = false; bool isCompressed = true; bool swizzleRGB = false; uint8_t overwriteAlpha = 0; // value to overwrite alpha (0 means no overwrite) CMP_BYTE bx = 4; CMP_BYTE by = 4; CMP_BYTE bz = 1; CMP_DWORD widthMultiplier = 0; // 0 for compressed formats. width multiplier to get pitch }; struct CompressInfo { bool isCompress; // progress tracking size_t curSteps; // number of steps before this compression size_t curStepWeight; // weight of this compression size_t numSteps; // total number of steps }; static CompressInfo s_currentCompressInfo; bool cmp_feedback_proc(float fProgress, CMP_DWORD_PTR pUser1, CMP_DWORD_PTR pUser2) { //const CompressInfo* info = reinterpret_cast<CompressInfo*>(pUser1); const CompressInfo* info = &s_currentCompressInfo; // they removed the user parameter passing... const char* desc = "compressing"; if (!info->isCompress) desc = "decompressing"; try { set_progress(uint32_t((info->curSteps + size_t(fProgress * 0.01f * float(info->curStepWeight))) / info->numSteps), desc); } catch (const std::exception&) { return true; } return false; // don't abort compression } CMP_FORMAT get_cmp_format(gli::format format, ExFormatInfo& exInfo, bool isSource) { switch (format) { // formats used by the exporter case gli::format::FORMAT_RGBA8_SRGB_PACK8: case gli::format::FORMAT_RGBA8_UNORM_PACK8: case gli::format::FORMAT_RGBA8_SNORM_PACK8: exInfo.isCompressed = false; exInfo.widthMultiplier = 4; return CMP_FORMAT_RGBA_8888; case gli::format::FORMAT_RGBA32_SFLOAT_PACK32: exInfo.isCompressed = false; exInfo.widthMultiplier = 16; return CMP_FORMAT_RGBA_32F; // not supported by converter // compressed formats case gli::format::FORMAT_RGBA_ASTC_10X10_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_10X10_UNORM_BLOCK16: exInfo.bx = 10; exInfo.by = 10; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_10X5_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_10X5_UNORM_BLOCK16: exInfo.bx = 10; exInfo.by = 5; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_10X6_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_10X6_UNORM_BLOCK16: exInfo.bx = 10; exInfo.by = 6; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_10X8_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_10X8_UNORM_BLOCK16: exInfo.bx = 10; exInfo.by = 8; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_12X10_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_12X10_UNORM_BLOCK16: exInfo.bx = 12; exInfo.by = 10; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_12X12_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_12X12_UNORM_BLOCK16: exInfo.bx = 12; exInfo.by = 12; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_4X4_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_4X4_UNORM_BLOCK16: exInfo.bx = 4; exInfo.by = 4; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_5X4_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_5X4_UNORM_BLOCK16: exInfo.bx = 5; exInfo.by = 4; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_5X5_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_5X5_UNORM_BLOCK16: exInfo.bx = 5; exInfo.by = 5; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_6X5_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_6X5_UNORM_BLOCK16: exInfo.bx = 6; exInfo.by = 5; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_6X6_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_6X6_UNORM_BLOCK16: exInfo.bx = 6; exInfo.by = 6; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_8X5_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_8X5_UNORM_BLOCK16: exInfo.bx = 8; exInfo.by = 5; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_8X6_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_8X6_UNORM_BLOCK16: exInfo.bx = 8; exInfo.by = 6; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGBA_ASTC_8X8_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ASTC_8X8_UNORM_BLOCK16: exInfo.bx = 8; exInfo.by = 8; return CMP_FORMAT_ASTC; case gli::format::FORMAT_RGB_DXT1_UNORM_BLOCK8: // BC 1 case gli::format::FORMAT_RGB_DXT1_SRGB_BLOCK8: return CMP_FORMAT_DXT1; case gli::format::FORMAT_RGBA_DXT1_UNORM_BLOCK8: // BC 1 case gli::format::FORMAT_RGBA_DXT1_SRGB_BLOCK8: exInfo.useDxt1Alpha = true; return CMP_FORMAT_DXT1; case gli::format::FORMAT_RGBA_DXT3_SRGB_BLOCK16: // BC 2 case gli::format::FORMAT_RGBA_DXT3_UNORM_BLOCK16: return CMP_FORMAT_DXT3; case gli::format::FORMAT_RGBA_DXT5_SRGB_BLOCK16: // BC 3 case gli::format::FORMAT_RGBA_DXT5_UNORM_BLOCK16: return CMP_FORMAT_DXT5; case gli::format::FORMAT_R_ATI1N_UNORM_BLOCK8: // BC 4 if (isSource) exInfo.overwriteAlpha = 255; return CMP_FORMAT_ATI1N; case gli::format::FORMAT_R_ATI1N_SNORM_BLOCK8: if (isSource) exInfo.overwriteAlpha = 127; return CMP_FORMAT_ATI1N; case gli::format::FORMAT_RG_ATI2N_UNORM_BLOCK16: // BC 5 if (isSource) exInfo.overwriteAlpha = 255; return CMP_FORMAT_ATI2N_XY; case gli::format::FORMAT_RG_ATI2N_SNORM_BLOCK16: if (isSource) exInfo.overwriteAlpha = 127; // signed 1 return CMP_FORMAT_ATI2N_XY; case gli::format::FORMAT_RGB_BP_UFLOAT_BLOCK16: // BC 6 return CMP_FORMAT_BC6H; case gli::format::FORMAT_RGB_BP_SFLOAT_BLOCK16: // BC 6 return CMP_FORMAT_BC6H_SF; case gli::format::FORMAT_RGBA_BP_UNORM_BLOCK16: // BC 7 case gli::format::FORMAT_RGBA_BP_SRGB_BLOCK16: return CMP_FORMAT_BC7; case gli::format::FORMAT_RGB_ATC_UNORM_BLOCK8: return CMP_FORMAT_ATC_RGB; case gli::format::FORMAT_RGBA_ATCI_UNORM_BLOCK16: return CMP_FORMAT_ATC_RGBA_Interpolated; case gli::format::FORMAT_RGBA_ATCA_UNORM_BLOCK16: return CMP_FORMAT_ATC_RGBA_Explicit; case gli::format::FORMAT_RGB_ETC_UNORM_BLOCK8: if (isSource) exInfo.swizzleRGB = true; return CMP_FORMAT_ETC_RGB; case gli::format::FORMAT_RGB_ETC2_SRGB_BLOCK8: return CMP_FORMAT_ETC2_SRGB; case gli::format::FORMAT_RGB_ETC2_UNORM_BLOCK8: return CMP_FORMAT_ETC2_RGB; case gli::format::FORMAT_RGBA_ETC2_SRGB_BLOCK8: if (isSource) exInfo.swizzleRGB = true; return CMP_FORMAT_ETC2_SRGBA; case gli::format::FORMAT_RGBA_ETC2_UNORM_BLOCK8: if (isSource) exInfo.swizzleRGB = true; return CMP_FORMAT_ETC2_RGBA; case gli::format::FORMAT_RGBA_ETC2_SRGB_BLOCK16: case gli::format::FORMAT_RGBA_ETC2_UNORM_BLOCK16: throw std::runtime_error("ETC2 Block16 formats are not supported"); case gli::format::FORMAT_R_EAC_UNORM_BLOCK8: case gli::format::FORMAT_R_EAC_SNORM_BLOCK8: case gli::format::FORMAT_RG_EAC_UNORM_BLOCK16: case gli::format::FORMAT_RG_EAC_SNORM_BLOCK16: throw std::runtime_error("EAC formats are not supported"); } exInfo.isCompressed = false; return CMP_FORMAT_Unknown; } // exchanges R and B channels void swizzleMipmap(uint8_t* data, uint32_t size, CMP_FORMAT format) { assert(format == CMP_FORMAT_RGBA_8888); for(auto i = data, end = data + size; i < end; i += 4) { // change R and B std::swap(*i, *(i + 2)); } } void overwriteAlpha(uint8_t* data, uint32_t size, CMP_FORMAT format, uint8_t /*overwrite*/ value) { assert(format == CMP_FORMAT_RGBA_8888); for(auto i = data + 3, end = data + size; i < end; i += 4) { *i = value; } } void copy_level(uint8_t* srcDat, uint8_t* dstDat, uint32_t width, uint32_t height, uint32_t srcSize, uint32_t dstSize, CMP_FORMAT srcFormat, CMP_FORMAT dstFormat, const ExFormatInfo& srcInfo, const ExFormatInfo& dstInfo, float quality, CompressInfo& curCompressInfo) { // fill out src texture CMP_Texture srcTex; srcTex.dwSize = sizeof(srcTex); srcTex.dwWidth = width; srcTex.dwHeight = height; srcTex.dwPitch = srcInfo.widthMultiplier * srcTex.dwWidth; srcTex.dwDataSize = CMP_DWORD(srcSize); srcTex.format = srcFormat; srcTex.pData = srcDat; srcTex.nBlockWidth = srcInfo.bx; srcTex.nBlockHeight = srcInfo.by; srcTex.nBlockDepth = srcInfo.bz; srcTex.pMipSet = nullptr; srcTex.transcodeFormat = CMP_FORMAT_Unknown; // only used if format == CMP_FORMAT_BASIS if (!srcInfo.isCompressed && (srcInfo.swizzleRGB || dstInfo.swizzleRGB)) swizzleMipmap(srcDat, srcSize, srcFormat); // fill out dst texture CMP_Texture dstTex; dstTex.dwSize = sizeof(srcTex); dstTex.dwWidth = width; dstTex.dwHeight = height; dstTex.dwPitch = dstInfo.widthMultiplier * dstTex.dwWidth; dstTex.format = dstFormat; dstTex.nBlockWidth = dstInfo.bx; dstTex.nBlockHeight = dstInfo.by; dstTex.nBlockDepth = dstInfo.bz; srcTex.pMipSet = nullptr; srcTex.transcodeFormat = CMP_FORMAT_Unknown; // only used if format == CMP_FORMAT_BASIS if (dstInfo.isCompressed) dstTex.dwDataSize = CMP_CalculateBufferSize(&dstTex); else dstTex.dwDataSize = dstTex.dwPitch * dstTex.dwHeight; //assert(dstSize >= dstTex.dwDataSize); if(dstSize < dstTex.dwDataSize) throw std::runtime_error("compression error: the expected data size does not match the suggested data size by compressonator"); dstTex.pData = dstDat; // set compress options CMP_CompressOptions options = {}; options.dwSize = sizeof(options); options.fquality = quality; static const size_t nThreads = std::thread::hardware_concurrency(); options.dwnumThreads = CMP_DWORD(nThreads); options.bDXT1UseAlpha = srcInfo.useDxt1Alpha || dstInfo.useDxt1Alpha; options.nAlphaThreshold = 127; options.bUseCGCompress = true; options.bUseGPUDecompress = true; options.nEncodeWith = CMP_Compute_type::CMP_GPU_DXC; options.nGPUDecode = CMP_GPUDecode::GPUDecode_DIRECTX; options.SourceFormat = srcTex.format; options.DestFormat = dstTex.format; // compress texture s_currentCompressInfo = curCompressInfo; // set static compress info since they removed the user parameter... auto status = CMP_ConvertTexture(&srcTex, &dstTex, &options, cmp_feedback_proc); if (status != CMP_OK) throw std::runtime_error("texture compression failed"); if (!dstInfo.isCompressed && (srcInfo.swizzleRGB || dstInfo.swizzleRGB)) swizzleMipmap(dstDat, dstSize, dstFormat); if (!dstInfo.isCompressed && srcInfo.overwriteAlpha) overwriteAlpha(dstDat, dstSize, dstFormat, srcInfo.overwriteAlpha); } void compressonator_convert_image(image::IImage& src, image::IImage& dst, int quality) { assert(src.getNumLayers() == dst.getNumLayers()); assert(src.getNumMipmaps() == dst.getNumMipmaps()); assert(src.getWidth(0) == dst.getWidth(0)); assert(src.getHeight(0 ) == dst.getHeight(0)); ExFormatInfo srcFormatInfo; const auto srcFormat = get_cmp_format(src.getFormat(), srcFormatInfo, true); ExFormatInfo dstFormatInfo; const auto dstFormat = get_cmp_format(dst.getFormat(), dstFormatInfo, false); const float fquality = quality / 100.0f; CompressInfo info; info.isCompress = dstFormatInfo.isCompressed; info.numSteps = std::max<size_t>(src.getNumPixels() / 100, 1); // progress range [0, 100] info.curSteps = 0; for(uint32_t layer = 0; layer < src.getNumLayers(); ++layer) { // copy mipmap levels for(uint32_t mipmap = 0; mipmap < src.getNumMipmaps(); ++mipmap) { const auto depth = src.getDepth(mipmap); const auto width = src.getWidth(mipmap); const auto height = src.getHeight(mipmap); info.curStepWeight = width * height; uint32_t srcSize; auto srcDat = src.getData(layer, mipmap, srcSize); uint32_t dstSize; auto dstDat = dst.getData(layer, mipmap, dstSize); auto srcPlaneSize = srcSize / depth; auto dstPlaneSize = dstSize / depth; for (uint32_t z = 0; z < depth; ++z) { copy_level( srcDat + srcPlaneSize * z, dstDat + dstPlaneSize * z, width, height, srcPlaneSize, dstPlaneSize, srcFormat, dstFormat, srcFormatInfo, dstFormatInfo, fquality, info ); info.curSteps += info.curStepWeight;; } } } } bool is_compressonator_format(gli::format format) { ExFormatInfo i; auto conv = get_cmp_format(format, i, true); return i.isCompressed; }
[ "felixbruell@live.de" ]
felixbruell@live.de
6d0de5a17b98d6f108d58fb999bf3fc806930923
833230af20b2b0ae62974c5df472ea2387e74577
/src/rpcmining.cpp
f23cee63d2c4c0217bc7857a100bc9e998d5f51b
[ "MIT" ]
permissive
thefuturecoin/futurecoin
d896ac6fa377d9274ab6ce179a6bbafe5969dff0
41ba616606877f95a4b8dcfebe99f05a35c20049
refs/heads/master
2020-04-12T19:14:01.557765
2014-05-03T01:07:48
2014-05-03T01:07:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,560
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; // Key used by getwork/getblocktemplate miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining static CReserveKey* pMiningKey = NULL; void InitRPCMining() { // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); } void ShutdownRPCMining() { delete pMiningKey; pMiningKey = NULL; } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen", false); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx)); obj.push_back(Pair("pow_algo_id", miningAlgo)); obj.push_back(Pair("pow_algo", GetAlgoName(miningAlgo))); obj.push_back(Pair("difficulty", (double)GetDifficulty(NULL, miningAlgo))); obj.push_back(Pair("difficulty_sha256d", (double)GetDifficulty(NULL, ALGO_SHA256D))); obj.push_back(Pair("difficulty_groestl", (double)GetDifficulty(NULL, ALGO_GROESTL))); obj.push_back(Pair("difficulty_skein", (double)GetDifficulty(NULL, ALGO_SKEIN))); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen", false))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", TestNet())); return obj; } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Futurecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Futurecoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlock(*pMiningKey, miningAlgo); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime UpdateTime(*pblock, pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Futurecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Futurecoin is downloading blocks..."); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } pblocktemplate = CreateNewBlock(*pMiningKey, miningAlgo); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime UpdateTime(*pblock, pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); if (!fAccepted) return "rejected"; // TODO: report validation state return Value::null; }
[ "easyusername12@gmail.com" ]
easyusername12@gmail.com