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
c579a1d27b315496f028f79d1f8555c3818da229
c91629e7617b264bfdf3a21294b03c13ae6b34ba
/inside_New1.5/inside_New1.5.ino
3635c64910cd53de0e6105f6ded62a759b380f3b
[]
no_license
mmywong/ezLCD_RoomStatusManager
1ec8ebe9f69782dcbceb70748c2e7376ff34b029
57b6b0d0597650288862093aa5711222a9b303ed
refs/heads/master
2021-01-01T19:15:27.838332
2015-07-20T19:57:26
2015-07-20T19:57:26
38,768,445
0
0
null
null
null
null
UTF-8
C++
false
false
6,846
ino
#include <SPI.h> #include <Ethernet.h> #include <EthernetUdp.h> #include <ezLCDLib.h> #include <string.h> ezLCD3 lcd; // Each Inside LCD needs a unique mac and ip // have 2 sets of mac and ip below to test 2 LCDs // upload sketch with 1 or the other for each LCD /* byte mac[] = { 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xCC }; byte ip[] = { 172, 21, 42, 58 }; char *ipaddress = "172.21.42.58"; byte localPort = 99; char room[10] = "4012"; */ byte mac[] = { 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xCB }; // unique mac address byte ip[] = { 172, 21, 42, 57 }; // unique ip address char *ipaddress = "172.21.42.57"; // ip address in string form. might be used to pass into Qt byte localPort = 99; // hardcoded localPort char room[10] = "4011"; // room number. might be used to pass into Qt char roombuf[10]; // buffer to hold the room number EthernetUDP Udp; static char buffer[UDP_TX_PACKET_MAX_SIZE]; // states enum States{Initial, HomeScreen, Select, DND, HK} state; int stateIDLE = 10; int stateDND = 30; int stateHK = 40; //Changing states based on reading from QT int st = 0; int r = 0; // r is read value from Qt for any state changes void Tick_State(){ switch(state){ case Initial: //the first state. set to choice. Choice(); state = Select; break; case Select: // while choice, check inputs, switch input to home, DND, or HK. become state. if((lcd.currentWidget==3) && (lcd.currentInfo==PRESSED) || r == stateDND) { //widget 3 put over do not disturb is a touchzone. DoNotDisturb(); //being pressed take you to the do not disturb screen state = DND; //state changed to DND } else if((lcd.currentWidget==4) && (lcd.currentInfo==PRESSED) || r == stateHK) { // widget 4 put over house keeping is a touchzone HouseKeeping(); // being pressed takes you to the house keeping screen state = HK; // state changed to HK } break; case DND: // same as homescreen. if((lcd.currentWidget==1) && (lcd.currentInfo==PRESSED) || r == stateIDLE) { // widget 1 is on DND and HK screen Choice(); // being pressed takes you to the Choice screen state = Select; // state changed to Select } else if(r == stateHK) { HouseKeeping(); // being pressed takes you to the house keeping screen state = HK; } break; case HK: // same as homescreen if((lcd.currentWidget==1) && (lcd.currentInfo==PRESSED) || r == stateIDLE) { // widget 1 is on DND and HK screen Choice(); // being pressed takes you to the Choice screen state = Select; // state changed to Select } else if(r == stateDND) { DoNotDisturb(); //being pressed take you to the do not disturb screen state = DND; } break; default: // default state state = Initial; break; } switch(state) { case Select: //Choice(); st = stateIDLE; break; case DND: //DoNotDisturb(); st = stateDND; break; case HK: //HouseKeeping(); st = stateHK; break; default: break; } } void setup() { lcd.begin( EZM_BAUD_RATE ); Ethernet.begin(mac,ip); Udp.begin(localPort); strcpy(roombuf, room); state = Initial; // first state becomes choice(); } void loop() { lcd.wstack(0); Tick_State(); // state machine activation writeStatus(st); } // send status update from LCD to Qt void writeStatus(int x){ int packetSize = Udp.parsePacket(); if(packetSize) { static char buffer[UDP_TX_PACKET_MAX_SIZE]; // clear buffer for(int i = 0; i < UDP_TX_PACKET_MAX_SIZE; ++i) { buffer[i] = 0; } Udp.read(buffer,UDP_TX_PACKET_MAX_SIZE); // read new data from Qt and store into buffer r = atoi(buffer); // if read data from Qt is dummy data 100 and is not the curren status on LCD, new state is read data from Qt if(r != 100 && r != x) { x = r; } itoa(x, buffer, 10); strcat(buffer, roombuf); strcat(buffer, ipaddress); Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); /* Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); strcpy(buffer, room); Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); strcpy(buffer, ipaddress); Udp.beginPacket(Udp.remoteIP(), Udp.remotePort()); Udp.write(buffer); Udp.endPacket(); */ } } void Choice() //choice function. multiple end points using touchzones. { lcd.cls(BLACK); lcd.light(0); //light off. pring image. light on. lcd.picture("Metro0.bmp"); lcd.light(100); lcd.font("Serif24"); // create font, color, position, angle. print out House Keeping lcd.color(WHITE); lcd.xy(165,155); lcd.fontO(1); lcd.print("House"); lcd.color(WHITE); lcd.xy(185,155); lcd.fontO(1); lcd.print("Keeping"); lcd.color(WHITE); // create color, position, angle. print out Do Not Disturb lcd.xy(110,155); lcd.fontO(1); lcd.print("Do Not"); lcd.color(WHITE); lcd.xy(130,155); lcd.fontO(1); lcd.print("Disturb"); lcd.font("0"); lcd.fontO(1); lcd.color(WHITE); lcd.xy(235,155); lcd.println("Touch To"); lcd.xy(250,200); lcd.println("Change Room Status"); lcd.touchZone(3,110,35,50,170,1); // touchzone 3 takes you to state DND lcd.touchZone(4,165,35,50,170,1); // touchzone 4 takes you to state HK } void HouseKeeping() //housekeeping. loop to choice on touchznoe. { lcd.light(0); // light off, ptint picture position, light on lcd.picture(100,60,"clean.bmp"); lcd.light(100); lcd.touchZone(1,0,0,320,240,1); //create touchzone for looping to choice } void DoNotDisturb() // do not disturb. loop to choice on touchzone. { lcd.light(0); // light off, ptint picture position, light on lcd.picture(100,60,"dont.bmp"); lcd.light(100); lcd.touchZone(1,0,0,320,240,1); //create touchzone for looping to choice }
[ "dcheung24@yahoo.com" ]
dcheung24@yahoo.com
345e6dd334e0d0c98b53540f454e172f3c358594
91c38d6739ef7eb47455396371cb75f0a668c9ff
/lib/Executors/Evers/Executor/Specializations/ResolveTErrorUndefined.hpp
4251ecf0a8bc19968c28306b8f6d9656714c694e
[ "MIT" ]
permissive
rocky01/promise
8256ab0d2e599f690f31e6b035e1ae67293e60a1
638415a117207a4cae9181e04114e1d7575a9689
refs/heads/master
2020-04-01T09:14:14.878034
2018-10-15T07:31:16
2018-10-15T07:31:16
153,066,476
2
0
null
null
null
null
UTF-8
C++
false
false
1,875
hpp
#ifndef _EVEREXECUTOR_RESOLVETERRORUNDEFINED_HPP_ #define _EVEREXECUTOR_RESOLVETERRORUNDEFINED_HPP_ #include "Executors/Evers/Executor/ResolveTErrorT.hpp" namespace prm { template < typename PerformerT, typename ResolveArgT, bool IsEmplace, typename... PerformerArgsT > class EverExecutor<PerformerT, ResolveArgT, ErrorTypeUndefined, IsEmplace, PerformerArgsT...> : public IExecutor<ResolveArgT>, public IFinisher, public PromiseExecutor<ResolveArgT, ErrorTypeUndefined> { using pe = PromiseExecutor<ResolveArgT, ErrorTypeUndefined>; using PerformerType = PerformerT; // only for enable if public: ENABLE_IF_IS_NOT_EMPLACE(PerformerType, IsEmplace) EverExecutor(PerformerT&& performer) : performer_(std::forward<PerformerT>(performer)) {} ENABLE_IF_IS_EMPLACE(PerformerType, IsEmplace) EverExecutor(PerformerArgsT&&... performerArgs) : performer_(std::forward<PerformerArgsT>(performerArgs)...) {} void execute(ResolveArgT executeArg) override { pe::state_ = State::InProgress; reporter_ = std::make_unique<Reporter<ResolveArgT, ErrorTypeUndefined>>(executeArg); impl(getOperatorTypeCounterpartForEver(&PerformerT::operator())); } void finish() override { pe::state_ = State::Resolved; if (pe::nextPromiseExecutor_) { pe::nextPromiseExecutor_->execute(reporter_->getResolveArg()); } } private: void impl(FinisherReporter) { Finisher finisher(this); performer_(finisher, *reporter_); } void impl(FinisherOnly) { Finisher finisher(this); performer_(finisher); } std::unique_ptr<Reporter<ResolveArgT, ErrorTypeUndefined>> reporter_; PerformerT performer_; }; } // namespace prm #endif // _EVEREXECUTOR_RESOLVETERRORUNDEFINED_HPP_
[ "pawel.mazurek@nokia.com" ]
pawel.mazurek@nokia.com
6d630bb6f2e03b627272c32721bb296a1ba73ec7
b3310d8daefc2bb52c0dc844c7f7399466c60cfc
/cUI_Icon_Speaker.cpp
8e3709fa48e8ee1f51cae18bad42e4d23633ab6e
[]
no_license
LalDi/SmileGate_Project
b89783c296924bedb33a7aa622f023bdbb8f383c
03d6a115f2143d5dd2dec060fea1c901ea694d1b
refs/heads/master
2022-11-24T13:01:15.986313
2020-07-30T14:34:42
2020-07-30T14:34:42
276,552,771
0
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
#include "Framework.h" cUI_Icon_Speaker::cUI_Icon_Speaker(POINT Pos, int tag) :cGameObject(Pos, tag) { m_Sprite = IMAGEMANAGER->AddImage("Option_Icon_Speaker", "./Images/Option/Option_Icon_Speaker.png"); } cUI_Icon_Speaker::~cUI_Icon_Speaker() { } void cUI_Icon_Speaker::Update() { } void cUI_Icon_Speaker::Render() { m_Sprite->CenterRender(m_Pos); }
[ "jungjh0513@naver.com" ]
jungjh0513@naver.com
b5b542ddb006aab5006730f387b512e5117a679c
6fc57553a02b485ad20c6e9a65679cd71fa0a35d
/garnet/bin/system_monitor/harvester/gather_cpu.cc
d9a33e45929e23a58a0e6347f94c9dd361172152
[ "BSD-3-Clause" ]
permissive
OpenTrustGroup/fuchsia
2c782ac264054de1a121005b4417d782591fb4d8
647e593ea661b8bf98dcad2096e20e8950b24a97
refs/heads/master
2023-01-23T08:12:32.214842
2019-08-03T20:27:06
2019-08-03T20:27:06
178,452,475
1
1
BSD-3-Clause
2023-01-05T00:43:10
2019-03-29T17:53:42
C++
UTF-8
C++
false
false
2,720
cc
// Copyright 2019 The Fuchsia 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 "gather_cpu.h" #include <zircon/status.h> #include "harvester.h" #include "src/lib/fxl/logging.h" namespace harvester { namespace { // Utility function to label and append a cpu sample to the |list|. |cpu| is the // index returned from the kernel. |path| is the kind of sample, e.g. // "interrupt_count". void AddCpuValue(SampleList* list, size_t cpu, const std::string path, dockyard::SampleValue value) { std::ostringstream label; label << "cpu:" << cpu << ":" << path; list->emplace_back(label.str(), value); } } // namespace void GatherCpu::Gather() { // TODO(smbug.com/34): Determine the array size at runtime (32 is arbitrary). zx_info_cpu_stats_t stats[32]; size_t actual, avail; zx_status_t err = zx_object_get_info(RootResource(), ZX_INFO_CPU_STATS, &stats, sizeof(stats), &actual, &avail); if (err != ZX_OK) { FXL_LOG(ERROR) << "ZX_INFO_CPU_STATS returned " << err << "(" << zx_status_get_string(err) << ")"; return; } auto now = std::chrono::high_resolution_clock::now(); auto cpu_time = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count(); SampleList list; for (size_t i = 0; i < actual; ++i) { // Note: stats[i].flags are not currently recorded. // Kernel scheduler counters. AddCpuValue(&list, i, "reschedules", stats[i].reschedules); AddCpuValue(&list, i, "context_switches", stats[i].context_switches); AddCpuValue(&list, i, "meaningful_irq_preempts", stats[i].irq_preempts); AddCpuValue(&list, i, "preempts", stats[i].preempts); AddCpuValue(&list, i, "yields", stats[i].yields); // CPU level interrupts and exceptions. uint64_t busy_time = cpu_time > stats[i].idle_time ? cpu_time - stats[i].idle_time : 0ull; AddCpuValue(&list, i, "busy_time", busy_time); AddCpuValue(&list, i, "idle_time", stats[i].idle_time); AddCpuValue(&list, i, "external_hardware_interrupts", stats[i].ints); AddCpuValue(&list, i, "timer_interrupts", stats[i].timer_ints); AddCpuValue(&list, i, "timer_callbacks", stats[i].timers); AddCpuValue(&list, i, "syscalls", stats[i].syscalls); // Inter-processor interrupts. AddCpuValue(&list, i, "reschedule_ipis", stats[i].reschedule_ipis); AddCpuValue(&list, i, "generic_ipis", stats[i].generic_ipis); } DockyardProxyStatus status = Dockyard().SendSampleList(list); if (status != DockyardProxyStatus::OK) { FXL_LOG(ERROR) << "SendSampleList failed (" << status << ")"; } } } // namespace harvester
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
7a1ff6ad21194cc87f5ca4b1815479ced047cd0a
2e0b981eff3c786b642493745e5331ece929e76f
/Precomputed.cpp
08b134f02cb5e8d6ab61b794797db3fc126bd72f
[]
no_license
den385/primes-app
4877cf14811eedf314b76f1e77a27360caafeaa7
eb9bf9388b741e12293b145f19ace97bb120a0a3
refs/heads/master
2021-05-27T16:23:01.904497
2014-10-22T18:38:54
2014-10-22T18:38:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,213
cpp
#include "stdafx.h" #include "Hashtable.h" using namespace std; using namespace stdext; typedef long long int64; typedef unsigned long long uint64; const string path = "precomputed_bin/"; const int NUMBERS_IN_CHUNK = 10 * 1000 * 1000; const int NCHUNKS32 = 20; const int NCHUNKS64 = 5; const int BYTES_IN_NUMBER32 = 4; const int BYTES_IN_NUMBER64 = 8; const int TOTAL_NUMBERS32 = NUMBERS_IN_CHUNK * NCHUNKS32; const int TOTAL_NUMBERS64 = NUMBERS_IN_CHUNK * NCHUNKS64; const unsigned long MIN32 = 0x00000000; const unsigned long MAX32 = 0xFFFFFFFF; const unsigned long long MAX64 = 5336500537; static char * buffer32; static char * buffer64; /* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both * windows and linux. */ int64 GetTimeHns64() { /* Windows */ FILETIME ft; LARGE_INTEGER li; /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it * to a LARGE_INTEGER structure. */ GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; uint64 ret = li.QuadPart; ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */ return ret; } pair<unsigned long long, unsigned long long> Init( bool silent, Callback ReportProgress ) { if ( sizeof ( unsigned long ) != 4 ) throw( "Bit size of unsigned long unexpected." ); if ( sizeof ( unsigned long long ) != 8 ) throw( "Bit size of unsigned long long unexpected." ); //auto mytime = GetTimeHns64(); buffer32 = new char[ NCHUNKS32 * BYTES_IN_NUMBER32 * NUMBERS_IN_CHUNK ]; buffer64 = new char[ NCHUNKS64 * BYTES_IN_NUMBER64 * NUMBERS_IN_CHUNK ]; // process 32bit chunks of primes for ( int n=1; n <= NCHUNKS32; ++n ) { ifstream* file = new ifstream( path + "precomputed" + to_string( (long long)n ), ios::in | ios::binary ); if ( !file->is_open() ) throw runtime_error("couldn't open"); int shift32 = (n-1) * BYTES_IN_NUMBER32 * NUMBERS_IN_CHUNK; file->read( buffer32 + shift32, BYTES_IN_NUMBER32 * NUMBERS_IN_CHUNK ); file->close(); file->clear(); delete file; if ( !silent ) ReportProgress( n * 4 ); } // process 64bit chunks of primes for ( int n=NCHUNKS32 + 1; n <= NCHUNKS32 + NCHUNKS64; ++n ) { ifstream* file = new ifstream( path + "precomputed" + to_string( (long long) n ), ios::in | ios::binary ); if ( !file->is_open() ) throw runtime_error("couldn't open"); int shift64 = (n-NCHUNKS32-1) * BYTES_IN_NUMBER64 * NUMBERS_IN_CHUNK; file->read( buffer64 + shift64, BYTES_IN_NUMBER64 * NUMBERS_IN_CHUNK ); file->close(); file->clear(); delete file; if ( !silent ) ReportProgress( n * 4 ); } return pair<unsigned long long, unsigned long long>( MIN32, MAX64 ); } bool Request( unsigned long long a ) { unsigned long * decoded32 = reinterpret_cast<unsigned long *>( buffer32 ); unsigned long long * decoded64 = reinterpret_cast<unsigned long long *>( buffer64 ); bool result; if ( a <= MAX32 ) result = binary_search( decoded32, decoded32 + TOTAL_NUMBERS32, (unsigned long)a ); else result = binary_search( decoded64, decoded64 + TOTAL_NUMBERS64, a ); return result; } void Destroy() { delete[] buffer32; delete[] buffer64; }
[ "d-shr@yandex.ru" ]
d-shr@yandex.ru
a73c3d8e564683fb47a857f7d097443396bae4b9
4beae9d121cced388d2295d1cbc436b80b4a25f2
/src/qt/addressbookpage.cpp
fe7659f13c34212cad71dd5bc762a566f81eb551
[ "MIT" ]
permissive
volbil/newmocha
8e5e5e3cbb51d05a330e7ad05d3bed4a3632ded6
809c90fbb6bc72364af2ed0ba6f97abac9d23e22
refs/heads/master
2022-06-11T09:37:03.595755
2020-04-27T02:35:06
2020-04-27T02:35:06
260,594,664
0
0
null
2020-05-02T01:50:46
2020-05-02T01:50:45
null
UTF-8
C++
false
false
11,047
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2019 The Mocha Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/mocha-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "mochagui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "qrdialog.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode, Tabs _tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(_mode), tab(_tab) { ui->setupUi(this); if (!platformStyle->getImagesOnButtons()) { ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); } else { ui->newAddress->setIcon(QIcon(":/icons/add")); ui->copyAddress->setIcon(QIcon(":/icons/editcopy")); ui->deleteAddress->setIcon(QIcon(":/icons/remove")); ui->exportButton->setIcon(QIcon(":/icons/export")); } ui->showAddressQRCode->setIcon(QIcon()); switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Mocha addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Mocha addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *showAddressQRCodeAction = new QAction(tr("&Show address QR code"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); contextMenu->addAction(showAddressQRCodeAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(showAddressQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showAddressQRCode_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *_model) { this->model = _model; if(!_model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(_model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::on_showAddressQRCode_clicked() { QList<QModelIndex> entries = GUIUtil::getEntryData(ui->tableView, AddressTableModel::Address); if (entries.empty()) { return; } QString strAddress = entries.at(0).data(Qt::EditRole).toString(); QRDialog* dialog = new QRDialog(this); OptionsModel *model = new OptionsModel(nullptr, false); dialog->setModel(model); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setInfo(tr("QR code"), "mocha:"+strAddress, "", strAddress); dialog->show(); } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); ui->showAddressQRCode->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); ui->showAddressQRCode->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); for (const QModelIndex& index : indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), nullptr); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
[ "whoffman1031@gmail.com" ]
whoffman1031@gmail.com
a109d05542d25c7e810c6f26333fba66c1cf24ac
3c39e829d2f4376e0d86dc911c3876d1b3181e74
/Prim 2nd MST.cpp
3fc653ada5c6264965185bc83bcdf6629ecc43f9
[]
no_license
Asif-EWU/algorithms
6c0f0c1bbc2cd725d4a381b6b2fae02a86c7484b
92c2e30c1b5b1d30ff49b6ab0015d8248d6f4558
refs/heads/master
2022-11-15T12:55:06.944814
2020-07-16T13:38:19
2020-07-16T13:38:19
280,163,502
0
0
null
null
null
null
UTF-8
C++
false
false
2,197
cpp
#include<bits/stdc++.h> #define MX 100 using namespace std; struct Edge { int to, cost; Edge(int _to, int _cost) { to=_to; cost=_cost; } }; bool operator<(Edge a, Edge b) { return a.cost>b.cost; } vector<Edge>arr[MX]; int prim(int from, int node) { priority_queue<Edge>pq; bool taken[MX]; int cost[MX]; int x, y, sum=0; int temp1=INT_MAX, temp2; for(int i=1; i<=node; i++) { taken[i]=false; cost[i]=INT_MAX; } cost[from]=0; pq.push(Edge(from,cost[from])); while(!pq.empty()) { Edge top=pq.top(); pq.pop(); if(taken[top.to]) continue; taken[top.to]=true; sum+=top.cost; for(int i=0; i<arr[top.to].size(); i++) { x=arr[top.to][i].to; y=arr[top.to][i].cost; if(taken[x]) continue; if(cost[x]>y) { if(temp1>cost[x]) // for 2nd MST { // for 2nd MST temp1=cost[x]; // for 2nd MST temp2=y; // for 2nd MST } // for 2nd MST cost[x]=y; pq.push(Edge(x,cost[x])); } else if(cost[x]<y) // for 2nd MST { // for 2nd MST if(temp1>y) // for 2nd MST { // for 2nd MST temp1=y; // for 2nd MST temp2=cost[x]; // for 2nd MST } // for 2nd MST } // for 2nd MST } } cout << "1st MST: " << sum << endl; cout << "2nd MST: " << sum-temp2+temp1 << endl; } int main() { freopen("_prim.txt", "r", stdin); int node, edge, a, b, c; cin >> node >> edge; for(int i=0; i<edge; i++) { cin >> a >> b >> c; arr[a].push_back(Edge(b,c)); arr[b].push_back(Edge(a,c)); } prim(1,node); return 0; }
[ "asifratul45@gmail.com" ]
asifratul45@gmail.com
3410df3433ecff68da70002a280f6c2ed1d1c726
b8b36bfd9632a18aafc63e68763c89eb5e894e2d
/extractfile.cpp
fb72b09fbb7c6931ef923bc853db28a360a7a520
[]
no_license
LHFCOD/ExtractFile
8e7a07ddbdbdd5915e83dca787c5cdd7719b9d71
ec14b2c76aa4ccc5639f70edc73b81aadc23deaa
refs/heads/master
2021-05-02T08:05:07.539326
2018-02-09T02:31:01
2018-02-09T02:31:01
120,844,673
0
1
null
null
null
null
GB18030
C++
false
false
2,927
cpp
#include "extractfile.h" #include "qfile.h" #include "qfiledialog.h" #include "qmessagebox.h" ExtractFile::ExtractFile(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); ui.progressBar->setVisible(false); connect(ui.SelectBtn, SIGNAL(clicked()), this, SLOT(OnSelectBtn())); connect(ui.AppointBtn, SIGNAL(clicked()), this, SLOT(OnAppointBtn())); connect(ui.ExtractBtn , SIGNAL(clicked()), this, SLOT(OnExtractBtn())); } ExtractFile::~ExtractFile() { delete io;//清除io } void ExtractFile::OnAppointBtn() { QDir dir; RootDir = QFileDialog::getExistingDirectory(this, QString::fromLocal8Bit("选择文件夹"), dir.currentPath(),QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); ui.AppointText->setText(RootDir); } void ExtractFile::OnExtractBtn() { if (io == nullptr) { QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("未选择文件!")); return; } if (RootDir.length() == 0) { QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("未选择文件夹!")); return; } NowProcess = 0; ui.progressBar->setVisible(true); Extract(0,RootDir); ui.progressBar->setValue(io->FileCount); //ui.progressBar->setVisible(false); QMessageBox::information(NULL, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("抽取完成!")); } void ExtractFile::Extract(i32_t DID,QString path) { QVector<Directory> *vec=io->FilePool[DID]; for each(Directory direct in *vec) { QString str = QString::fromUtf16((ushort*)(direct.EntryName), direct.NameSize / 2-1);//文件名字 QString currentstr = path + QString::fromLocal8Bit("/"); currentstr.append(str); QByteArray arr = currentstr.toLocal8Bit();//这个地方不太明白,为啥要分开去写比较合适 char *tmp = arr.data(); if (direct.EntryType == 1) { QDir dir; dir.cd(path); dir.mkdir(str); Extract(direct.DID, path + "/" + str); } else { byte_t *p; if (direct.StreamSize <io-> m_Header.MiniSize) p =io-> ReadShortStreamFromSID(direct.SID, direct.StreamSize); else p = io->ReadStreamFromSID(direct.SID, direct.StreamSize);//一次性把所需要写的字符流读取,然后写入文件 FILE * pFile; pFile = fopen(tmp, "wb"); fwrite(p, sizeof(char), direct.StreamSize, pFile); fclose(pFile); NowProcess++; ui.progressBar->setValue(NowProcess); } } } void ExtractFile::OnSelectBtn() { QString path = QFileDialog::getOpenFileName(this, QString::fromLocal8Bit("打开文件"), ".", "MDS Files(*.mds)"); if (path.length() == 0) { QMessageBox::information(NULL, tr("Path"), QString::fromLocal8Bit("你未选择任何文件!")); } else { ui.SelectText->setText(path); if (io) delete io; io = new ComDocIO(path); ui.progressBar->setRange(0, io->FileCount); } }
[ "2278200244@qq.com" ]
2278200244@qq.com
e5637de3ec6d02822275d9ceee8034c587693827
071ab7375e4342433c2edfb2f5f3d6d1bd4b4aed
/Blending/transparency/main.cpp
fa9343e2b69665c99af283ed01b0f648479aff68
[]
no_license
Nicolas99-9/OPengGLTeaching
70bbbd8112ae5cea9f14d1b8ce5071bca84fbd68
2881dbcf21f5618ee78b7fe6ce953c9748308659
refs/heads/master
2021-01-10T15:51:29.608972
2016-02-27T16:49:51
2016-02-27T16:49:51
51,576,901
0
0
null
null
null
null
UTF-8
C++
false
false
13,084
cpp
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <cstdio> #include "Shader.h" #include <SOIL.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Camera.h" #include "Model.h" // Function prototypes void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void Do_movement(); // Properties GLuint screenWidth = 800, screenHeight = 600; // Camera Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); GLfloat lastX = screenWidth / 2.0; GLfloat lastY = screenHeight / 2.0; bool keys[1024]; // Light attributes glm::vec3 lightPos(1.2f, 1.0f, 2.0f); // Deltatime GLfloat deltaTime = 0.0f; // Time between current frame and last frame GLfloat lastFrame = 0.0f; // Time of last frame void error_callback(int error, const char* description) { fputs(description, stderr); } // This function loads a texture from file. Note: texture loading functions like these are usually // managed by a 'Resource Manager' that manages all resources (like textures, models, audio). // For learning purposes we'll just define it as a utility function. // This function loads a texture from file. Note: texture loading functions like these are usually // managed by a 'Resource Manager' that manages all resources (like textures, models, audio). // For learning purposes we'll just define it as a utility function. GLuint loadTexture(GLchar* path, GLboolean alpha) { //Generate texture ID and load texture data GLuint textureID; glGenTextures(1, &textureID); int width, height; unsigned char* image = SOIL_load_image(path, &width, &height, 0, alpha ? SOIL_LOAD_RGBA : SOIL_LOAD_RGB); // Assign texture to ID glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, alpha ? GL_RGBA : GL_RGB, width, height, 0, alpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); // Parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT); // Use GL_CLAMP_TO_EDGE to prevent semi-transparent borders. Due to interpolation it takes value from next repeat glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, alpha ? GL_CLAMP_TO_EDGE : GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); SOIL_free_image_data(image); return textureID; } int main(void) { // initialise the windows GLFWwindow *window; glfwSetErrorCallback(error_callback); if (!glfwInit()) { return -1; } window = glfwCreateWindow(640, 480, "Test", NULL, NULL); if (window == nullptr) { std::cout << "Erreur lors du chargement de la fenetree "; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); printf("OpenGL Version:%s\n", glGetString(GL_VERSION)); printf("GLSL Version :%s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); // create a windows if (!window) { fprintf(stderr, "Failed to initialize GLFW\n"); glfwTerminate(); return -1; } // make the window's current context // loop until the window close glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // GLFW Options //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // triangle // must be normalized to be inside the screen // GLEW INITIALISATION glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout << "Failed to initialize GLEW" << std::endl; } glViewport(0, 0, screenWidth, screenHeight); // Setup some OpenGL options glEnable(GL_DEPTH_TEST); //glDepthFunc(GL_ALWAYS); // Set to always pass the depth test (same effect as glDisable(GL_DEPTH_TEST)) //glDepthFunc(GL_LESS); //enable stencil testing //------------------------------------------------------------------ //glEnable(GL_STENCIL_TEST); //glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); Shader shader("shader.vs", "shader.frag"); Shader lampShader("shaderLight.vs", "shaderLight.frag"); #pragma region "object_initialization" // Set the object data (buffers, vertex attributes) GLfloat cubeVertices[] = { // Positions // Texture Coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; GLfloat planeVertices[] = { // Positions // Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat) 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, 5.0f, 0.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, 5.0f, 2.0f, 0.0f, -5.0f, -0.5f, -5.0f, 0.0f, 2.0f, 5.0f, -0.5f, -5.0f, 2.0f, 2.0f }; GLfloat transparentVertices[] = { // Positions // Texture Coords (swapped y coordinates because texture is flipped upside down) 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 0.0f }; // Setup cube VAO GLuint cubeVAO, cubeVBO; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &cubeVBO); glBindVertexArray(cubeVAO); glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Setup plane VAO GLuint planeVAO, planeVBO; glGenVertexArrays(1, &planeVAO); glGenBuffers(1, &planeVBO); glBindVertexArray(planeVAO); glBindBuffer(GL_ARRAY_BUFFER, planeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Setup transparent plane VAO GLuint transparentVAO, transparentVBO; glGenVertexArrays(1, &transparentVAO); glGenBuffers(1, &transparentVBO); glBindVertexArray(transparentVAO); glBindBuffer(GL_ARRAY_BUFFER, transparentVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(transparentVertices), transparentVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glBindVertexArray(0); // Load textures GLuint cubeTexture = loadTexture("images/container.jpg",false); GLuint floorTexture = loadTexture("images/sol.jpg",false); GLuint transparentTexture = loadTexture("images/blending_transparent_window.png", true); //enable different levels of transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); #pragma endregion std::vector<glm::vec3> windows; windows.push_back(glm::vec3(-1.5f, 0.0f, -0.48f)); windows.push_back(glm::vec3(1.5f, 0.0f, 0.51f)); windows.push_back(glm::vec3(0.0f, 0.0f, 0.7f)); windows.push_back(glm::vec3(-0.3f, 0.0f, -2.3f)); windows.push_back(glm::vec3(0.5f, 0.0f, -0.6f)); // Game loop while (!glfwWindowShouldClose(window)) { // Set frame time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents(); Do_movement(); // Clear the colorbuffer glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Sort windows std::map<GLfloat, glm::vec3> sorted; for (GLuint i = 0; i < windows.size(); i++) { GLfloat distance = glm::length(camera.Position - windows[i]); sorted[distance] = windows[i]; } // Draw objects shader.Use(); glm::mat4 model; glm::mat4 view = camera.GetViewMatrix(); glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth / (float)screenHeight, 0.1f, 100.0f); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection)); // Cubes glBindVertexArray(cubeVAO); glBindTexture(GL_TEXTURE_2D, cubeTexture); // We omit the glActiveTexture part since TEXTURE0 is already the default active texture unit. (a single sampler used in fragment is set to 0 as well by default) model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); model = glm::mat4(); model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f)); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 36); // Floor glBindVertexArray(planeVAO); glBindTexture(GL_TEXTURE_2D, floorTexture); model = glm::mat4(); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 6); // Render windows (from furthest to nearest) glBindVertexArray(transparentVAO); glBindTexture(GL_TEXTURE_2D, transparentTexture); for (std::map<float, glm::vec3>::reverse_iterator it = sorted.rbegin(); it != sorted.rend(); ++it) { model = glm::mat4(); model = glm::translate(model, it->second); glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glDrawArrays(GL_TRIANGLES, 0, 6); } glBindVertexArray(0); // Swap the buffers glfwSwapBuffers(window); } // Properly de-allocate all resources once they've outlived their purpose // Terminate GLFW, clearing any resources allocated by GLFW. glfwTerminate(); return 0; } // Is called whenever a key is pressed/released via GLFW void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) keys[key] = true; else if (action == GLFW_RELEASE) keys[key] = false; } } void Do_movement() { // Camera controls if (keys[GLFW_KEY_W]) camera.ProcessKeyboard(FORWARD, deltaTime); if (keys[GLFW_KEY_S]) camera.ProcessKeyboard(BACKWARD, deltaTime); if (keys[GLFW_KEY_A]) camera.ProcessKeyboard(LEFT, deltaTime); if (keys[GLFW_KEY_D]) camera.ProcessKeyboard(RIGHT, deltaTime); } bool firstMouse = true; void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } GLfloat xoffset = xpos - lastX; GLfloat yoffset = lastY - ypos; // Reversed since y-coordinates go from bottom to left lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); }
[ "bougie.nicolas@gmail.com" ]
bougie.nicolas@gmail.com
b7b8b6278dbe90ad4de8b7e168eb919f83bcfcee
1e668279a619a3649c0f546970c469bb4fdd2b90
/include/precision.h
371b8c14bb77b43f9f6068af74a4337ce6360a57
[ "MIT" ]
permissive
doreiss/BAM
dbb8299fc382051d35c0e7c2fb1dc86915dae601
2f6abd5031c0a2ea1a74c2fa8d22764802e80323
refs/heads/master
2020-04-11T23:49:32.368774
2018-12-18T21:50:52
2018-12-18T21:50:52
162,180,773
0
0
null
null
null
null
UTF-8
C++
false
false
1,925
h
#ifndef BAM_PRECISION_H #define BAM_PRECISION_H #include <cmath> namespace BAM { #define FLOAT_PRECISION #ifdef DOUBLE_PRECISION typedef double real; typedef long long magic_int; #define REAL_MAX DBL_MAX #define REAL_SQRT_MAGIC 0x5fe6ec85e7de30daLL #define PI 3.14159265358979323846 #define realSqrt sqrt #define realAbs abs #define realSin sin #define realCos cos #define realTan tan #define realACos acos #define realASin asin #define realATan atan #define realATan2 atan2 #define realPow pow #define REAL_ZERO 0.0 #define REAL_ONE 1.0 #define REAL_TWO 2.0 #define REAL_THREE 3.0 #define REAL_FOUR 4.0 #define REAL_FIVE 5.0 #define REAL_HALF 0.5 #define REAL_THREEHALVES 1.5 #define REAL_FIVEHALVES 2.5 #define REAL_SEVENHALVES 3.5 #define REAL_NINEHALVES 4.5 #define REAL_MINUS_ONE -1.0 #define REAL_MINUS_TWO -2.0 #define REAL_HUNDRED_EIGHTY 180.0 #define REAL_THOUSAND 1000.0 #endif #ifdef FLOAT_PRECISION typedef float real; typedef long magic_int; #define REAL_MAX FLT_MAX #define REAL_SQRT_MAGIC 0x5f375a86 #define PI 3.14159265358979323846f #define realSqrt sqrtf #define realAbs fabsf #define realSin sinf #define realCos cosf #define realTan tanf #define realACos acosf #define realASin asinf #define realATan atanf #define realATan2 atan2f #define realPow powf #define realExp expf #define REAL_ZERO 0.0f #define REAL_ONE 1.0f #define REAL_TWO 2.0f #define REAL_THREE 3.0f #define REAL_FOUR 4.0f #define REAL_FIVE 5.0f #define REAL_HALF 0.5f #define REAL_THREEHALVES 1.5f #define REAL_FIVEHALVES 2.5f #define REAL_SEVENHALVES 3.5f #define REAL_NINEHALVES 4.5f #define REAL_MINUS_ONE -1.0f #define REAL_MINUS_TWO -2.0f #define REAL_HUNDRED_EIGHTY 180.0f #define REAL_THOUSAND 1000.f #endif } //BAM #endif //BAM_PRECISION_H
[ "dominic.reiss@gmail.com" ]
dominic.reiss@gmail.com
33066600430f569226dd8018d7f018f421c5fe41
1aca27af5f40f53b5773ff35356c588836aef227
/Extensions/BabaPython/Sources/Games/Map.cpp
8b093fede989609ac46b9a6ad83c9614d7fd0e64
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
siva-msft/baba-is-auto
c9a5dfd2cb44629ee99f5ce5e733bf6e86fb8b8a
3237b5b70167130558827979bde7dcee14ef39f3
refs/heads/master
2022-06-26T12:05:50.536600
2020-05-12T21:55:39
2020-05-12T21:55:39
257,706,228
0
1
MIT
2020-05-12T21:55:40
2020-04-21T20:19:10
Python
UTF-8
C++
false
false
1,063
cpp
// Copyright (c) 2020 Chris Ohk // I am making my contributions/submissions to this project solely in our // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include <Games/Map.hpp> #include <baba-is-auto/Games/Map.hpp> #include <pybind11/pybind11.h> #include <pybind11/stl.h> using namespace baba_is_auto; void AddMap(pybind11::module& m) { pybind11::class_<Map>(m, "Map") .def(pybind11::init<>()) .def(pybind11::init<std::size_t, std::size_t>()) .def("Reset", &Map::Reset) .def("GetWidth", &Map::GetWidth) .def("GetHeight", &Map::GetHeight) .def("Load", &Map::Load) .def("AddObject", &Map::AddObject) .def("RemoveObject", &Map::RemoveObject) .def("At", static_cast<Object& (Map::*)(std::size_t, std::size_t)>(&Map::At)) .def( "At", static_cast<const Object& (Map::*)(std::size_t, std::size_t) const>( &Map::At)) .def("GetPositions", &Map::GetPositions); }
[ "utilForever@gmail.com" ]
utilForever@gmail.com
35854de2810e397892420629525613bfdbc917dc
9b7facbc51af989228f2452e2b8ed3d6b5fe8c66
/问题 E 特殊的语言/问题 E 特殊的语言/源.cpp
4ec0b812010bdbc409ed420f1acc87304aace455
[]
no_license
ZibeSun/OJ-Data-Structures-and-Algorithms
1028a08bf55b8685e6b1b3736bde42075c7ba789
e66c20a389e36085b277253a662f8d9763c7dd08
refs/heads/main
2023-06-06T07:08:19.608958
2021-07-02T04:14:35
2021-07-02T04:14:35
346,795,114
1
1
null
null
null
null
GB18030
C++
false
false
1,229
cpp
#include<iostream> #include<cstring> using namespace std; int SpecialLanguage(string str, string str1) { int num = 0; int len = str.length(); int len1 = str1.length(); for (int i = 0; i <= len-len1; i+=2) { if (str.substr(i, len1).compare(str1) == 0) num++; } return num; } int main() { string str; string str1; while (cin >> str >> str1) { cout << SpecialLanguage(str, str1) << endl; } } /* 题目描述 某城邦的语言,每个字是由两个字母构成的。考古学家发现把他们的文字数字化之后,当想搜索特定的句子时,总会匹配到错误的地方。 比如一段文字是 aabcdaabcdef,想要搜索 abcd,应当搜到的是 aabcda abcd ef ,却会得到额外的一个并不符合该语言语法的结果 a abcd aabcdef(因为每个字由两个字符组成,这样匹配就把正确的“字”拆开了)。 请你帮他实现正确的匹配算法。 输入 每组数据两行,第一行为该语言的主串,第二行为模式串,都由大写或小写英文字母组成,长度都不超过 10000,且一定为偶数个。 输出 每组数据输出正确匹配的次数 样例输入 abcdaabbab ab AbdcAbdcAbqAbdcAbdcAbp AbdcAb 样例输出 2 2 提示 */
[ "979271618@qq.com" ]
979271618@qq.com
7f8d759a546c201f7b3316d8f21e461889d54a69
cc63466d8a66bb8925508791c007c0054149ce5a
/msj_archives/code/C++/Doc.cpp
0a1055907d33e741897eb779487a1e0f12de7134
[ "Unlicense" ]
permissive
liumorgan/misc-code
9675cc258162064083126a22d97902dae36739c9
d47a8d1cc41f19701ce628c9f15976bb5baa239d
refs/heads/master
2022-06-29T20:41:54.288305
2020-05-13T00:20:05
2020-05-13T00:20:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,161
cpp
//////////////////////////////////////////////////////////////// // 1997 Microsoft Systems Journal. // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // // CSharedDoc implements an MFC doc class that does file sharing by // locking a file for the duration of an edit session. // Compiles with VC++ 5.0 or later // #include "stdafx.h" #include "doc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CSharedDoc, CDocument) BEGIN_MESSAGE_MAP(CSharedDoc, CDocument) END_MESSAGE_MAP() CSharedDoc::CSharedDoc() { m_pFile = NULL; } CSharedDoc::~CSharedDoc() { } ////////////////// // Load/Save doc as normal (use edit view) // void CSharedDoc::Serialize(CArchive& ar) { ((CEditView*)m_viewList.GetHead())->SerializeRaw(ar); } //////////////////////////////////////////////////////////////// // Below are overrides for shared stuff ///////////////// // Map "Save" to "Save As" if doc is read-only // BOOL CSharedDoc::DoFileSave() { return m_bReadOnly ? DoSave(NULL) : // do Save As CDocument::DoFileSave(); // save as normal } //////////////// // Create new doc. Close old one in case this is an SDI app // BOOL CSharedDoc::OnNewDocument() { CloseFile(); // Required for SDI app only, because MFC re-uses doc. BOOL bRet = CDocument::OnNewDocument(); if (bRet) // do normal stuff ((CEditView*)m_viewList.GetHead())->SetWindowText(NULL); return bRet; } ////////////////// // Open New doc. Close old one in case this is an SDI app // BOOL CSharedDoc::OnOpenDocument(LPCTSTR lpszPathName) { CloseFile(); // Required for SDI app only, because MFC re-uses doc // Open the file CFile* pFile = OpenFile(lpszPathName, m_bReadOnly); if (!pFile) { // Can't even open file read-only??? punt CString s; s.Format(_T("Unknown error opening file '%s'"), lpszPathName); AfxMessageBox(s); return FALSE; } if (m_bReadOnly) { // Doc was opened read-only: tell user CString s; s.Format(_T("File '%s' is in use.\nIt will be opened read-only"), lpszPathName); AfxMessageBox(s); } m_pFile = pFile; // Now do standard MFC Open, but close file if the open fails BOOL bRet = CDocument::OnOpenDocument(lpszPathName); if (!bRet) CloseFile(); return bRet; } ///////////////// // Save document. Use already-open file, unless saving to a new name. // Either way, lock the file and set length to zero before saving it. // Note: m_pFile could be NULL if this is a new document. // BOOL CSharedDoc::OnSaveDocument(LPCTSTR lpszPathName) { BOOL bReadOnly = m_bReadOnly; CFile* pFile = m_pFile; // Check for new doc BOOL bNewFile = (pFile==NULL) || (pFile->GetFilePath() != lpszPathName); if (bNewFile) { // new file, or saving w/different name: open new file pFile = OpenFile(lpszPathName, bReadOnly, TRUE); } // If can't get write access, can't save. // Display message and return FALSE. // if (bReadOnly || pFile == NULL) { CString s; s.Format(_T("File '%s' is in use.\nSave with a different name."), lpszPathName); AfxMessageBox(s); if (bNewFile && pFile) // if new file was opened: pFile->Close(); // close it return FALSE; } if (bNewFile) { // new file: close old one and install it CloseFile(); m_pFile = pFile; // and replace w/new one m_bReadOnly = bReadOnly;// read-only flag too } // Now do normal Serialize. Lock the file first and set length to zero // This is required because I opened with modeNoTruncate. You might // want to consider "robust" saving here: that is, save to a temp file // before destroying the original file; then if the save succeeds, replace // the original file with the new one. // pFile->LockRange(0,(DWORD)-1); // will throw exception if fails pFile->SetLength(0); // get rid of current contents BOOL bRet = CDocument::OnSaveDocument(lpszPathName); // normal MFC save pFile->UnlockRange(0,(DWORD)-1); // unlock return bRet; } ////////////////// // Close document: time to really close the file too. MFC only calls this // function in a MDI app, not SDI. // void CSharedDoc::OnCloseDocument() { CloseFile(); // close file CDocument::OnCloseDocument(); // Warning: must call this last // because MFC will "delete this" } ////////////////// // "Release" the file. This means either abort or close. // In the case of close, I don't really close it, but leave // file open for duration of user session. // void CSharedDoc::ReleaseFile(CFile* pFile, BOOL bAbort) { if (bAbort) CDocument::ReleaseFile(pFile, bAbort); else if (!m_bReadOnly) { pFile->Flush(); // write changes to disk, but don't close! } } ////////////////// // Override to use my always-open CFile object instead // of creating and opening a new one. // CFile* CSharedDoc::GetFile(LPCTSTR, UINT, CFileException*) { ASSERT_VALID(m_pFile); return m_pFile; } //////////////////////////////////////////////////////////////// // Helper functions // CFile::Open mode flags const OPENREAD = CFile::modeRead | CFile::shareDenyNone; const OPENWRITE = CFile::modeReadWrite | CFile::shareDenyWrite; const OPENCREATE = CFile::modeCreate | CFile::modeReadWrite | CFile::shareDenyWrite; ////////////////// // Open the document file. Try to open with write acess, else read-only. // bCreate says whether to create the file, used when saving to a new name. // Returns the CFile opened, and sets bReadOnly. // CFile* CSharedDoc::OpenFile(LPCTSTR lpszPathName, BOOL& bReadOnly, BOOL bCreate) { CFile* pFile = new CFile; ASSERT(pFile); bReadOnly = TRUE; // assume read only // try opening for write CFileException fe; if (pFile->Open(lpszPathName, bCreate ? OPENCREATE : OPENWRITE, &fe)) { bReadOnly = FALSE; // got write access } else if (bCreate || !pFile->Open(lpszPathName, OPENREAD, &fe)) { // can't open for read OR write--yikes! Time to punt delete pFile; pFile = NULL; } if (pFile) pFile->SeekToBegin(); return pFile; } ///////////////// // Close the file if it's open. Called from multiple places for SDI app // void CSharedDoc::CloseFile() { if (m_pFile) { m_pFile->Close(); m_pFile = NULL; } }
[ "1380950+sarangbaheti@users.noreply.github.com" ]
1380950+sarangbaheti@users.noreply.github.com
4044db600ff12d3ba670f2f1fda5c2c1d6986f68
f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e
/sc-virt/src/utils/TableGen/DAGISelEmitter.cpp
0fe3bbd8d788d0c9b36e69a4bc994ddbc7ba8964
[ "MIT", "NCSA" ]
permissive
archercreat/dta-vs-osc
2f495f74e0a67d3672c1fc11ecb812d3bc116210
b39f4d4eb6ffea501025fc3e07622251c2118fe0
refs/heads/main
2023-08-01T01:54:05.925289
2021-09-05T21:00:35
2021-09-05T21:00:35
438,047,267
1
1
MIT
2021-12-13T22:45:20
2021-12-13T22:45:19
null
UTF-8
C++
false
false
6,244
cpp
//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits a DAG instruction selector. // //===----------------------------------------------------------------------===// #include "CodeGenDAGPatterns.h" #include "DAGISelMatcher.h" #include "llvm/Support/Debug.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" using namespace llvm; #define DEBUG_TYPE "dag-isel-emitter" namespace { /// DAGISelEmitter - The top-level class which coordinates construction /// and emission of the instruction selector. class DAGISelEmitter { CodeGenDAGPatterns CGP; public: explicit DAGISelEmitter(RecordKeeper &R) : CGP(R) {} void run(raw_ostream &OS); }; } // End anonymous namespace //===----------------------------------------------------------------------===// // DAGISelEmitter Helper methods // /// getResultPatternCost - Compute the number of instructions for this pattern. /// This is a temporary hack. We should really include the instruction /// latencies in this calculation. static unsigned getResultPatternCost(TreePatternNode *P, CodeGenDAGPatterns &CGP) { if (P->isLeaf()) return 0; unsigned Cost = 0; Record *Op = P->getOperator(); if (Op->isSubClassOf("Instruction")) { Cost++; CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op); if (II.usesCustomInserter) Cost += 10; } for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) Cost += getResultPatternCost(P->getChild(i), CGP); return Cost; } /// getResultPatternCodeSize - Compute the code size of instructions for this /// pattern. static unsigned getResultPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) { if (P->isLeaf()) return 0; unsigned Cost = 0; Record *Op = P->getOperator(); if (Op->isSubClassOf("Instruction")) { Cost += Op->getValueAsInt("CodeSize"); } for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) Cost += getResultPatternSize(P->getChild(i), CGP); return Cost; } namespace { // PatternSortingPredicate - return true if we prefer to match LHS before RHS. // In particular, we want to match maximal patterns first and lowest cost within // a particular complexity first. struct PatternSortingPredicate { PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {} CodeGenDAGPatterns &CGP; bool operator()(const PatternToMatch *LHS, const PatternToMatch *RHS) { const TreePatternNode *LHSSrc = LHS->getSrcPattern(); const TreePatternNode *RHSSrc = RHS->getSrcPattern(); MVT LHSVT = (LHSSrc->getNumTypes() != 0 ? LHSSrc->getType(0) : MVT::Other); MVT RHSVT = (RHSSrc->getNumTypes() != 0 ? RHSSrc->getType(0) : MVT::Other); if (LHSVT.isVector() != RHSVT.isVector()) return RHSVT.isVector(); if (LHSVT.isFloatingPoint() != RHSVT.isFloatingPoint()) return RHSVT.isFloatingPoint(); // Otherwise, if the patterns might both match, sort based on complexity, // which means that we prefer to match patterns that cover more nodes in the // input over nodes that cover fewer. int LHSSize = LHS->getPatternComplexity(CGP); int RHSSize = RHS->getPatternComplexity(CGP); if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost if (LHSSize < RHSSize) return false; // If the patterns have equal complexity, compare generated instruction cost unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP); unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP); if (LHSCost < RHSCost) return true; if (LHSCost > RHSCost) return false; unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP); unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP); if (LHSPatSize < RHSPatSize) return true; if (LHSPatSize > RHSPatSize) return false; // Sort based on the UID of the pattern, giving us a deterministic ordering // if all other sorting conditions fail. assert(LHS == RHS || LHS->ID != RHS->ID); return LHS->ID < RHS->ID; } }; } // End anonymous namespace void DAGISelEmitter::run(raw_ostream &OS) { emitSourceFileHeader("DAG Instruction Selector for the " + CGP.getTargetInfo().getName() + " target", OS); OS << "// *** NOTE: This file is #included into the middle of the target\n" << "// *** instruction selector class. These functions are really " << "methods.\n\n"; DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n"; for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end(); I != E; ++I) { errs() << "PATTERN: "; I->getSrcPattern()->dump(); errs() << "\nRESULT: "; I->getDstPattern()->dump(); errs() << "\n"; }); // Add all the patterns to a temporary list so we can sort them. std::vector<const PatternToMatch*> Patterns; for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end(); I != E; ++I) Patterns.push_back(&*I); // We want to process the matches in order of minimal cost. Sort the patterns // so the least cost one is at the start. std::sort(Patterns.begin(), Patterns.end(), PatternSortingPredicate(CGP)); // Convert each variant of each pattern into a Matcher. std::vector<Matcher*> PatternMatchers; for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { for (unsigned Variant = 0; ; ++Variant) { if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP)) PatternMatchers.push_back(M); else break; } } std::unique_ptr<Matcher> TheMatcher = llvm::make_unique<ScopeMatcher>(PatternMatchers); OptimizeMatcher(TheMatcher, CGP); //Matcher->dump(); EmitMatcherTable(TheMatcher.get(), CGP, OS); } namespace llvm { void EmitDAGISel(RecordKeeper &RK, raw_ostream &OS) { DAGISelEmitter(RK).run(OS); } } // End llvm namespace
[ "sebi@quantstamp.com" ]
sebi@quantstamp.com
8e9f5215fecaa9e009196ff081d857d8ff7771fb
5ef0619efc9193f5313439e94b87a777861649d2
/exp/basic/pic/Picture.h
8362175b5ba83244eafcca7754aaedf6f1319d7d
[]
no_license
SSPKUZX/cpp-comm
b73f0a6c6efc86afdd609c4c358d7637e0e1ddbd
ba64d086bd7f6eb5f29e6e97f3e5ae88a3d7ae4c
refs/heads/master
2021-01-19T16:40:35.938570
2017-11-16T12:57:19
2017-11-16T12:57:19
101,015,705
2
0
null
null
null
null
UTF-8
C++
false
false
1,106
h
#ifndef PICTURE_H_ #define PICTURE_H_ #include <iostream> class Picture { friend std::ostream& operator<< (std::ostream&, const Picture&); friend Picture frame(const Picture&); friend Picture operator| (const Picture&, const Picture&); friend Picture operator& (const Picture&, const Picture&); public: Picture(); Picture(const char* const*, unsigned int); Picture(const Picture&); ~Picture(); Picture& operator= (const Picture&); private: unsigned int width; unsigned int height; char* data; char& pixelAt(unsigned int row, unsigned int col); char pixelAt(unsigned int row, unsigned int col) const; static unsigned int max(unsigned int left, unsigned int right); void init(unsigned int w, unsigned int h); void copyBlock(unsigned int x, unsigned int y, const Picture& pic); void fillRect(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const char ch); }; std::ostream& operator<< (std::ostream&, const Picture&); Picture operator| (const Picture&, const Picture&); Picture operator& (const Picture&, const Picture&); Picture frame(const Picture&); #endif
[ "948049305@qq.com" ]
948049305@qq.com
13f028b281e5fa4ff5bed94eef525ced586dc92a
0fd86e890bd1e1c915869286b6851b0ed1b1f57b
/2021-2022/summer-contest/01 Vowelless/vowelless.cpp
0b202acad10b27cf913275a7ec38c4ea594e666c
[]
no_license
flaming-snowman/pps
efc30e7aaf354753515c7e3076834948fdccbff2
ec7263d3520ae5fa12c85a2d5fa7f7d0445bc637
refs/heads/master
2023-07-01T23:14:50.929068
2021-08-09T03:55:43
2021-08-09T03:55:43
274,296,679
1
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
// My solution #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; string s; cin >> s; for(char c: s) { if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { n--; } } cout << n << '\n'; }
[ "a.flaming.snowman@gmail.com" ]
a.flaming.snowman@gmail.com
3eb7b105599f70db9b8a0f717af2f0fe4ee39976
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/ic8h18/0.0065/CH3COCH2O
4d6fffa817ac934b84ef726945d0ede2753d2a35
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
842
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0065"; object CH3COCH2O; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 2.81205e-29; boundaryField { boundary { type empty; } } // ************************************************************************* //
[ "jfeatherstone123@gmail.com" ]
jfeatherstone123@gmail.com
079bb2c625c315a8f617d84a85c1f9c6241b0f9b
9b59c3a2a6b248e0b8f4f2f51939844aced729ce
/Step1/neuron.cpp
e69ef8c90f343ebf79c2901d160cfa8b8f56dbd8
[]
no_license
TheEzo/AVS-1
7eb5aea6712826c00f7f83ae8fdf6d77a3cdfa22
64561b863115fce770a459c21bef12cd179d2fad
refs/heads/master
2022-03-13T15:58:42.567818
2019-11-10T10:45:06
2019-11-10T10:45:06
219,592,315
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
/* * Architektury výpočetních systémů (AVS 2019) * Projekt c. 1 (ANN) * Login: xwilla00 */ #include <cstdlib> #include "neuron.h" float evalNeuron( size_t inputSize, size_t neuronCount, const float* input, const float* weights, float bias, size_t neuronId ) { float result = 0; for(int i = 0; i < inputSize; i++) result += input[i] * weights[i * neuronCount + neuronId]; result += bias; return result > 0 ? result : 0; }
[ "tomas.willaschek@nxp.com" ]
tomas.willaschek@nxp.com
0e5a02f2107f66b6536b8c58a55b17640f195c79
34252ecd8762d8c3ece6bac271c9c457202ff1a7
/nnopencl/NetT.h
c9d385330fea1f7dace24c0ad5af85d2aaba070c
[ "MIT" ]
permissive
freegraphics/cpputils
cdf16819e8d4ae10368e3ec84f232af9c5ef4e5c
3f990d4765a50c7428bd6a4929a83ff49d3567bd
refs/heads/master
2020-05-20T18:47:40.529569
2016-09-18T20:24:25
2016-09-18T20:24:25
68,520,367
0
0
null
null
null
null
UTF-8
C++
false
false
6,635
h
#pragma once #include "openclnet.h" namespace opencl { template<typename _InputState,typename _OutputState> struct NetT : public DLNet { public: typedef DLNet::LayersList Layers; protected: typedef DLNet base; public: NetT(DLNetKernels* _kernels) :base(_kernels) { } void load(const CString& _file_name) { base::load(_file_name); } void save(const CString& _file_name) { base::save(_file_name); } void init_net( size_t _batch_size ,size_t _hidden_layer_size,size_t _hidden_layers_count ,real _learning_rate,real _momentum,real _l2_decay ,bool _dropout_mode,real _dropout_prob ,bool _last_layer_half_tanh ,bool _last_layer_single_relu ,bool _last_layer_regression ,bool _run_only_mode ,real _weights_scale_coef ,size_t _dropout_layer_count = 0 ) { create_input(divisible_8(_InputState::size())-1,_batch_size); std::vector<LayerOptions> layers; { LayerOptions opts; opts.out_depth = _hidden_layer_size; opts.relu_mode = true; size_t i = 0; for(i=0;i<_hidden_layers_count;i++) { if(_dropout_layer_count && (i%_dropout_layer_count==_dropout_layer_count/2)) { opts.dropout_mode = _dropout_mode; opts.drop_probability = _dropout_prob; } else { opts.dropout_mode = false; opts.drop_probability = (real)0.0; } layers.push_back(opts); } } if(_last_layer_half_tanh) { LayerOptions opts1; opts1.out_depth = divisible_8(_OutputState::size())-1; layers.push_back(opts1); LayerOptions opts2; opts2.out_depth = opts1.out_depth; opts2.single_half_tanh_mode = true; layers.push_back(opts2); } else if(_last_layer_single_relu) { LayerOptions opts1; opts1.out_depth = divisible_8(_OutputState::size())-1; layers.push_back(opts1); LayerOptions opts2; opts2.out_depth = opts1.out_depth; opts2.single_relu_mode = true; layers.push_back(opts2); } else if(_last_layer_regression) { LayerOptions opts; opts.out_depth = divisible_8(_OutputState::size())-1; opts.regression_mode = true; layers.push_back(opts); } else { LayerOptions opts; opts.out_depth = divisible_8(_OutputState::size())-1; layers.push_back(opts); } NetOptions net_options; net_options.run_only_net_mode = _run_only_mode; net_options.learning_rate = _learning_rate; net_options.momentum = _momentum; net_options.l2_decay = _l2_decay; net_options.weights_scale_coef = _weights_scale_coef; create(layers,net_options); } void init_autoencoder( size_t _batch_size ,size_t _hidden_layer_size,size_t _hidden_layers_count ,size_t _encoded_size ,real _learning_rate,real _momentum,real _l2_decay ,bool _dropout_mode,real _dropout_prob ,bool _run_only_mode ,real _weights_scale_coef ,size_t _dropout_layer_count = 0 ) { VERIFY_EXIT(EQL(divisible_8(_encoded_size)-1,_encoded_size)); create_input(divisible_8(_InputState::size())-1,_batch_size); std::vector<LayerOptions> layers; // 1st part { LayerOptions opts; opts.out_depth = _hidden_layer_size; opts.relu_mode = true; size_t i = 0; for(i=0;i<_hidden_layers_count;i++) { if(_dropout_layer_count && i%_dropout_layer_count==_dropout_layer_count/2) { opts.dropout_mode = _dropout_mode; opts.drop_probability = _dropout_prob; } else { opts.dropout_mode = false; opts.drop_probability = (real)0.0; } layers.push_back(opts); } } // encoded { LayerOptions opts; opts.out_depth = divisible_8(_encoded_size)-1; layers.push_back(opts); } // 2nd part { LayerOptions opts; opts.out_depth = _hidden_layer_size; opts.relu_mode = true; size_t i = 0; for(i=0;i<_hidden_layers_count;i++) { if(_dropout_layer_count && i%_dropout_layer_count==_dropout_layer_count/2) { opts.dropout_mode = _dropout_mode; opts.drop_probability = _dropout_prob; } else { opts.dropout_mode = false; opts.drop_probability = (real)0.0; } layers.push_back(opts); } } // regression { LayerOptions opts; opts.out_depth = divisible_8(_OutputState::size())-1; opts.regression_mode = true; layers.push_back(opts); } NetOptions net_options; net_options.run_only_net_mode = _run_only_mode; net_options.learning_rate = _learning_rate; net_options.momentum = _momentum; net_options.l2_decay = _l2_decay; net_options.weights_scale_coef = _weights_scale_coef; create(layers,net_options); } Data& get_input_dw() { return input_dw; } Layers& get_layers() { return m_layers; } DLNetKernels* get_kernels() { return kernels; } };// template<> struct NetT template<typename _InputState,typename _OutputState> struct NetDataBaseT { public: typedef std::vector<real> WT; typedef _InputState InputState; typedef _OutputState OutputState; InputState input; OutputState output; protected: WT input_w; WT result_w; WT target_w; WT target_mask_w; public: NetDataBaseT() { input_w.resize(InputState::size()); result_w.resize(OutputState::size()); target_w.resize(OutputState::size()); target_mask_w.resize(OutputState::size()); } void to_vec(bool _train_mode) { input.to_vec(input_w); if(_train_mode) { output.to_vec(target_w); output.set_target_mask(target_mask_w); } } void from_vec() { output.from_vec(result_w); } const WT& get_input() const {return input_w;} const WT& get_target() const {return target_w;} const WT& get_target_mask() const {return target_mask_w;} WT& get_result() {return result_w;} void copy_to_net(NetT<InputState,OutputState>& _net,size_t _idx,bool _train_mode,bool _forward_mode) { } void copy_from_net(NetT<InputState,OutputState>& _net,size_t _idx,bool _train_mode,bool _forward_mode) { } };//template<> struct NetDataBaseT template<typename _NetData> struct NetDataHolder : protected std::list<_NetData> { protected: typedef std::list<_NetData> base; public: NetDataHolder() { } _NetData* create() { push_back(_NetData()); return &back(); } _NetData* create(const _NetData& _cd) { push_back(_NetData(_cd)); return &back(); } bool remove(_NetData* _cd) { base::iterator it = begin() ,ite = end() ; for(;it!=ite;++it) { if(EQL(&*it,_cd)) { erase(it); return true; } } return false; } };//template<> struct NetDataHolder }
[ "klizardin@gmail.com" ]
klizardin@gmail.com
8ee2d6b054341c27ddcf5d55f26e5940bfedd8cc
6e115adc9021ceed1b37e44abf3b89db7dc5fa21
/коды пп/final1/all.cpp
ce34a75070b421477f93262d6470fb1e84607833
[]
no_license
inirbayeva/pp1
baef1a8e6b638e62dcb2127e98c8634c2a59b8a3
e01afa0fe4bdb25a9c7a755c916b1e2bca0b0f81
refs/heads/master
2023-03-01T05:41:56.085163
2021-02-06T11:29:09
2021-02-06T11:29:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
835
cpp
#include <iostream> using namespace std; int main(){ int mary[7], mol[] = {1, 2, 5, 10, 20, 50, 100}; for (int i = 0; i < 7; i++) cin >> mary[i]; int n; cin>>n; int m[n]; for (int i = 0; i < n; i++) cin>>m[i]; for (int i = 0; i < n; i++) { int old[7]; for (int j = 0; j < 7; j++) old[j] = mary[j]; for (int j = 6; j >= 0; j--) { if (old[j] > 0) { while(m[i] >= mol[j] && old[j] > 0) { old[j]--; m[i] -= mol[j]; } } } if (m[i] == 0) { cout<< "Transaction accepted!\n"; for (int j = 0; j < 7; j++) mary[j] = old[j]; } else { cout<< "Transaction stopped!\n"; } } }
[ "you@example.com" ]
you@example.com
d35613ad073f6ef2e0b4f9e4dced1732fbd323e1
bbdd63f4403ad2e15dce8dfd5ef35263d2f2bd86
/common/x64/include/Paint.h
bfe3798f7131c1eb2eb94c673658fe13ee72a6f9
[]
no_license
MelodyD/pytest_API
a7d4dcb1bd8ba9b1981ca640080c27e2b5aaa0b7
77e11924e3fec6e3ddbf65f07d05cf77a4fe94ea
refs/heads/main
2023-07-18T10:02:15.382032
2021-09-11T12:57:08
2021-09-11T12:57:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,694
h
/******************************************************************************* * RoadDB Confidential * Copyright (c) RoadDB 2019-2020 * * This software is furnished under license and may be used or * copied only in accordance with the terms of such license. ******************************************************************************* * @file Paint.h * @brief The class definition of Paint. * * Change Log: * Date Author Changes * 2020-06-18 Wei Tian Init version. * ******************************************************************************* */ #pragma once #include <vector> #include <utility> #include <memory> #include "VehicleAPICommon.h" #include "Line.h" #include "LogicTypes.h" #include <memory> namespace RDBVehicleAPI { class Line; class Paint : public Visualization, public std::enable_shared_from_this<Paint> { public: ~Paint(); /** * @brief Get the line object expressed this paint. * @return line object. */ std::shared_ptr<const Line> &getExpressedLine() { return expressedLine_; } private: void setExpressedLine(const std::shared_ptr<const Line> &line) { expressedLine_ = line; } objectID_t getExpressedLineID() { return expressedLineId_; } Paint(const objectID_t &id, const objectID_t &expressedLineId); Paint() = delete; Paint(const Paint &obj) = delete; Paint &operator=(const Paint &obj) = delete; private: std::shared_ptr<const Line> expressedLine_; objectID_t expressedLineId_; FRIEND_2_ROADDATAINFO; }; } /* namespace RDBVehicleAPI */
[ "guangli.bao@roaddb.com" ]
guangli.bao@roaddb.com
f99101e27098783a1e4590e38fe08e41c3025d5c
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2458486_0/C++/NovGosh/main.cpp
a18a78dba99f1178310fb39f5547e29614f26a59
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,677
cpp
#include <cstdio> #include <fstream> #include <iostream> #include <set> #include <map> #include <queue> #include <deque> #include <cmath> #include <vector> #include <bitset> #include <string> #include <cstring> #include <algorithm> #include <ctime> #include <cstdlib> #include <cassert> #define pb push_back #define mp make_pair #define sz(A) (int) (A).size() #define eprintf(...) fprintf(stderr, __VA_ARGS__) #define eputs(A) fputs((A), stderr) #define sqr(A) ((A) * (A)) #define x first #define y second using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef long double LD; typedef pair <int, int> pii; const int T = 25; const int N = 20; const int SZ = 1 << N; struct node { bool flag; vector <int> res; node (bool flag = false) { node :: flag = flag; } node (bool flag, vector <int> res) { node :: flag = flag; node :: res = res; } }; int t, n, k, type[N], fcnt[T]; vector <int> tmp, v[N]; node dp[SZ]; void update (node & v, node a, int d) { tmp = a.res; tmp.push_back(d); if (!v.flag || v.res > tmp) v = node(true, tmp); } bool have (int mask, int num) { int cnt = fcnt[num]; for (int i = 0; i < n; i++) if (mask >> i & 1) { if (type[i] == num) cnt--; for (int j = 0; j < sz(v[i]); j++) if (v[i][j] == num) cnt++; } return cnt; } int main () { #ifdef DEBUG freopen(".in", "r", stdin); freopen(".out", "w", stdout); #endif cin >> t; for (int test = 0; test < t; test++) { cerr << test << endl; memset(fcnt, 0, sizeof(fcnt)); for (int i = 0; i < SZ; i++) dp[i] = node(); cin >> k >> n; cerr << k << ' ' << n << endl; for (int i = 0; i < k; i++) { int val; cin >> val; fcnt[val - 1]++; } for (int i = 0; i < n; i++) { cin >> type[i]; v[i].clear(); type[i]--; int cnt; cin >> cnt; for (int j = 0; j < cnt; j++) { int num; cin >> num; v[i].push_back(num - 1); } } dp[0] = node(true); for (int i = 0; i < (1 << n); i++) if (dp[i].flag) { for (int j = 0; j < n; j++) { if (!(i >> j & 1) && have(i, type[j])) { update(dp[i ^ (1 << j)], dp[i], j); } } } int last = (1 << n) - 1; printf("Case #%d: ", test + 1); if (dp[last].flag) { for (int i = 0; i < n; i++) printf("%d ", dp[last].res[i] + 1); puts(""); } else puts("IMPOSSIBLE"); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
1d2d13273e6152f04fb937537a50a0aae67b5b58
09c2c8d7f42dd5c678b064fd56bc65d49af16b3c
/dotenv.h
765692c695b17acec7b171908e3a2588d1966d75
[ "MIT" ]
permissive
sryze/dotenv
040e04e0cab99bba1d691ac657098fc327880a2c
b30ceb7b5de46a71c4bf682aa338d007b447964d
refs/heads/master
2023-04-01T09:15:31.697300
2021-04-09T18:40:39
2021-04-09T18:40:39
286,269,276
0
0
null
null
null
null
UTF-8
C++
false
false
351
h
#ifndef DOTENV_H #define DOTENV_H #include <string> namespace dotenv { std::string get(const std::string &name, const std::string &default_value = ""); void set(const std::string &name, const std::string &value); void unset(const std::string &name); void load(const std::string &filename = ".env"); } // namespace dotenv #endif
[ "sryze@protonmail.com" ]
sryze@protonmail.com
ef4da3ca9412ed3e71197c073ec6e75d8275b974
f69403a1fac323997daf0a44d8058f0e1b39709a
/csharp/src/corelib/WideChar.cpp
150372edc69f8187332de34b6f0852449e06bc10
[]
no_license
nfeltman/RenderGen
d4858e5559e1cfadc6748cd4e5cb4ad4cd4f900b
9e44b92da4da87d3ac35569f3449f8212d64f36b
refs/heads/master
2021-01-21T07:57:56.049014
2016-01-19T13:19:50
2016-01-19T13:19:50
6,394,209
0
0
null
null
null
null
UTF-8
C++
false
false
1,655
cpp
#include "WideChar.h" #ifdef WINDOWS_PLATFORM #include <Windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <memory.h> char * WideCharToMByte(const wchar_t * buffer, int length) { #ifdef WINDOWS_PLATFORM size_t requiredBufferSize; requiredBufferSize = WideCharToMultiByte(CP_OEMCP, NULL, buffer, length, 0, 0, NULL, NULL)+1; if (requiredBufferSize) { char * multiByteBuffer = new char[requiredBufferSize]; WideCharToMultiByte(CP_OEMCP, NULL, buffer, length, multiByteBuffer, requiredBufferSize, NULL, NULL); multiByteBuffer[requiredBufferSize-1] = 0; return multiByteBuffer; } else return 0; #else size_t ret; char * dest = new char[length*2 + 1]; memset(dest, 0, sizeof(char)*(length*2+1)); wcstombs_s(&ret, dest, length*2+1, buffer, _TRUNCATE); return dest; #endif } wchar_t * MByteToWideChar(const char * buffer, int length) { #ifdef WINDOWS_PLATFORM // regard as ansi int rlength = MultiByteToWideChar(CP_ACP, 0, buffer, length, NULL, 0)-1; if (length < 0) length = 0; if (length != 0) { wchar_t * rbuffer = new wchar_t[length+1]; MultiByteToWideChar(CP_ACP, NULL, buffer, length, rbuffer, length+1); return rbuffer; } else return 0; #else size_t ret; wchar_t * dest = new wchar_t[length+1]; memset(dest, 0, sizeof(wchar_t)*(length+1)); mbstowcs_s(&ret, dest, length+1, buffer, _TRUNCATE); return dest; #endif } void MByteToWideChar(wchar_t * buffer, int bufferSize, const char * str, int length) { #ifdef WINDOWS_PLATFORM // regard as ansi MultiByteToWideChar(CP_ACP, NULL, str, length, buffer, bufferSize); #else size_t ret; mbstowcs_s(&ret, buffer, bufferSize, str, _TRUNCATE); #endif }
[ "yonghe@outlook.com" ]
yonghe@outlook.com
f10841b65b4b0a9c84454ab6bd4c6125f7453c3f
e72a75dcf0307af7ee53a29155bf61de13263020
/src/points_to_analysis/Common/Include/context.h
b2cb5adc8d08b5de1b027501245fa61c2001556d
[]
no_license
tapicer/resource-contracts-.net
f90e38a8c4e62c5408e70232f23edf5a1e641c30
f7b4977e6e004ec16dde4ad65266bb46417d2234
refs/heads/master
2020-03-28T00:43:48.508821
2016-12-05T17:03:56
2016-12-05T17:03:56
4,037,508
0
0
null
null
null
null
UTF-8
C++
false
false
78,683
h
#pragma warning( disable: 4049 ) /* more than 64k source lines */ /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0347 */ /* at Tue Sep 25 01:28:41 2001 */ /* Compiler settings for context.idl: Oicf, W0, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext error checks: allocation ref bounds_check enum stub_data , no_format_optimization VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 440 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __context_h__ #define __context_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IVsUserContext_FWD_DEFINED__ #define __IVsUserContext_FWD_DEFINED__ typedef interface IVsUserContext IVsUserContext; #endif /* __IVsUserContext_FWD_DEFINED__ */ #ifndef __IVsUserContextUpdate_FWD_DEFINED__ #define __IVsUserContextUpdate_FWD_DEFINED__ typedef interface IVsUserContextUpdate IVsUserContextUpdate; #endif /* __IVsUserContextUpdate_FWD_DEFINED__ */ #ifndef __IVsProvideUserContext_FWD_DEFINED__ #define __IVsProvideUserContext_FWD_DEFINED__ typedef interface IVsProvideUserContext IVsProvideUserContext; #endif /* __IVsProvideUserContext_FWD_DEFINED__ */ #ifndef __IVsProvideUserContextForObject_FWD_DEFINED__ #define __IVsProvideUserContextForObject_FWD_DEFINED__ typedef interface IVsProvideUserContextForObject IVsProvideUserContextForObject; #endif /* __IVsProvideUserContextForObject_FWD_DEFINED__ */ #ifndef __IVsUserContextItemCollection_FWD_DEFINED__ #define __IVsUserContextItemCollection_FWD_DEFINED__ typedef interface IVsUserContextItemCollection IVsUserContextItemCollection; #endif /* __IVsUserContextItemCollection_FWD_DEFINED__ */ #ifndef __IVsUserContextItem_FWD_DEFINED__ #define __IVsUserContextItem_FWD_DEFINED__ typedef interface IVsUserContextItem IVsUserContextItem; #endif /* __IVsUserContextItem_FWD_DEFINED__ */ #ifndef __IVsHelpAttributeList_FWD_DEFINED__ #define __IVsHelpAttributeList_FWD_DEFINED__ typedef interface IVsHelpAttributeList IVsHelpAttributeList; #endif /* __IVsHelpAttributeList_FWD_DEFINED__ */ #ifndef __IVsMonitorUserContext_FWD_DEFINED__ #define __IVsMonitorUserContext_FWD_DEFINED__ typedef interface IVsMonitorUserContext IVsMonitorUserContext; #endif /* __IVsMonitorUserContext_FWD_DEFINED__ */ #ifndef __IVsUserContextItemProvider_FWD_DEFINED__ #define __IVsUserContextItemProvider_FWD_DEFINED__ typedef interface IVsUserContextItemProvider IVsUserContextItemProvider; #endif /* __IVsUserContextItemProvider_FWD_DEFINED__ */ #ifndef __IVsUserContextCustomize_FWD_DEFINED__ #define __IVsUserContextCustomize_FWD_DEFINED__ typedef interface IVsUserContextCustomize IVsUserContextCustomize; #endif /* __IVsUserContextCustomize_FWD_DEFINED__ */ #ifndef __IVsUserContextItemEvents_FWD_DEFINED__ #define __IVsUserContextItemEvents_FWD_DEFINED__ typedef interface IVsUserContextItemEvents IVsUserContextItemEvents; #endif /* __IVsUserContextItemEvents_FWD_DEFINED__ */ #ifndef __VsContextClass_FWD_DEFINED__ #define __VsContextClass_FWD_DEFINED__ #ifdef __cplusplus typedef class VsContextClass VsContextClass; #else typedef struct VsContextClass VsContextClass; #endif /* __cplusplus */ #endif /* __VsContextClass_FWD_DEFINED__ */ /* header files for imported files */ #include "oleidl.h" #include "servprov.h" #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); /* interface __MIDL_itf_context_0000 */ /* [local] */ #pragma once typedef DWORD_PTR VSCOOKIE; typedef DWORD_PTR VSCONTEXTUPDATECOOKIE; typedef DWORD_PTR VSSUBCONTEXTCOOKIE; typedef DWORD_PTR VSINFOPROVIDERCOOKIE; typedef enum tagVsUserContextPriority { VSUC_Priority_None = 0, VSUC_Priority_Ambient = 100, VSUC_Priority_State = 200, VSUC_Priority_Project = 300, VSUC_Priority_ProjectItem = 400, VSUC_Priority_Window = 500, VSUC_Priority_Selection = 600, VSUC_Priority_MarkerSel = 700, VSUC_Priority_Enterprise = 800, VSUC_Priority_WindowFrame = 900, VSUC_Priority_ToolWndSel = 1000, VSUC_Priority_Highest = 1100 } VSUSERCONTEXTPRIORITY; typedef enum tagVsUserContextAttributeUsage { VSUC_Usage_Filter = 0, VSUC_Usage_Lookup = 1, VSUC_Usage_LookupF1 = 2, VSUC_Usage_Lookup_CaseSensitive = 3, VSUC_Usage_LookupF1_CaseSensitive = 4 } VSUSERCONTEXTATTRIBUTEUSAGE; extern RPC_IF_HANDLE __MIDL_itf_context_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0000_v0_0_s_ifspec; #ifndef __IVsUserContext_INTERFACE_DEFINED__ #define __IVsUserContext_INTERFACE_DEFINED__ /* interface IVsUserContext */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContext; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("761081DF-D45F-4683-9B9E-1B7241E56F5C") IVsUserContext : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE AddAttribute( /* [in] */ VSUSERCONTEXTATTRIBUTEUSAGE usage, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAttribute( /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue) = 0; virtual HRESULT STDMETHODCALLTYPE AddSubcontext( /* [in] */ IVsUserContext *pSubCtx, /* [in] */ int lPriority, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveSubcontext( /* [in] */ VSCOOKIE dwcookie) = 0; virtual HRESULT STDMETHODCALLTYPE CountAttributes( /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ int *pc) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttribute( /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue) = 0; virtual HRESULT STDMETHODCALLTYPE CountSubcontexts( /* [retval][out] */ int *pc) = 0; virtual HRESULT STDMETHODCALLTYPE GetSubcontext( /* [in] */ int i, /* [retval][out] */ IVsUserContext **ppSubCtx) = 0; virtual HRESULT STDMETHODCALLTYPE IsDirty( /* [retval][out] */ BOOL *pfDirty) = 0; virtual HRESULT STDMETHODCALLTYPE SetDirty( /* [in] */ BOOL fDirty) = 0; virtual HRESULT STDMETHODCALLTYPE Update( void) = 0; virtual HRESULT STDMETHODCALLTYPE AdviseUpdate( /* [in] */ IVsUserContextUpdate *pUpdate, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE UnadviseUpdate( /* [in] */ VSCOOKIE dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttrUsage( /* [in] */ int index, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ VSUSERCONTEXTATTRIBUTEUSAGE *pUsage) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAllSubcontext( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetPriority( /* [retval][out] */ int *lPriority) = 0; virtual HRESULT STDMETHODCALLTYPE RemoveAttributeIncludeChildren( /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributePri( /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ int *piPriority, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue) = 0; }; #else /* C style interface */ typedef struct IVsUserContextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContext * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContext * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContext * This); HRESULT ( STDMETHODCALLTYPE *AddAttribute )( IVsUserContext * This, /* [in] */ VSUSERCONTEXTATTRIBUTEUSAGE usage, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); HRESULT ( STDMETHODCALLTYPE *RemoveAttribute )( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); HRESULT ( STDMETHODCALLTYPE *AddSubcontext )( IVsUserContext * This, /* [in] */ IVsUserContext *pSubCtx, /* [in] */ int lPriority, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *RemoveSubcontext )( IVsUserContext * This, /* [in] */ VSCOOKIE dwcookie); HRESULT ( STDMETHODCALLTYPE *CountAttributes )( IVsUserContext * This, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ int *pc); HRESULT ( STDMETHODCALLTYPE *GetAttribute )( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); HRESULT ( STDMETHODCALLTYPE *CountSubcontexts )( IVsUserContext * This, /* [retval][out] */ int *pc); HRESULT ( STDMETHODCALLTYPE *GetSubcontext )( IVsUserContext * This, /* [in] */ int i, /* [retval][out] */ IVsUserContext **ppSubCtx); HRESULT ( STDMETHODCALLTYPE *IsDirty )( IVsUserContext * This, /* [retval][out] */ BOOL *pfDirty); HRESULT ( STDMETHODCALLTYPE *SetDirty )( IVsUserContext * This, /* [in] */ BOOL fDirty); HRESULT ( STDMETHODCALLTYPE *Update )( IVsUserContext * This); HRESULT ( STDMETHODCALLTYPE *AdviseUpdate )( IVsUserContext * This, /* [in] */ IVsUserContextUpdate *pUpdate, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *UnadviseUpdate )( IVsUserContext * This, /* [in] */ VSCOOKIE dwCookie); HRESULT ( STDMETHODCALLTYPE *GetAttrUsage )( IVsUserContext * This, /* [in] */ int index, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ VSUSERCONTEXTATTRIBUTEUSAGE *pUsage); HRESULT ( STDMETHODCALLTYPE *RemoveAllSubcontext )( IVsUserContext * This); HRESULT ( STDMETHODCALLTYPE *GetPriority )( IVsUserContext * This, /* [retval][out] */ int *lPriority); HRESULT ( STDMETHODCALLTYPE *RemoveAttributeIncludeChildren )( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); HRESULT ( STDMETHODCALLTYPE *GetAttributePri )( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ int *piPriority, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); END_INTERFACE } IVsUserContextVtbl; interface IVsUserContext { CONST_VTBL struct IVsUserContextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContext_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContext_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContext_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContext_AddAttribute(This,usage,szName,szValue) \ (This)->lpVtbl -> AddAttribute(This,usage,szName,szValue) #define IVsUserContext_RemoveAttribute(This,szName,szValue) \ (This)->lpVtbl -> RemoveAttribute(This,szName,szValue) #define IVsUserContext_AddSubcontext(This,pSubCtx,lPriority,pdwCookie) \ (This)->lpVtbl -> AddSubcontext(This,pSubCtx,lPriority,pdwCookie) #define IVsUserContext_RemoveSubcontext(This,dwcookie) \ (This)->lpVtbl -> RemoveSubcontext(This,dwcookie) #define IVsUserContext_CountAttributes(This,pszName,fIncludeChildren,pc) \ (This)->lpVtbl -> CountAttributes(This,pszName,fIncludeChildren,pc) #define IVsUserContext_GetAttribute(This,iAttribute,pszName,fIncludeChildren,pbstrName,pbstrValue) \ (This)->lpVtbl -> GetAttribute(This,iAttribute,pszName,fIncludeChildren,pbstrName,pbstrValue) #define IVsUserContext_CountSubcontexts(This,pc) \ (This)->lpVtbl -> CountSubcontexts(This,pc) #define IVsUserContext_GetSubcontext(This,i,ppSubCtx) \ (This)->lpVtbl -> GetSubcontext(This,i,ppSubCtx) #define IVsUserContext_IsDirty(This,pfDirty) \ (This)->lpVtbl -> IsDirty(This,pfDirty) #define IVsUserContext_SetDirty(This,fDirty) \ (This)->lpVtbl -> SetDirty(This,fDirty) #define IVsUserContext_Update(This) \ (This)->lpVtbl -> Update(This) #define IVsUserContext_AdviseUpdate(This,pUpdate,pdwCookie) \ (This)->lpVtbl -> AdviseUpdate(This,pUpdate,pdwCookie) #define IVsUserContext_UnadviseUpdate(This,dwCookie) \ (This)->lpVtbl -> UnadviseUpdate(This,dwCookie) #define IVsUserContext_GetAttrUsage(This,index,fIncludeChildren,pUsage) \ (This)->lpVtbl -> GetAttrUsage(This,index,fIncludeChildren,pUsage) #define IVsUserContext_RemoveAllSubcontext(This) \ (This)->lpVtbl -> RemoveAllSubcontext(This) #define IVsUserContext_GetPriority(This,lPriority) \ (This)->lpVtbl -> GetPriority(This,lPriority) #define IVsUserContext_RemoveAttributeIncludeChildren(This,szName,szValue) \ (This)->lpVtbl -> RemoveAttributeIncludeChildren(This,szName,szValue) #define IVsUserContext_GetAttributePri(This,iAttribute,pszName,fIncludeChildren,piPriority,pbstrName,pbstrValue) \ (This)->lpVtbl -> GetAttributePri(This,iAttribute,pszName,fIncludeChildren,piPriority,pbstrName,pbstrValue) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContext_AddAttribute_Proxy( IVsUserContext * This, /* [in] */ VSUSERCONTEXTATTRIBUTEUSAGE usage, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); void __RPC_STUB IVsUserContext_AddAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveAttribute_Proxy( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); void __RPC_STUB IVsUserContext_RemoveAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_AddSubcontext_Proxy( IVsUserContext * This, /* [in] */ IVsUserContext *pSubCtx, /* [in] */ int lPriority, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsUserContext_AddSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveSubcontext_Proxy( IVsUserContext * This, /* [in] */ VSCOOKIE dwcookie); void __RPC_STUB IVsUserContext_RemoveSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_CountAttributes_Proxy( IVsUserContext * This, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ int *pc); void __RPC_STUB IVsUserContext_CountAttributes_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetAttribute_Proxy( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); void __RPC_STUB IVsUserContext_GetAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_CountSubcontexts_Proxy( IVsUserContext * This, /* [retval][out] */ int *pc); void __RPC_STUB IVsUserContext_CountSubcontexts_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetSubcontext_Proxy( IVsUserContext * This, /* [in] */ int i, /* [retval][out] */ IVsUserContext **ppSubCtx); void __RPC_STUB IVsUserContext_GetSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_IsDirty_Proxy( IVsUserContext * This, /* [retval][out] */ BOOL *pfDirty); void __RPC_STUB IVsUserContext_IsDirty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_SetDirty_Proxy( IVsUserContext * This, /* [in] */ BOOL fDirty); void __RPC_STUB IVsUserContext_SetDirty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_Update_Proxy( IVsUserContext * This); void __RPC_STUB IVsUserContext_Update_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_AdviseUpdate_Proxy( IVsUserContext * This, /* [in] */ IVsUserContextUpdate *pUpdate, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsUserContext_AdviseUpdate_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_UnadviseUpdate_Proxy( IVsUserContext * This, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsUserContext_UnadviseUpdate_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetAttrUsage_Proxy( IVsUserContext * This, /* [in] */ int index, /* [in] */ BOOL fIncludeChildren, /* [retval][out] */ VSUSERCONTEXTATTRIBUTEUSAGE *pUsage); void __RPC_STUB IVsUserContext_GetAttrUsage_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveAllSubcontext_Proxy( IVsUserContext * This); void __RPC_STUB IVsUserContext_RemoveAllSubcontext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetPriority_Proxy( IVsUserContext * This, /* [retval][out] */ int *lPriority); void __RPC_STUB IVsUserContext_GetPriority_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_RemoveAttributeIncludeChildren_Proxy( IVsUserContext * This, /* [in] */ LPCOLESTR szName, /* [in] */ LPCOLESTR szValue); void __RPC_STUB IVsUserContext_RemoveAttributeIncludeChildren_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContext_GetAttributePri_Proxy( IVsUserContext * This, /* [in] */ int iAttribute, /* [in] */ LPCOLESTR pszName, /* [in] */ BOOL fIncludeChildren, /* [out] */ int *piPriority, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); void __RPC_STUB IVsUserContext_GetAttributePri_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContext_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextUpdate_INTERFACE_DEFINED__ #define __IVsUserContextUpdate_INTERFACE_DEFINED__ /* interface IVsUserContextUpdate */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextUpdate; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("F5ED7D1C-61B6-428A-8129-E13B36D9E9A7") IVsUserContextUpdate : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE UpdateUserContext( /* [in] */ IVsUserContext *pCtx, /* [in] */ VSCOOKIE dwCookie) = 0; }; #else /* C style interface */ typedef struct IVsUserContextUpdateVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextUpdate * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextUpdate * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextUpdate * This); HRESULT ( STDMETHODCALLTYPE *UpdateUserContext )( IVsUserContextUpdate * This, /* [in] */ IVsUserContext *pCtx, /* [in] */ VSCOOKIE dwCookie); END_INTERFACE } IVsUserContextUpdateVtbl; interface IVsUserContextUpdate { CONST_VTBL struct IVsUserContextUpdateVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextUpdate_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextUpdate_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextUpdate_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextUpdate_UpdateUserContext(This,pCtx,dwCookie) \ (This)->lpVtbl -> UpdateUserContext(This,pCtx,dwCookie) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextUpdate_UpdateUserContext_Proxy( IVsUserContextUpdate * This, /* [in] */ IVsUserContext *pCtx, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsUserContextUpdate_UpdateUserContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextUpdate_INTERFACE_DEFINED__ */ #ifndef __IVsProvideUserContext_INTERFACE_DEFINED__ #define __IVsProvideUserContext_INTERFACE_DEFINED__ /* interface IVsProvideUserContext */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsProvideUserContext; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("997D7904-D948-4C8B-8BAB-0BDA1E212F6E") IVsProvideUserContext : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetUserContext( /* [retval][out] */ IVsUserContext **ppctx) = 0; }; #else /* C style interface */ typedef struct IVsProvideUserContextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsProvideUserContext * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsProvideUserContext * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsProvideUserContext * This); HRESULT ( STDMETHODCALLTYPE *GetUserContext )( IVsProvideUserContext * This, /* [retval][out] */ IVsUserContext **ppctx); END_INTERFACE } IVsProvideUserContextVtbl; interface IVsProvideUserContext { CONST_VTBL struct IVsProvideUserContextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsProvideUserContext_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsProvideUserContext_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsProvideUserContext_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsProvideUserContext_GetUserContext(This,ppctx) \ (This)->lpVtbl -> GetUserContext(This,ppctx) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsProvideUserContext_GetUserContext_Proxy( IVsProvideUserContext * This, /* [retval][out] */ IVsUserContext **ppctx); void __RPC_STUB IVsProvideUserContext_GetUserContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsProvideUserContext_INTERFACE_DEFINED__ */ #ifndef __IVsProvideUserContextForObject_INTERFACE_DEFINED__ #define __IVsProvideUserContextForObject_INTERFACE_DEFINED__ /* interface IVsProvideUserContextForObject */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsProvideUserContextForObject; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("F98CCC8A-9C5F-41EB-8421-711C0F1880E6") IVsProvideUserContextForObject : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetObjectContext( /* [in] */ IUnknown *punk, /* [retval][out] */ IVsUserContext **ppctx) = 0; }; #else /* C style interface */ typedef struct IVsProvideUserContextForObjectVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsProvideUserContextForObject * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsProvideUserContextForObject * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsProvideUserContextForObject * This); HRESULT ( STDMETHODCALLTYPE *GetObjectContext )( IVsProvideUserContextForObject * This, /* [in] */ IUnknown *punk, /* [retval][out] */ IVsUserContext **ppctx); END_INTERFACE } IVsProvideUserContextForObjectVtbl; interface IVsProvideUserContextForObject { CONST_VTBL struct IVsProvideUserContextForObjectVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsProvideUserContextForObject_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsProvideUserContextForObject_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsProvideUserContextForObject_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsProvideUserContextForObject_GetObjectContext(This,punk,ppctx) \ (This)->lpVtbl -> GetObjectContext(This,punk,ppctx) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsProvideUserContextForObject_GetObjectContext_Proxy( IVsProvideUserContextForObject * This, /* [in] */ IUnknown *punk, /* [retval][out] */ IVsUserContext **ppctx); void __RPC_STUB IVsProvideUserContextForObject_GetObjectContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsProvideUserContextForObject_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextItemCollection_INTERFACE_DEFINED__ #define __IVsUserContextItemCollection_INTERFACE_DEFINED__ /* interface IVsUserContextItemCollection */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextItemCollection; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("2A6DE4A2-5B3D-46EB-A65C-24C4EF4F396F") IVsUserContextItemCollection : public IUnknown { public: virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( /* [in] */ VARIANT index, /* [retval][out] */ IVsUserContextItem **ppItem) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( /* [retval][out] */ IUnknown **pEnum) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Count( /* [retval][out] */ long *pCount) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ItemAt( /* [in] */ long index, /* [retval][out] */ IVsUserContextItem **ppItem) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemCollectionVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItemCollection * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItemCollection * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItemCollection * This); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( IVsUserContextItemCollection * This, /* [in] */ VARIANT index, /* [retval][out] */ IVsUserContextItem **ppItem); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( IVsUserContextItemCollection * This, /* [retval][out] */ IUnknown **pEnum); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( IVsUserContextItemCollection * This, /* [retval][out] */ long *pCount); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemAt )( IVsUserContextItemCollection * This, /* [in] */ long index, /* [retval][out] */ IVsUserContextItem **ppItem); END_INTERFACE } IVsUserContextItemCollectionVtbl; interface IVsUserContextItemCollection { CONST_VTBL struct IVsUserContextItemCollectionVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItemCollection_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItemCollection_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItemCollection_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItemCollection_get_Item(This,index,ppItem) \ (This)->lpVtbl -> get_Item(This,index,ppItem) #define IVsUserContextItemCollection_get__NewEnum(This,pEnum) \ (This)->lpVtbl -> get__NewEnum(This,pEnum) #define IVsUserContextItemCollection_get_Count(This,pCount) \ (This)->lpVtbl -> get_Count(This,pCount) #define IVsUserContextItemCollection_get_ItemAt(This,index,ppItem) \ (This)->lpVtbl -> get_ItemAt(This,index,ppItem) #endif /* COBJMACROS */ #endif /* C style interface */ /* [id][propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get_Item_Proxy( IVsUserContextItemCollection * This, /* [in] */ VARIANT index, /* [retval][out] */ IVsUserContextItem **ppItem); void __RPC_STUB IVsUserContextItemCollection_get_Item_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [id][propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get__NewEnum_Proxy( IVsUserContextItemCollection * This, /* [retval][out] */ IUnknown **pEnum); void __RPC_STUB IVsUserContextItemCollection_get__NewEnum_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get_Count_Proxy( IVsUserContextItemCollection * This, /* [retval][out] */ long *pCount); void __RPC_STUB IVsUserContextItemCollection_get_Count_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItemCollection_get_ItemAt_Proxy( IVsUserContextItemCollection * This, /* [in] */ long index, /* [retval][out] */ IVsUserContextItem **ppItem); void __RPC_STUB IVsUserContextItemCollection_get_ItemAt_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItemCollection_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextItem_INTERFACE_DEFINED__ #define __IVsUserContextItem_INTERFACE_DEFINED__ /* interface IVsUserContextItem */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextItem; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("720B8500-17B3-4C89-AE84-2CFE7251B4B8") IVsUserContextItem : public IUnknown { public: virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Name( /* [retval][out] */ BSTR *pbstrName) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_Command( /* [retval][out] */ BSTR *pbstrCommand) = 0; virtual HRESULT STDMETHODCALLTYPE CountAttributes( /* [in] */ LPCOLESTR pszAttrName, /* [retval][out] */ int *pc) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttribute( /* [in] */ LPCOLESTR pszAttrName, /* [in] */ int index, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItem * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItem * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItem * This); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrName); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_Command )( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrCommand); HRESULT ( STDMETHODCALLTYPE *CountAttributes )( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [retval][out] */ int *pc); HRESULT ( STDMETHODCALLTYPE *GetAttribute )( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [in] */ int index, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); END_INTERFACE } IVsUserContextItemVtbl; interface IVsUserContextItem { CONST_VTBL struct IVsUserContextItemVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItem_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItem_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItem_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItem_get_Name(This,pbstrName) \ (This)->lpVtbl -> get_Name(This,pbstrName) #define IVsUserContextItem_get_Command(This,pbstrCommand) \ (This)->lpVtbl -> get_Command(This,pbstrCommand) #define IVsUserContextItem_CountAttributes(This,pszAttrName,pc) \ (This)->lpVtbl -> CountAttributes(This,pszAttrName,pc) #define IVsUserContextItem_GetAttribute(This,pszAttrName,index,pbstrName,pbstrValue) \ (This)->lpVtbl -> GetAttribute(This,pszAttrName,index,pbstrName,pbstrValue) #endif /* COBJMACROS */ #endif /* C style interface */ /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItem_get_Name_Proxy( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrName); void __RPC_STUB IVsUserContextItem_get_Name_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsUserContextItem_get_Command_Proxy( IVsUserContextItem * This, /* [retval][out] */ BSTR *pbstrCommand); void __RPC_STUB IVsUserContextItem_get_Command_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItem_CountAttributes_Proxy( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [retval][out] */ int *pc); void __RPC_STUB IVsUserContextItem_CountAttributes_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItem_GetAttribute_Proxy( IVsUserContextItem * This, /* [in] */ LPCOLESTR pszAttrName, /* [in] */ int index, /* [out] */ BSTR *pbstrName, /* [retval][out] */ BSTR *pbstrValue); void __RPC_STUB IVsUserContextItem_GetAttribute_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItem_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0259 */ /* [local] */ typedef enum tagAttrValueType { VSHAL_Real = 0, VSHAL_Display = 1 } ATTRVALUETYPE; extern RPC_IF_HANDLE __MIDL_itf_context_0259_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0259_v0_0_s_ifspec; #ifndef __IVsHelpAttributeList_INTERFACE_DEFINED__ #define __IVsHelpAttributeList_INTERFACE_DEFINED__ /* interface IVsHelpAttributeList */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsHelpAttributeList; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0A56FB1E-1B2F-4699-8178-63B98E816F35") IVsHelpAttributeList : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetAttributeName( /* [out] */ BSTR *bstrName) = 0; virtual HRESULT STDMETHODCALLTYPE GetCount( /* [out] */ int *pCount) = 0; virtual HRESULT STDMETHODCALLTYPE UpdateAttributeStatus( /* [in] */ BOOL *afActive) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributeStatusVal( /* [in] */ BSTR bstrValue, /* [in] */ ATTRVALUETYPE type, /* [out] */ BOOL *pfActive) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributeStatusIndex( /* [in] */ int index, /* [out] */ BOOL *pfActive) = 0; virtual HRESULT STDMETHODCALLTYPE GetAttributeValue( /* [in] */ int index, /* [in] */ ATTRVALUETYPE type, /* [out] */ BSTR *pbstrValue) = 0; }; #else /* C style interface */ typedef struct IVsHelpAttributeListVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsHelpAttributeList * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsHelpAttributeList * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsHelpAttributeList * This); HRESULT ( STDMETHODCALLTYPE *GetAttributeName )( IVsHelpAttributeList * This, /* [out] */ BSTR *bstrName); HRESULT ( STDMETHODCALLTYPE *GetCount )( IVsHelpAttributeList * This, /* [out] */ int *pCount); HRESULT ( STDMETHODCALLTYPE *UpdateAttributeStatus )( IVsHelpAttributeList * This, /* [in] */ BOOL *afActive); HRESULT ( STDMETHODCALLTYPE *GetAttributeStatusVal )( IVsHelpAttributeList * This, /* [in] */ BSTR bstrValue, /* [in] */ ATTRVALUETYPE type, /* [out] */ BOOL *pfActive); HRESULT ( STDMETHODCALLTYPE *GetAttributeStatusIndex )( IVsHelpAttributeList * This, /* [in] */ int index, /* [out] */ BOOL *pfActive); HRESULT ( STDMETHODCALLTYPE *GetAttributeValue )( IVsHelpAttributeList * This, /* [in] */ int index, /* [in] */ ATTRVALUETYPE type, /* [out] */ BSTR *pbstrValue); END_INTERFACE } IVsHelpAttributeListVtbl; interface IVsHelpAttributeList { CONST_VTBL struct IVsHelpAttributeListVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsHelpAttributeList_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsHelpAttributeList_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsHelpAttributeList_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsHelpAttributeList_GetAttributeName(This,bstrName) \ (This)->lpVtbl -> GetAttributeName(This,bstrName) #define IVsHelpAttributeList_GetCount(This,pCount) \ (This)->lpVtbl -> GetCount(This,pCount) #define IVsHelpAttributeList_UpdateAttributeStatus(This,afActive) \ (This)->lpVtbl -> UpdateAttributeStatus(This,afActive) #define IVsHelpAttributeList_GetAttributeStatusVal(This,bstrValue,type,pfActive) \ (This)->lpVtbl -> GetAttributeStatusVal(This,bstrValue,type,pfActive) #define IVsHelpAttributeList_GetAttributeStatusIndex(This,index,pfActive) \ (This)->lpVtbl -> GetAttributeStatusIndex(This,index,pfActive) #define IVsHelpAttributeList_GetAttributeValue(This,index,type,pbstrValue) \ (This)->lpVtbl -> GetAttributeValue(This,index,type,pbstrValue) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeName_Proxy( IVsHelpAttributeList * This, /* [out] */ BSTR *bstrName); void __RPC_STUB IVsHelpAttributeList_GetAttributeName_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetCount_Proxy( IVsHelpAttributeList * This, /* [out] */ int *pCount); void __RPC_STUB IVsHelpAttributeList_GetCount_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_UpdateAttributeStatus_Proxy( IVsHelpAttributeList * This, /* [in] */ BOOL *afActive); void __RPC_STUB IVsHelpAttributeList_UpdateAttributeStatus_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeStatusVal_Proxy( IVsHelpAttributeList * This, /* [in] */ BSTR bstrValue, /* [in] */ ATTRVALUETYPE type, /* [out] */ BOOL *pfActive); void __RPC_STUB IVsHelpAttributeList_GetAttributeStatusVal_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeStatusIndex_Proxy( IVsHelpAttributeList * This, /* [in] */ int index, /* [out] */ BOOL *pfActive); void __RPC_STUB IVsHelpAttributeList_GetAttributeStatusIndex_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsHelpAttributeList_GetAttributeValue_Proxy( IVsHelpAttributeList * This, /* [in] */ int index, /* [in] */ ATTRVALUETYPE type, /* [out] */ BSTR *pbstrValue); void __RPC_STUB IVsHelpAttributeList_GetAttributeValue_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsHelpAttributeList_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0260 */ /* [local] */ #define VSUC_CURRENT_F1 ((LPCOLESTR)1) extern RPC_IF_HANDLE __MIDL_itf_context_0260_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0260_v0_0_s_ifspec; #ifndef __IVsMonitorUserContext_INTERFACE_DEFINED__ #define __IVsMonitorUserContext_INTERFACE_DEFINED__ /* interface IVsMonitorUserContext */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsMonitorUserContext; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("9C074FDB-3D7D-4512-9604-72B3B0A5F609") IVsMonitorUserContext : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE SetSite( /* [in] */ IServiceProvider *pSP) = 0; virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_ApplicationContext( /* [retval][out] */ IVsUserContext **ppContext) = 0; virtual /* [propput] */ HRESULT STDMETHODCALLTYPE put_ApplicationContext( /* [in] */ IVsUserContext *pContext) = 0; virtual HRESULT STDMETHODCALLTYPE CreateEmptyContext( /* [retval][out] */ IVsUserContext **ppContext) = 0; virtual HRESULT STDMETHODCALLTYPE GetContextItems( /* [out] */ IVsUserContextItemCollection **pplist) = 0; virtual HRESULT STDMETHODCALLTYPE FindTargetItems( /* [in] */ LPCOLESTR pszTargetAttr, /* [in] */ LPCOLESTR pszTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [out] */ BOOL *pfF1Kwd) = 0; virtual HRESULT STDMETHODCALLTYPE RegisterItemProvider( /* [in] */ IVsUserContextItemProvider *pProvider, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE UnregisterItemProvider( /* [in] */ VSCOOKIE dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE AdviseContextItemEvents( /* [in] */ IVsUserContextItemEvents *pEvents, /* [retval][out] */ VSCOOKIE *pdwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE UnadviseContextItemEvent( /* [in] */ VSCOOKIE dwCookie) = 0; virtual HRESULT STDMETHODCALLTYPE GetNextCtxBagAttr( /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal) = 0; virtual HRESULT STDMETHODCALLTYPE ResetNextCtxBagAttr( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetPrevAttrCache( /* [out] */ BSTR **pbstrCacheArray, /* [out] */ int **pnCurrNumStored, /* [out] */ int *pnMaxNumStored) = 0; virtual HRESULT STDMETHODCALLTYPE GetNextCtxBag( /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal) = 0; virtual HRESULT STDMETHODCALLTYPE IsIdleAvailable( /* [out] */ BOOL *pfIdleAvail) = 0; virtual HRESULT STDMETHODCALLTYPE SetTopicTypeFilter( /* [in] */ IVsHelpAttributeList *pTopicTypeList) = 0; virtual HRESULT STDMETHODCALLTYPE GetF1Kwd( /* [out] */ BSTR *pbstrKwd, /* [out] */ BOOL *fF1Kwd) = 0; virtual HRESULT STDMETHODCALLTYPE IsF1Lookup( /* [out] */ BOOL *fF1Lookup) = 0; }; #else /* C style interface */ typedef struct IVsMonitorUserContextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsMonitorUserContext * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsMonitorUserContext * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsMonitorUserContext * This); HRESULT ( STDMETHODCALLTYPE *SetSite )( IVsMonitorUserContext * This, /* [in] */ IServiceProvider *pSP); /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_ApplicationContext )( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); /* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_ApplicationContext )( IVsMonitorUserContext * This, /* [in] */ IVsUserContext *pContext); HRESULT ( STDMETHODCALLTYPE *CreateEmptyContext )( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); HRESULT ( STDMETHODCALLTYPE *GetContextItems )( IVsMonitorUserContext * This, /* [out] */ IVsUserContextItemCollection **pplist); HRESULT ( STDMETHODCALLTYPE *FindTargetItems )( IVsMonitorUserContext * This, /* [in] */ LPCOLESTR pszTargetAttr, /* [in] */ LPCOLESTR pszTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [out] */ BOOL *pfF1Kwd); HRESULT ( STDMETHODCALLTYPE *RegisterItemProvider )( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemProvider *pProvider, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *UnregisterItemProvider )( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); HRESULT ( STDMETHODCALLTYPE *AdviseContextItemEvents )( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemEvents *pEvents, /* [retval][out] */ VSCOOKIE *pdwCookie); HRESULT ( STDMETHODCALLTYPE *UnadviseContextItemEvent )( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); HRESULT ( STDMETHODCALLTYPE *GetNextCtxBagAttr )( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); HRESULT ( STDMETHODCALLTYPE *ResetNextCtxBagAttr )( IVsMonitorUserContext * This); HRESULT ( STDMETHODCALLTYPE *GetPrevAttrCache )( IVsMonitorUserContext * This, /* [out] */ BSTR **pbstrCacheArray, /* [out] */ int **pnCurrNumStored, /* [out] */ int *pnMaxNumStored); HRESULT ( STDMETHODCALLTYPE *GetNextCtxBag )( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); HRESULT ( STDMETHODCALLTYPE *IsIdleAvailable )( IVsMonitorUserContext * This, /* [out] */ BOOL *pfIdleAvail); HRESULT ( STDMETHODCALLTYPE *SetTopicTypeFilter )( IVsMonitorUserContext * This, /* [in] */ IVsHelpAttributeList *pTopicTypeList); HRESULT ( STDMETHODCALLTYPE *GetF1Kwd )( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrKwd, /* [out] */ BOOL *fF1Kwd); HRESULT ( STDMETHODCALLTYPE *IsF1Lookup )( IVsMonitorUserContext * This, /* [out] */ BOOL *fF1Lookup); END_INTERFACE } IVsMonitorUserContextVtbl; interface IVsMonitorUserContext { CONST_VTBL struct IVsMonitorUserContextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsMonitorUserContext_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsMonitorUserContext_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsMonitorUserContext_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsMonitorUserContext_SetSite(This,pSP) \ (This)->lpVtbl -> SetSite(This,pSP) #define IVsMonitorUserContext_get_ApplicationContext(This,ppContext) \ (This)->lpVtbl -> get_ApplicationContext(This,ppContext) #define IVsMonitorUserContext_put_ApplicationContext(This,pContext) \ (This)->lpVtbl -> put_ApplicationContext(This,pContext) #define IVsMonitorUserContext_CreateEmptyContext(This,ppContext) \ (This)->lpVtbl -> CreateEmptyContext(This,ppContext) #define IVsMonitorUserContext_GetContextItems(This,pplist) \ (This)->lpVtbl -> GetContextItems(This,pplist) #define IVsMonitorUserContext_FindTargetItems(This,pszTargetAttr,pszTargetAttrValue,ppList,pfF1Kwd) \ (This)->lpVtbl -> FindTargetItems(This,pszTargetAttr,pszTargetAttrValue,ppList,pfF1Kwd) #define IVsMonitorUserContext_RegisterItemProvider(This,pProvider,pdwCookie) \ (This)->lpVtbl -> RegisterItemProvider(This,pProvider,pdwCookie) #define IVsMonitorUserContext_UnregisterItemProvider(This,dwCookie) \ (This)->lpVtbl -> UnregisterItemProvider(This,dwCookie) #define IVsMonitorUserContext_AdviseContextItemEvents(This,pEvents,pdwCookie) \ (This)->lpVtbl -> AdviseContextItemEvents(This,pEvents,pdwCookie) #define IVsMonitorUserContext_UnadviseContextItemEvent(This,dwCookie) \ (This)->lpVtbl -> UnadviseContextItemEvent(This,dwCookie) #define IVsMonitorUserContext_GetNextCtxBagAttr(This,pbstrAttrName,pbstrAttrVal) \ (This)->lpVtbl -> GetNextCtxBagAttr(This,pbstrAttrName,pbstrAttrVal) #define IVsMonitorUserContext_ResetNextCtxBagAttr(This) \ (This)->lpVtbl -> ResetNextCtxBagAttr(This) #define IVsMonitorUserContext_GetPrevAttrCache(This,pbstrCacheArray,pnCurrNumStored,pnMaxNumStored) \ (This)->lpVtbl -> GetPrevAttrCache(This,pbstrCacheArray,pnCurrNumStored,pnMaxNumStored) #define IVsMonitorUserContext_GetNextCtxBag(This,pbstrAttrName,pbstrAttrVal) \ (This)->lpVtbl -> GetNextCtxBag(This,pbstrAttrName,pbstrAttrVal) #define IVsMonitorUserContext_IsIdleAvailable(This,pfIdleAvail) \ (This)->lpVtbl -> IsIdleAvailable(This,pfIdleAvail) #define IVsMonitorUserContext_SetTopicTypeFilter(This,pTopicTypeList) \ (This)->lpVtbl -> SetTopicTypeFilter(This,pTopicTypeList) #define IVsMonitorUserContext_GetF1Kwd(This,pbstrKwd,fF1Kwd) \ (This)->lpVtbl -> GetF1Kwd(This,pbstrKwd,fF1Kwd) #define IVsMonitorUserContext_IsF1Lookup(This,fF1Lookup) \ (This)->lpVtbl -> IsF1Lookup(This,fF1Lookup) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_SetSite_Proxy( IVsMonitorUserContext * This, /* [in] */ IServiceProvider *pSP); void __RPC_STUB IVsMonitorUserContext_SetSite_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propget] */ HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_get_ApplicationContext_Proxy( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); void __RPC_STUB IVsMonitorUserContext_get_ApplicationContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); /* [propput] */ HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_put_ApplicationContext_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsUserContext *pContext); void __RPC_STUB IVsMonitorUserContext_put_ApplicationContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_CreateEmptyContext_Proxy( IVsMonitorUserContext * This, /* [retval][out] */ IVsUserContext **ppContext); void __RPC_STUB IVsMonitorUserContext_CreateEmptyContext_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetContextItems_Proxy( IVsMonitorUserContext * This, /* [out] */ IVsUserContextItemCollection **pplist); void __RPC_STUB IVsMonitorUserContext_GetContextItems_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_FindTargetItems_Proxy( IVsMonitorUserContext * This, /* [in] */ LPCOLESTR pszTargetAttr, /* [in] */ LPCOLESTR pszTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [out] */ BOOL *pfF1Kwd); void __RPC_STUB IVsMonitorUserContext_FindTargetItems_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_RegisterItemProvider_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemProvider *pProvider, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsMonitorUserContext_RegisterItemProvider_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_UnregisterItemProvider_Proxy( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsMonitorUserContext_UnregisterItemProvider_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_AdviseContextItemEvents_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsUserContextItemEvents *pEvents, /* [retval][out] */ VSCOOKIE *pdwCookie); void __RPC_STUB IVsMonitorUserContext_AdviseContextItemEvents_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_UnadviseContextItemEvent_Proxy( IVsMonitorUserContext * This, /* [in] */ VSCOOKIE dwCookie); void __RPC_STUB IVsMonitorUserContext_UnadviseContextItemEvent_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetNextCtxBagAttr_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); void __RPC_STUB IVsMonitorUserContext_GetNextCtxBagAttr_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_ResetNextCtxBagAttr_Proxy( IVsMonitorUserContext * This); void __RPC_STUB IVsMonitorUserContext_ResetNextCtxBagAttr_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetPrevAttrCache_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR **pbstrCacheArray, /* [out] */ int **pnCurrNumStored, /* [out] */ int *pnMaxNumStored); void __RPC_STUB IVsMonitorUserContext_GetPrevAttrCache_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetNextCtxBag_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrAttrName, /* [out] */ BSTR *pbstrAttrVal); void __RPC_STUB IVsMonitorUserContext_GetNextCtxBag_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_IsIdleAvailable_Proxy( IVsMonitorUserContext * This, /* [out] */ BOOL *pfIdleAvail); void __RPC_STUB IVsMonitorUserContext_IsIdleAvailable_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_SetTopicTypeFilter_Proxy( IVsMonitorUserContext * This, /* [in] */ IVsHelpAttributeList *pTopicTypeList); void __RPC_STUB IVsMonitorUserContext_SetTopicTypeFilter_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_GetF1Kwd_Proxy( IVsMonitorUserContext * This, /* [out] */ BSTR *pbstrKwd, /* [out] */ BOOL *fF1Kwd); void __RPC_STUB IVsMonitorUserContext_GetF1Kwd_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsMonitorUserContext_IsF1Lookup_Proxy( IVsMonitorUserContext * This, /* [out] */ BOOL *fF1Lookup); void __RPC_STUB IVsMonitorUserContext_IsF1Lookup_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsMonitorUserContext_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0261 */ /* [local] */ enum _VSCIPPROPID { VSCIPPROPID_NIL = -1, VSCIPPROPID_LookupType = 100, VSCIPPROPID_Customize = 200 } ; typedef LONG VSCIPPROPID; extern RPC_IF_HANDLE __MIDL_itf_context_0261_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0261_v0_0_s_ifspec; #ifndef __IVsUserContextItemProvider_INTERFACE_DEFINED__ #define __IVsUserContextItemProvider_INTERFACE_DEFINED__ /* interface IVsUserContextItemProvider */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextItemProvider; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("715C98B7-05FB-4A1A-86C8-FF00CE2E5D64") IVsUserContextItemProvider : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ VSCIPPROPID property, /* [retval][out] */ VARIANT *pvar) = 0; virtual HRESULT STDMETHODCALLTYPE SetProperty( /* [in] */ VSCIPPROPID property, /* [in] */ VARIANT var) = 0; virtual HRESULT STDMETHODCALLTYPE KeywordLookup( /* [in] */ LPCOLESTR pwzTargetAttr, /* [in] */ LPCOLESTR pwzTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [in] */ IVsMonitorUserContext *pCMUC, /* [in] */ BOOL fCheckIdle, /* [in] */ BOOL fContinueInterrupt) = 0; virtual HRESULT STDMETHODCALLTYPE PackedAttributeLookup( /* [in] */ LPCOLESTR pwzRequired, /* [in] */ LPCOLESTR pwzScope, /* [out] */ IVsUserContextItemCollection **ppList) = 0; virtual HRESULT STDMETHODCALLTYPE LookupEnabled( /* [out] */ BOOL *pfLookupEnabled) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemProviderVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItemProvider * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItemProvider * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItemProvider * This); HRESULT ( STDMETHODCALLTYPE *GetProperty )( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [retval][out] */ VARIANT *pvar); HRESULT ( STDMETHODCALLTYPE *SetProperty )( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [in] */ VARIANT var); HRESULT ( STDMETHODCALLTYPE *KeywordLookup )( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzTargetAttr, /* [in] */ LPCOLESTR pwzTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [in] */ IVsMonitorUserContext *pCMUC, /* [in] */ BOOL fCheckIdle, /* [in] */ BOOL fContinueInterrupt); HRESULT ( STDMETHODCALLTYPE *PackedAttributeLookup )( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzRequired, /* [in] */ LPCOLESTR pwzScope, /* [out] */ IVsUserContextItemCollection **ppList); HRESULT ( STDMETHODCALLTYPE *LookupEnabled )( IVsUserContextItemProvider * This, /* [out] */ BOOL *pfLookupEnabled); END_INTERFACE } IVsUserContextItemProviderVtbl; interface IVsUserContextItemProvider { CONST_VTBL struct IVsUserContextItemProviderVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItemProvider_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItemProvider_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItemProvider_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItemProvider_GetProperty(This,property,pvar) \ (This)->lpVtbl -> GetProperty(This,property,pvar) #define IVsUserContextItemProvider_SetProperty(This,property,var) \ (This)->lpVtbl -> SetProperty(This,property,var) #define IVsUserContextItemProvider_KeywordLookup(This,pwzTargetAttr,pwzTargetAttrValue,ppList,pCMUC,fCheckIdle,fContinueInterrupt) \ (This)->lpVtbl -> KeywordLookup(This,pwzTargetAttr,pwzTargetAttrValue,ppList,pCMUC,fCheckIdle,fContinueInterrupt) #define IVsUserContextItemProvider_PackedAttributeLookup(This,pwzRequired,pwzScope,ppList) \ (This)->lpVtbl -> PackedAttributeLookup(This,pwzRequired,pwzScope,ppList) #define IVsUserContextItemProvider_LookupEnabled(This,pfLookupEnabled) \ (This)->lpVtbl -> LookupEnabled(This,pfLookupEnabled) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_GetProperty_Proxy( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [retval][out] */ VARIANT *pvar); void __RPC_STUB IVsUserContextItemProvider_GetProperty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_SetProperty_Proxy( IVsUserContextItemProvider * This, /* [in] */ VSCIPPROPID property, /* [in] */ VARIANT var); void __RPC_STUB IVsUserContextItemProvider_SetProperty_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_KeywordLookup_Proxy( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzTargetAttr, /* [in] */ LPCOLESTR pwzTargetAttrValue, /* [out] */ IVsUserContextItemCollection **ppList, /* [in] */ IVsMonitorUserContext *pCMUC, /* [in] */ BOOL fCheckIdle, /* [in] */ BOOL fContinueInterrupt); void __RPC_STUB IVsUserContextItemProvider_KeywordLookup_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_PackedAttributeLookup_Proxy( IVsUserContextItemProvider * This, /* [in] */ LPCOLESTR pwzRequired, /* [in] */ LPCOLESTR pwzScope, /* [out] */ IVsUserContextItemCollection **ppList); void __RPC_STUB IVsUserContextItemProvider_PackedAttributeLookup_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); HRESULT STDMETHODCALLTYPE IVsUserContextItemProvider_LookupEnabled_Proxy( IVsUserContextItemProvider * This, /* [out] */ BOOL *pfLookupEnabled); void __RPC_STUB IVsUserContextItemProvider_LookupEnabled_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItemProvider_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_context_0262 */ /* [local] */ enum _LIMITTOPICSOURCE { CCW_LimKwd_SelOnly = 0, CCW_LimKwd_NoAmbient = 1, CCW_LimKwd_All = 2, CCW_LimKwd_Last = 3 } ; typedef LONG LIMITTOPICSOURCE; extern RPC_IF_HANDLE __MIDL_itf_context_0262_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0262_v0_0_s_ifspec; #ifndef __IVsUserContextCustomize_INTERFACE_DEFINED__ #define __IVsUserContextCustomize_INTERFACE_DEFINED__ /* interface IVsUserContextCustomize */ /* [version][object][uuid] */ EXTERN_C const IID IID_IVsUserContextCustomize; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0F817159-761D-447e-9600-4C3387F4C0FD") IVsUserContextCustomize : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetLimitKeywordSource( /* [retval][out] */ LONG *pLimKwdSrc) = 0; }; #else /* C style interface */ typedef struct IVsUserContextCustomizeVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextCustomize * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextCustomize * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextCustomize * This); HRESULT ( STDMETHODCALLTYPE *GetLimitKeywordSource )( IVsUserContextCustomize * This, /* [retval][out] */ LONG *pLimKwdSrc); END_INTERFACE } IVsUserContextCustomizeVtbl; interface IVsUserContextCustomize { CONST_VTBL struct IVsUserContextCustomizeVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextCustomize_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextCustomize_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextCustomize_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextCustomize_GetLimitKeywordSource(This,pLimKwdSrc) \ (This)->lpVtbl -> GetLimitKeywordSource(This,pLimKwdSrc) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextCustomize_GetLimitKeywordSource_Proxy( IVsUserContextCustomize * This, /* [retval][out] */ LONG *pLimKwdSrc); void __RPC_STUB IVsUserContextCustomize_GetLimitKeywordSource_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextCustomize_INTERFACE_DEFINED__ */ #ifndef __IVsUserContextItemEvents_INTERFACE_DEFINED__ #define __IVsUserContextItemEvents_INTERFACE_DEFINED__ /* interface IVsUserContextItemEvents */ /* [object][version][uuid] */ EXTERN_C const IID IID_IVsUserContextItemEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("A2078F0E-A310-420A-BA27-16531905B88F") IVsUserContextItemEvents : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE OnUserContextItemsAvailable( /* [in] */ IVsUserContextItemCollection *pList) = 0; }; #else /* C style interface */ typedef struct IVsUserContextItemEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IVsUserContextItemEvents * This, /* [in] */ REFIID riid, /* [iid_is][out] */ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IVsUserContextItemEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( IVsUserContextItemEvents * This); HRESULT ( STDMETHODCALLTYPE *OnUserContextItemsAvailable )( IVsUserContextItemEvents * This, /* [in] */ IVsUserContextItemCollection *pList); END_INTERFACE } IVsUserContextItemEventsVtbl; interface IVsUserContextItemEvents { CONST_VTBL struct IVsUserContextItemEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IVsUserContextItemEvents_QueryInterface(This,riid,ppvObject) \ (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) #define IVsUserContextItemEvents_AddRef(This) \ (This)->lpVtbl -> AddRef(This) #define IVsUserContextItemEvents_Release(This) \ (This)->lpVtbl -> Release(This) #define IVsUserContextItemEvents_OnUserContextItemsAvailable(This,pList) \ (This)->lpVtbl -> OnUserContextItemsAvailable(This,pList) #endif /* COBJMACROS */ #endif /* C style interface */ HRESULT STDMETHODCALLTYPE IVsUserContextItemEvents_OnUserContextItemsAvailable_Proxy( IVsUserContextItemEvents * This, /* [in] */ IVsUserContextItemCollection *pList); void __RPC_STUB IVsUserContextItemEvents_OnUserContextItemsAvailable_Stub( IRpcStubBuffer *This, IRpcChannelBuffer *_pRpcChannelBuffer, PRPC_MESSAGE _pRpcMessage, DWORD *_pdwStubPhase); #endif /* __IVsUserContextItemEvents_INTERFACE_DEFINED__ */ #ifndef __VsContext_LIBRARY_DEFINED__ #define __VsContext_LIBRARY_DEFINED__ /* library VsContext */ /* [version][uuid] */ EXTERN_C const IID LIBID_VsContext; EXTERN_C const CLSID CLSID_VsContextClass; #ifdef __cplusplus class DECLSPEC_UUID("3c1f59c6-69cf-11d2-aa7c-00c04f990343") VsContextClass; #endif #endif /* __VsContext_LIBRARY_DEFINED__ */ /* interface __MIDL_itf_context_0264 */ /* [local] */ #define SID_SVsMonitorUserContext IID_IVsMonitorUserContext #define HH_1x_ATTR L"HtmlHelp_1.X_LookupInfo" #define KWD_GUID L"KWD_GUID" #define KEYWORD_CS L"KEYWORD_CS" extern RPC_IF_HANDLE __MIDL_itf_context_0264_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_context_0264_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree( unsigned long *, BSTR * ); unsigned long __RPC_USER VARIANT_UserSize( unsigned long *, unsigned long , VARIANT * ); unsigned char * __RPC_USER VARIANT_UserMarshal( unsigned long *, unsigned char *, VARIANT * ); unsigned char * __RPC_USER VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT * ); void __RPC_USER VARIANT_UserFree( unsigned long *, VARIANT * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "tapicer@gmail.com" ]
tapicer@gmail.com
ea8e4c0dfd8078e3e36ecf435a5c888514e74fbe
e8dc33fae8ff29d98e81660198caa55a691e42f1
/Common/toolBase.cxx
b7dfac046245241f0256d3f1cac218c6230228f1
[]
no_license
colddie/MICA
b1f0379cff203b7a088f028cc0488b06e2c0b30e
549b46818202a3901a66897aa966f46372c640c7
refs/heads/master
2020-05-28T03:23:09.098974
2013-12-13T07:24:34
2013-12-13T07:24:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
750
cxx
#include "toolBase.h" #include <algorithm> namespace std { const string trim (const string &str, const string &whitespace) { const size_t begin_str = str.find_first_not_of (whitespace); if (begin_str == string::npos) { // no content return ""; } const size_t end_str = str.find_last_not_of(whitespace); const size_t range = end_str - begin_str + 1; return str.substr (begin_str, range); } // find substring (case insensitive) size_t ci_find (const string& str1, const string& str2) { string::const_iterator it = search (str1.begin(), str1.end(), str2.begin(), str2.end(), my_equal()); if (it != str1.end()) return it - str1.begin(); else return string::npos; } }
[ "colddiesun@gmail.com" ]
colddiesun@gmail.com
971b91ed8babddcd0cbf2b64caf12336f3c1c16e
1d35d3b77312ddd236a210254b82f92c88bc87b5
/src/qt/editaddressdialog.cpp
053b36ce7fdfadc2ec472ca8a43b5e2239ced438
[ "MIT" ]
permissive
blankcoin/blank
bee311cdfadf4f0bf449a20e6086736caa63c8f4
96be8b866e59cfaa8ee2884d9028c0293da92384
refs/heads/master
2020-03-20T23:12:54.777084
2018-06-22T05:35:12
2018-06-22T05:35:12
137,835,440
0
2
null
null
null
null
UTF-8
C++
false
false
3,729
cpp
#include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Blank address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
[ "ridwansky92@gmail.com" ]
ridwansky92@gmail.com
0b322c53506beece77d4b7abecc3bb4b45ddc8be
f0c7faa78175bc3853f0c0a3cab6b8449ae0283d
/src/SpiralMatrixII.cpp
244261269034dc03b2e742d3fce69b56619e7fca
[]
no_license
lxstorm/LeetCode
7b4f76a7aad1931bdab729ec994bf3f21e6ccb37
02c8ed83651bc80ba5bd2e992947cb1bf4e3ef70
refs/heads/master
2020-04-06T08:03:08.355152
2016-11-16T09:55:05
2016-11-16T09:55:05
52,674,353
0
0
null
null
null
null
UTF-8
C++
false
false
780
cpp
class Solution { public: vector<vector<int>> generateMatrix(int n) { // we can use vector<vector<int>> result(n, vector<int>(n)); vector<int> tmp(n, 0); vector<vector<int>> result(n, tmp); vector<int> pos{0, -1}; vector<vector<int>> direction{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector<int> count{n, n - 1}; int step = 0; int num = 1; while(count[0] >= 0 && count[1] >= 0){ for(int i = 0;i < count[step % 2];++i){ pos[0] += direction[step % 4][0]; pos[1] += direction[step % 4][1]; result[pos[0]][pos[1]] = num; num++; } count[step % 2]--; step++; } return result; } };
[ "lxstormy@gmail.com" ]
lxstormy@gmail.com
c69767abf6c3217849e2e8f35dba59cafe618433
ccda07d0b27779e66b57c4d94441fe08d407e232
/tools/transform.h
3e002e801ed61512122c12dafbe9069415fb4349
[ "MIT" ]
permissive
arsenm/alive2
8677f8494b1dd6da514dbd1cbe00ae78eddbc7a6
a631decc679eca18ea6ab33b6083a8f9f1c7f95b
refs/heads/master
2022-11-17T10:36:26.547305
2020-07-07T15:41:11
2020-07-07T15:41:23
280,014,085
0
0
MIT
2020-07-16T00:35:46
2020-07-16T00:35:45
null
UTF-8
C++
false
false
1,332
h
#pragma once // Copyright (c) 2018-present The Alive2 Authors. // Distributed under the MIT license that can be found in the LICENSE file. #include "ir/function.h" #include "smt/solver.h" #include "util/errors.h" #include <string> #include <ostream> #include <unordered_map> namespace tools { struct TransformPrintOpts { bool print_fn_header = true; }; struct Transform { std::string name; IR::Function src, tgt; IR::Predicate *precondition = nullptr; void preprocess(); void print(std::ostream &os, const TransformPrintOpts &opt) const; friend std::ostream& operator<<(std::ostream &os, const Transform &t); }; class TypingAssignments { smt::Solver s, sneg; smt::Result r; bool has_only_one_solution = false; bool is_unsat = false; TypingAssignments(const smt::expr &e); public: bool operator!() const { return !(bool)*this; } operator bool() const; void operator++(void); bool hasSingleTyping() const { return has_only_one_solution; } friend class TransformVerify; }; class TransformVerify { Transform &t; std::unordered_map<std::string, const IR::Instr*> tgt_instrs; bool check_each_var; public: TransformVerify(Transform &t, bool check_each_var); util::Errors verify() const; TypingAssignments getTypings() const; void fixupTypes(const TypingAssignments &ty); }; }
[ "nuno.lopes@ist.utl.pt" ]
nuno.lopes@ist.utl.pt
b37a9baefe63dba3e088ce3e1bbe0dace7878905
a86a8bfd545aa059202e4052e079d3353030364c
/src/client/cli/main.cc
b07624d869b471b37c4bb1ab4530857172a076aa
[ "MIT" ]
permissive
delizhang/spada
741623a2abc207e63337952f3ccbdd7b460138e7
f87e42c0c64b4d5fa2917df985f5403d8a7b3fd8
refs/heads/master
2021-01-01T19:21:31.561633
2017-07-27T18:29:12
2017-07-27T18:29:12
93,212,547
0
0
null
null
null
null
UTF-8
C++
false
false
503
cc
#include <iostream> #include "client/connector.h" #include "common/network/connection.h" int main(int argc, const char *argv[]) { Connector connector("127.0.0.1", DEFAULT_PORT); if(connector.Init()) { std::cout << "Sever connected" << std::endl; const int bufSize = 1024; char buffer[bufSize]; do{ std::cout << "Spada: "; std::cin.getline(buffer, bufSize); } while(connector.Send(buffer, bufSize)); } return 0; }
[ "deli.zhang@outlook.com" ]
deli.zhang@outlook.com
00fd0d74110b3ac1853aa0ca4673f2614ac7a033
2495c956bac63236aa071948b4c3c96ba0abfafb
/exercises.hpp
2f9698b5688b8fbd95cc0182cc189820ad2fd6b1
[]
no_license
mhrtmnn/GraphTheory_Exercises
3669713a2714b82bdb9854c2ae0d378330a3de48
0713caedd33e69a4d7374666b4deb2f749680f5b
refs/heads/master
2020-04-01T04:22:37.668901
2018-10-13T10:25:36
2018-10-13T10:26:21
152,860,774
0
0
null
null
null
null
UTF-8
C++
false
false
695
hpp
// // Created by marco on 5/8/16. // #ifndef GRAPHTHEORY_GIT_EXERCISES_HPP #define GRAPHTHEORY_GIT_EXERCISES_HPP #include "graphAlgorithms.hpp" #include "ComplexityAlgorithms.hpp" #include <thread> using namespace std; void printMetrics(Graph&, graphAlgorithms&); void startEx4(Graph&); void startEx5(); void startEx6(string, graphAlgorithms&); void startEx7(string, graphAlgorithms&); void Ex5Worker(vector<pair<int, int>>*, int, int); void createCSV(vector<pair<int, int>> &); void startEx10(graphAlgorithms&); void startEx11(ComplexityAlgorithms &); void printSAT(struct satFormula*); void printVal(struct satFormula*); void startEx13(string s); #endif //GRAPHTHEORY_GIT_EXERCISES_HPP
[ "marco.hartmann@tuhh.de" ]
marco.hartmann@tuhh.de
524e6aa676ce7263a6ee4586ef72dc84a72cbdcb
cae9edc918596933a9644033a89e3f27db534c3a
/Module_04/ex03/Cure.hpp
02f1e569a203fb51820176c699304975930201d0
[]
no_license
Tjobo-Hero/CPP
81c409e4c32cfd74ccd432d8dfec7d069a4f9ef2
93c5aae2be453e19e5e0948640a32ea6e32d55c8
refs/heads/master
2023-04-23T06:24:56.804387
2021-05-14T09:35:36
2021-05-14T09:35:36
309,345,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,324
hpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* Cure.hpp :+: :+: */ /* +:+ */ /* By: timvancitters <timvancitters@student.co +#+ */ /* +#+ */ /* Created: 2021/02/02 15:34:05 by timvancitte #+# #+# */ /* Updated: 2021/02/04 13:56:40 by timvancitte ######## odam.nl */ /* */ /* ************************************************************************** */ #ifndef CURE_HPP # define CURE_HPP #include "AMateria.hpp" #include "ICharacter.hpp" #include <iostream> #include <string> class Cure : public AMateria { public: Cure(void); Cure(Cure const &src); virtual ~Cure(void); Cure& operator=(Cure const &obj); std::string const& getType() const; unsigned int getXP(void) const; virtual Cure* clone(void) const; virtual void use(ICharacter &target); }; #endif
[ "timvancitters@Tims-MacBook-Pro.local" ]
timvancitters@Tims-MacBook-Pro.local
94f45f1eb5462105aaa10f73dba9d7cc0b402e70
624511f6ad0cf17a2ba1a1ea1f25c3b139ce4295
/baselib/lib/Lsc/alloc/Lsc_alloc.h
0ec1e994c6b0e8f37641fa634956e04ac32051ea
[]
no_license
lightchainone/lightchain
7d90338d4a4e8d31d550c07bf380c06580941334
6fc7019c76a8b60d4fd63fba58fa79858856f66b
refs/heads/master
2021-05-11T05:47:17.672527
2019-12-16T09:51:39
2019-12-16T09:51:39
117,969,593
23
6
null
null
null
null
GB18030
C++
false
false
3,142
h
#ifndef BSL_ALLOC_H__ #define BSL_ALLOC_H__ #include <cstdio> #include <cstdlib> #include <new> #include <algorithm> namespace Lsc { /** * * This is precisely the allocator defined in the C++ Standard. * - all allocation calls malloc * - all deallocation calls free */ template < typename _Tp > class Lsc_alloc { plclic: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _Tp *pointer; typedef const _Tp *const_pointer; typedef _Tp & reference; typedef const _Tp & const_reference; typedef _Tp value_type; typedef Lsc_alloc<_Tp> pool_type; template < typename _Tp1 > struct rebind { typedef Lsc_alloc < _Tp1 > other; }; static const bool recycle_space;// = false; //在alloc析构的时候,是否释放空间 static const bool thread_safe;// = true; //空间分配器是否线程安全 Lsc_alloc() { create(); } Lsc_alloc(const Lsc_alloc &) { create(); } template < typename _Tp1 > Lsc_alloc(const Lsc_alloc < _Tp1 > &) { create(); } ~Lsc_alloc() { destroy(); } pointer address(reference __x) const { return &__x; } const_pointer address(const_reference __x) const { return &__x; } //NB:__n is permitted to be 0. The C++ standard says nothing // about what the return value is when __n == 0. pointer allocate(size_type __n, const void * = 0) { pointer __ret = static_cast < _Tp * >(malloc(__n * sizeof(_Tp))); return __ret; } pointer reallocate(size_type __n, void * ptr = 0) { if (ptr == NULL) { return allocate(__n, ptr); } return static_cast < _Tp * >(realloc(ptr, __n * sizeof(_Tp))); } //__p is not permitted to be a null pointer. void deallocate(pointer __p, size_type) { free(static_cast < void *>(__p)); } size_type max_size() const { return size_t(-1) / sizeof(_Tp); } //_GLIBCXX_RESOLVE_LIB_DEFECTS //402. wrong new expression in[some_] allocator: : construct void construct(pointer __p, const _Tp & __val) { ::new(__p) value_type(__val); } void destroy(pointer __p) { __p->~ _Tp(); } int create() { return 0; } int destroy() { return 0; } void swap (Lsc_alloc<_Tp> &) { } int merge(Lsc_alloc<_Tp> &){ return 0; } value_type * getp(pointer __p) const { return __p; } }; template < typename _Tp > inline bool operator == (const Lsc_alloc < _Tp > &, const Lsc_alloc < _Tp > &) { return true; } template < typename _Tp, class _Alloc2 > inline bool operator == (const Lsc_alloc <_Tp > &, const _Alloc2 &) { return false; } template < typename _Tp > inline bool operator != (const Lsc_alloc < _Tp > &, const Lsc_alloc < _Tp > &) { return false; } template < typename _Tp, class _Alloc2 > inline bool operator != (const Lsc_alloc <_Tp > &, const _Alloc2 &) { return true; } template <typename _Tp> const bool Lsc_alloc<_Tp>::recycle_space = false; template <typename _Tp> const bool Lsc_alloc<_Tp>::thread_safe = true; } #endif // xalloc_h__
[ "lightchainone@hotmail.com" ]
lightchainone@hotmail.com
a18a242c63227c05609d7387ba746fd3dc0b9bb0
875e3a1668ef11a63033336abb81b78775a26488
/firmware/AD5254_example/AD5254_example.ino
5fd4c255bab65ebc1754fbc519f87b587cdeeb09
[]
no_license
jjculber/volume-control-board
77fbfaf1532746060fab95c072a516236f1e7046
88eb4743675034aa87c05a153bd3ff823560e8af
refs/heads/master
2020-04-20T13:12:43.093271
2019-04-20T01:05:22
2019-04-20T01:05:22
168,862,983
0
0
null
null
null
null
UTF-8
C++
false
false
7,380
ino
// Distributed with a free-will license. // Use it any way you want, profit or free, provided it fits in the licenses of its associated works. // AD5254 // This code is designed to work with the AD5254_I2CPOT_10K I2C Mini Module available from ControlEverything.com. // https://www.controleverything.com/content/Potentiometers?sku=AD5254_I2CPOT_10K#tabs-0-product_tabset-2 #include <Wire.h> #include <Encoder.h> // AD5254 I2C address is 0x2C(44) #define Addr 0x2F Encoder myEnc(1, 2); const int buttonPin = 0; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin void setup() { // Initialise I2C communication as Master Wire.begin(); // Initialise serial communication, set baud rate = 9600 Serial.begin(9600); pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); mute(); unmute(); } unsigned int volume = 0; unsigned int muted = 0; long oldPosition = -999; int ledState = LOW; // the current state of the output pin int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin int registeredPress = 0; long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void loop() { readPushButtonState(); readRotaryEncoderState(); } void readRotaryEncoderState() { long newPosition = myEnc.read(); if (newPosition < 0) { Serial.print("<0 = "); Serial.println(newPosition); newPosition = 0; myEnc.write(0); readAndPrintAllValues(); } if (newPosition > 255) { Serial.print(">255 = "); Serial.println(newPosition); newPosition = 255; myEnc.write(255); setAllValues(newPosition); readAndPrintAllValues(); } if (newPosition != oldPosition) { //unmute(); Serial.print("mid = "); Serial.println(newPosition); oldPosition = newPosition; setAllValues(newPosition); readAndPrintAllValues(); } } void readPushButtonState() { // read the state of the switch into a local variable: int reading = digitalRead(buttonPin); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: buttonState = reading; if (buttonState == LOW && registeredPress == 0) { ledState = ((ledState == LOW) ? HIGH : LOW); registeredPress = 1; // set the LED using the state of the button: if (ledState == HIGH) { mute(); } else { unmute(); } } if (buttonState == HIGH && registeredPress == 1) { registeredPress = 0; } } // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonState = reading; } void mute() { ledState = HIGH; digitalWrite(ledPin, ledState); //setAllValues(0); Wire.beginTransmission(Addr); Wire.write(0x00); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x01); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x02); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x03); Wire.write(0x00); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x80); Wire.endTransmission(); volume = 0; muted = 1; myEnc.write(0); Serial.println("muted"); readAndPrintAllValues(); } void unmute() { ledState = LOW; digitalWrite(ledPin, ledState); muted = 0; myEnc.write(1); setAllValues(1); Serial.println("unmuted"); readAndPrintAllValues(); } void readAndPrintAllValues() { unsigned int data = -1; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x00); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_0 = (data / 256.0 ) * 10.0; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x01); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_1 = (data / 256.0 ) * 10.0; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x02); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_2 = (data / 256.0 ) * 10.0; // Start I2C transmission Wire.beginTransmission(Addr); // Select data register Wire.write(0x03); // Stop I2C transmission Wire.endTransmission(); // Request 1 byte of data Wire.requestFrom(Addr, 1); // Read 1 byte of data if (Wire.available() == 1) { data = Wire.read(); } // Convert the data float res_3 = (data / 256.0 ) * 10.0; // Output data to serial monitor Serial.print("Resistance Channel-0 : "); Serial.print(res_0); Serial.println(" K"); Serial.print("Resistance Channel-1 : "); Serial.print(res_1); Serial.println(" K"); Serial.print("Resistance Channel-2 : "); Serial.print(res_2); Serial.println(" K"); Serial.print("Resistance Channel-3 : "); Serial.print(res_3); Serial.println(" K"); } void setAllValues(unsigned int val) { if (muted == 1) { return; } uint8_t command = 0x80; // nop if (volume > val) { // decrease volume command = 0xb0; } else if (volume < val) { // increase volume command = 0xd8; } Serial.println(command); Wire.beginTransmission(Addr); Wire.write(command); Wire.endTransmission(); Wire.beginTransmission(Addr); Wire.write(0x80); Wire.endTransmission(); volume = val; return; // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-0 Wire.write(0x00); // Input resistance value, 0x80(128) //Wire.write(val); // Stop I2C transmission Wire.endTransmission(); // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-1 Wire.write(0x01); // Input resistance value, 0x80(128) Wire.write(val); // Stop I2C transmission Wire.endTransmission(); // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-2 Wire.write(0x02); // Input resistance value, 0x80(128) Wire.write(val); // Stop I2C transmission Wire.endTransmission(); // Start I2C transmission Wire.beginTransmission(Addr); // Send instruction for POT channel-3 Wire.write(0x03); // Input resistance value, 0x80(128) Wire.write(val); // Stop I2C transmission Wire.endTransmission(); }
[ "jculberts@gmail.com" ]
jculberts@gmail.com
d8744cd4f23815ad87e5f4e96a9307d2e1cc91f6
3d8c44ed73ec0d9776e7cbc2ffd11005a1a41579
/include/alds/sort/1_2_c_stable_sort.h
f33dfb8a9292831aae9e883bac3979f33f68c998
[]
no_license
eiji03aero/alds
490c5e9fa2f9f225d74a5fd5d9d91bc0c90c71d2
4f92fa114fc4dc6c23f8259cccbe606ddd31e56e
refs/heads/master
2023-01-10T14:32:57.661496
2020-11-08T13:01:32
2020-11-08T13:01:32
302,466,212
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
h
#ifndef ALDS_SORT_1_1_D_STABLE_SORT_H_INCLUDED #define ALDS_SORT_1_1_D_STABLE_SORT_H_INCLUDED #include "alds/shared.h" #include <vector> namespace alds { namespace sort { void bubble_sort(std::vector<alds::Card> &input) { for (int i = 0; i < input.size(); i++) { for (int j = input.size() - 1; j >= i+1; j--) { if (input[j].value < input[j - 1].value) { std::swap(input[j], input[j - 1]); } } } } void selection_sort(std::vector<alds::Card> &input) { for (int i = 0; i < input.size(); i++) { int minj = i; for (int j = i; j < input.size(); j++) { if (input[j].value < input[minj].value) { minj = j; } } std::swap(input[i], input[minj]); } } bool is_stable(std::vector<alds::Card> v1, std::vector<alds::Card> v2) { for (int i = 0; i < v1.size(); i++) { if (v1[i].suit != v2[i].suit) { return false; } } return true; } } /* namespace sort */ } /* namespace alds */ #endif /* ifndef ALDS_SORT_1_1_D_STABLE_SORT_H_INCLUDED */
[ "eiji03aero@gmail.com" ]
eiji03aero@gmail.com
dc8b13faa19521e44997a38562ec1d411b944f6d
f19896ff3a1016d4ae63db6e9345cfcc4d0a2967
/Topics/Topic/Data Structures and Alogrithms (Topic)/Leetcode(Website)/205(Isomorphic Strings).cpp
de9bec1603db2408ffb11eae857cb0f48024e5d1
[]
no_license
Akshay199456/100DaysOfCode
079800b77a44abe560866cf4750dfc6c7fe01a59
b4ed8a6793c17bcb71c56686d98fcd683af64841
refs/heads/master
2023-08-08T07:59:02.723675
2023-08-01T03:44:15
2023-08-01T03:44:15
226,718,143
3
0
null
null
null
null
UTF-8
C++
false
false
3,370
cpp
// This problem was also solved using the UMPIRE approach /* -------------------------Question: Given two strings s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be replaced to get t. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. Example 1: Input: s = "egg", t = "add" Output: true Example 2: Input: s = "foo", t = "bar" Output: false Example 3: Input: s = "paper", t = "title" Output: true Note: You may assume both s and t have the same length. */ /* -------------------------My Approaches: 1. Using a map and set to store the occurrences This problem can be solved efficiently using a map and a set to store the occurrences of the characters in string s and t. To get more information about this approach, check out the corresponding images with respect to this problem in 'Helping Images'. Time and space complexity are both of O(n) since the both strings are assumed to be of the same length. Time complexity: O(n) Space complexity: O(n) */ /* -------------------------Other approaches 1. Using an array instead of a map. If we know the kind of characters we will be dealing with, we can use an array instead of a map. That way we can optimize on space complexity. In this problem, we know that all characters are possible and since there are 128 characters with ASCII characters that's the size I have chosen. We initialize initially the values to -1. After going through each character in both the strings, we make sure to correspond both the characters in the strings to the same value since they are mapped to each other. If they don't match in value, it means that they have been mapped to differnt characters and so we return false. If we get rhough the whole loop, we return true. Our space complexity here is O(1) since the array is of a constant fixed size and doesn't change with input. Time complexity: O(n) Space complexity: O(1) */ // My Approaches(1) class Solution { public: bool checkIsomorphic(string s, string t){ unordered_map<char, char> sMap; unordered_set<char> tSet; for(int i=0; i<s.size(); i++){ auto it = sMap.find(s[i]); if(it != sMap.end()){ if(sMap[s[i]] != t[i]) return false; } else{ auto it = tSet.find(t[i]); if(it != tSet.end()) return false; sMap[s[i]] = t[i]; tSet.emplace(t[i]); } } return true; } bool isIsomorphic(string s, string t) { if(!s.size()) return true; else return checkIsomorphic(s, t); } }; // Other approaches(1) class Solution { public: bool checkIsomorphic(string s, string t){ vector<int> sArray (128, -1), tArray(128, -1); for(int i=0; i<s.size(); i++){ if(sArray[s[i]] != tArray[t[i]]) return false; sArray[s[i]] = i; tArray[t[i]] = i; } return true; } bool isIsomorphic(string s, string t) { if(!s.size()) return true; else return checkIsomorphic(s, t); } };
[ "akshay.kum94@gmail.com" ]
akshay.kum94@gmail.com
44657c79cf47a5588b76620a680800d75a215196
7b99b71a2fe674c16ebdd8bf74f1782076bb10b0
/Init.h
9f36a5eaa837bc6fad663950238de274249f3296
[]
no_license
AplDGrape/GDGRAPX_Final_v1
485e482b1b02bf1f0009142cefa000ec207650f7
230281154be471207b4b85c1f82f7618a6e361b7
refs/heads/main
2023-07-30T01:51:49.974728
2021-09-17T12:23:20
2021-09-17T12:23:20
407,530,277
0
0
null
null
null
null
UTF-8
C++
false
false
981
h
#pragma once #include <stdio.h> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> GLFWwindow* Window; int width, height; GLFWwindow* initialize() { //initialize glfw if (glfwInit() != GLFW_TRUE) { fprintf(stderr, "Failed to initialized! \n"); return NULL; } width = 1366; height = 768; // set opengl version to 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // create window GLFWwindow* window; window = glfwCreateWindow(width, height, "Apolinar & Santonia", NULL, NULL); if (window == NULL) { fprintf(stderr, "Failed to load window! \n"); return NULL; } glfwMakeContextCurrent(window); //initialize glew glewExperimental = true; if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return NULL; } return Window; } int getWidth() { return width; } int getHeight() { return height; }
[ "raphaelapolinar16@yahoo.com" ]
raphaelapolinar16@yahoo.com
cf7fe611769694de00c3f00c4beda7628dd9e336
88c1c2bf1327a15edf9614e24bb2100f7e57d2d2
/safeMain.cpp
133413ab6e0331d7ad0465b798a712496d18330d
[]
no_license
juanpinto232901/SUBtoCUDA
7805e52501e3068c375683a14589b8ff144669d3
7303ad43e9da1563e649ad55444503cdc6fba8d4
refs/heads/master
2020-05-27T21:40:23.274546
2019-06-04T13:43:20
2019-06-04T13:43:20
188,796,282
0
0
null
null
null
null
UTF-8
C++
false
false
162,133
cpp
#include <iostream> #include <fstream> #include <Windows.h> #include <cstdio> #include <string> #include <exception> #include <functional> #include <stdexcept> #include "signals_unity_bridge.h" #include "TimerHQ.h" #include <sdl\include\SDL.h> #include "cwipc_codec\include\api.h" #include "safeMain.h" #include <QDebug> #include <QMouseEvent> #include <qtimer.h> #include "CapturSUBThread.h" #include "CapturSUB.h" #undef main using namespace std; #define IMPORT(name) ((decltype(name)*)SDL_LoadFunction(lib, # name)) QVector<CapturSUBThread*> theSUBNodes; SafeMain::SafeMain(QWidget *parent) : useCUDA(false) , iSUBThreadsNumber(1) , iNumProcessorsQTH(1) , xRot(0.0) , yRot(0.0) , zRot(0.0) , m_fDistEye(0.0) , initialized(false) /// The devices was initialized , allocated(false) /// The memory was allocated , plyloaded(false) /// The file PLY was loaded , drawed(0) , m_fViewportZoomFactor(0.0) , ViewerVertexBuffer1(0) , iBufferID(0) #ifdef USE_CUDA , block_size(16) , positionCUDABuffer(0) , posColorCUDABuffer(0) , indicesCUDABuffer(0) #endif , iMaxMem(0) , filePos(0) , num_elems(0) , iNumBlocks(0) , iFileMaxSize(0) , m_iNumVertices(0) , m_iNumVerticesPerThread(0) , iThreadsNumber(0) /// Number of threads , moveUp(0.0) , incMov(0.0) , iAvatar(0xffffffff) , bSeeColor(true) , yElev(0) , bOnlyOne(false) , iPosPrev(0) #ifndef THREADSUB , mySUB01(0) , mySUB02(0) , mySUB03(0) #endif { qDebug() << QString("SafeMain constructor .......... "); setAutoFillBackground(false); setFocus(); for(int i=0; i<MAX_THREADS; i++) { ViewerVertexBufferTh[i] = 0; iBufferIDTh[i] = 0; num_elemsTh[i] = 0; } #ifndef THREADSUB m_fDistEye = -160; yElev = 100; #else // m_fDistEye = 150; m_fDistEye = 700.0; // m_fDistEye = 3150.0; yElev = -200; #endif iAvatar = 0xffffffff; bOnlyOne = false; iPosPrev = 0; iNumProcessorsQTH = QThread::idealThreadCount(); qDebug() << QString("iNumProcessorsQTH=%1").arg(iNumProcessorsQTH); // setThreadsNumber(4);// iNumProcessorsQTH - 2); setSUBThreadsNumber(NUMPCL); iThreadsNumber = NUMPCL; cudaInfo(); // safeMainV31(); #ifdef THREADSUB setUseSUBThreads(true); #else mySUB01 = new CapturSUB; mySUB02 = new CapturSUB; mySUB03 = new CapturSUB; #endif //#ifdef CONGL QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(animate())); timer->start(20); //#endif } SafeMain::~SafeMain() { #ifndef THREADSUB mySUB01->read_end(0); mySUB02->read_end(1); mySUB03->read_end(2); #endif } void* safeImport(void* lib, const char* name) { auto r = SDL_LoadFunction(lib, name); if (!r) throw runtime_error("Symbol not found: " + string(name)); return r; } //#define IMPORT(name) ((decltype(name)*)safeImport(lib, # name)) void SafeMain::safeMainV31()//int argc, char const* argv[]) { //if (argc != 3) // throw runtime_error("Usage: app.exe <signals-unity-bridge.dll> [media url]"); //const string libraryPath = argv[1]; //const string mediaUrl = argv[2]; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) throw runtime_error(string("Unable to initialize SDL: ") + SDL_GetError()); const string libraryPath = "signals-unity-bridge.dll"; const string mediaUrl = "http://vrt-pcl2dash.viaccess-orca.com/loot/vrtogether.mpd"; qDebug() << QString("libraryPath=%1 mediaUrl=%2").arg(libraryPath.c_str()).arg(mediaUrl.c_str()); auto lib = SDL_LoadObject(libraryPath.c_str()); if (!lib) throw runtime_error("Can't load '" + libraryPath + "': " + SDL_GetError()); auto func_sub_create = IMPORT(sub_create); auto func_sub_play = IMPORT(sub_play); auto func_sub_destroy = IMPORT(sub_destroy); auto func_sub_grab_frame = IMPORT(sub_grab_frame); auto func_sub_get_stream_count = IMPORT(sub_get_stream_count); auto handle = func_sub_create("MyMediaPipeline"); func_sub_play(handle, mediaUrl.c_str()); if (func_sub_get_stream_count(handle) == 0) throw runtime_error("No streams found"); vector<uint8_t> buffer; for (int i = 0; i < 100000; ++i) { FrameInfo info{}; buffer.resize(1024 * 1024 * 10); auto size = func_sub_grab_frame(handle, 0, buffer.data(), buffer.size(), &info); buffer.resize(size); if (size == 0) SDL_Delay(100); else { printf("Frame: % 5d bytes, t=%.3f [", (int)size, info.timestamp / 1000.0); for (int k = 0; k < (int)buffer.size(); ++k) { if (k == 8) { printf(" ..."); break; } printf(" %.2X", buffer[k]); } printf(" ]\n"); } } func_sub_destroy(handle); SDL_UnloadObject(lib); } int SafeMain::safeMain() { // if(argc != 2 && argc != 3) // throw runtime_error("Usage: app.exe <signals-unity-bridge.dll> [media url]"); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) throw runtime_error(string("Unable to initialize SDL: ") + SDL_GetError()); const string libraryPath = "signals-unity-bridge.dll"; const string mediaUrl = "http://vrt-pcl2dash.viaccess-orca.com/loot/vrtogether.mpd"; qDebug() << QString("libraryPath=%1 mediaUrl=%2").arg( libraryPath.c_str() ).arg(mediaUrl.c_str()); auto lib = SDL_LoadObject("D:/i2cat_vrtogether/v30_stable_qt5/getSUB/w64/signals-unity-bridge.dll");// libraryPath.c_str()); if (!lib)fprintf(stdout, "Error=%s", SDL_GetError()); auto func_sub_create = IMPORT(sub_create); auto func_sub_play = IMPORT(sub_play); auto func_sub_destroy = IMPORT(sub_destroy); auto func_sub_grab_frame = IMPORT(sub_grab_frame); Timer myTimer; FrameInfo* info = 0; info = (FrameInfo*)malloc(sizeof(FrameInfo)); int streamIndex = 0; uint8_t* dst = 0; auto handle = func_sub_create("MyMediaPipeline"); // struct sub_handle hhh = func_create("MyMediaPipeline"); func_sub_play(handle, mediaUrl.c_str()); size_t iSize = 0;//(size_t)func_sub_grab_frame; size_t iSizeB = 1048576 * 1; dst = (uint8_t*)malloc(iSizeB); cwipc_point* mypcl; mypcl = (cwipc_point*)malloc(iSizeB * 2 * sizeof(cwipc_point)); //qDebug() << QString("dst=%1 mypcl=%2 cwipc_point=%3 ").arg(_msize(dst)).arg(_msize(mypcl)).arg(sizeof(cwipc_point)); for (int n = 0; n < 200; n++) { myTimer.start(); //fprintf(stdout, "\n\nn= %d\n", (int)n); Sleep(30); iSize = 1048576; streamIndex = 0; iSize = (size_t)func_sub_grab_frame(handle, streamIndex, 0, 0, info); if (iSize > 0) { //fprintf(stdout, "iSize= %d\n", (int)iSize); //fprintf(stdout, "dst_size= %d handle=%d iSize=%d info=%d \n", (unsigned int)_msize(dst), (unsigned int)handle, (unsigned int)iSize, (unsigned int)_msize(info)); iSize = (size_t)func_sub_grab_frame(handle, streamIndex, dst, iSize, info); //for (int i = 0; i < 20; i++) { // qDebug() << QString( "i=%1 buff=%2 %3 ").arg( i).arg( dst[i]).arg( QString::number(dst[i], 16)); //} // // Uncompress // cwipc_decoder *decoder = cwipc_new_decoder(); if (decoder == NULL) { qDebug() << QString("%1: Could not create decoder \n").arg(libraryPath.c_str()); return 1; } decoder->feed((void*)dst, iSize); // free((uint8_t *)dst); // After feed() we can free the input buffer bool ok = decoder->available(true); if (!ok) { qDebug() << QString("%1: Decoder did not create pointcloud \n").arg(libraryPath.c_str()); return 1; } cwipc *pc = decoder->get(); if (pc == NULL) { qDebug() << QString("%1: Decoder did not return cwipc \n").arg(libraryPath.c_str()); return 1; } decoder->free(); // We don't need the encoder anymore //qDebug() << "Decoded successfully, " << pc->get_uncompressed_size(CWIPC_POINT_VERSION) << " bytes (uncompressed)"; int isizepcl = pc->get_uncompressed_size(CWIPC_POINT_VERSION); pc->copy_uncompressed(mypcl, isizepcl); // // Save pointcloud file // //if (cwipc_write(argv[2], pc, NULL) < 0) { // std::cerr << argv[0] << ": Error writing PLY file " << argv[2] << std::endl; // return 1; //} pc->free(); // We no longer need to pointcloud //for (int i = 0; i < 50; i++) { // qDebug() << QString("i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg( i).arg( mypcl[i].x).arg( mypcl[i].y).arg( mypcl[i].z).arg( mypcl[i].r).arg( mypcl[i].g).arg( mypcl[i].b); //} } myTimer.stop(); double dTime = myTimer.getElapsedTimeInMilliSec(); fprintf(stdout, "............................................... time=%f ... ", dTime); } free(dst); dst = 0; free(mypcl); mypcl = 0; func_sub_destroy(handle); SDL_UnloadObject(lib); SDL_Quit(); //*/ return 1; } //**************************************************************************** void SafeMain::stopSUBThreads() { qDebug("stopSUBThreads Stopping threads ......................... "); if (theSUBNodes.size() < 1)return; QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->stop(); ++itGeom; } itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->wait(); ++itGeom; } } void SafeMain::unStopSUBThreads() { qDebug("unStopSUBThreads unStopping threads ......................... "); QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->unStop(); ++itGeom; } } void SafeMain::startSUBThreads() { qDebug() << QString("startSUBThreads ............... "); int iIndex = 0; QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { //uint sz3 = sz2; //if (szrest >= (uint)iIndex)sz3++; qDebug() << QString("VRtogetherWidget::startSUBThreads iIndex=%1 ").arg(iIndex); CapturSUBThread* thNode = (*itGeom); //thNode->setLimit(sz3); //thNode->setCount(0); //thNode->setMethod(0); thNode->setID(iIndex); ++itGeom; iIndex++; } iIndex = 0; itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); thNode->start((QThread::Priority)QThread::LowPriority); qDebug() << QString("startSUBThreads iIndex=%1 ").arg(iIndex); ++itGeom; iIndex++; } /* enum Priority { IdlePriority, LowestPriority, LowPriority, NormalPriority, HighPriority, HighestPriority, TimeCriticalPriority, InheritPriority }; */ } void SafeMain::setSUBThreads() { // makeCurrent(); qDebug() << QString("VRtogetherWidget::setSUBThreads ........................ num=%1 ").arg(getSUBThreadsNumber()); for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = new CapturSUBThread(); QString tx1 = QString("TH%1").arg(i + 1); thNode->theGLMessageTh = &theGLMessage; thNode->setName(tx1); thNode->setID(i); mypcl[i] = thNode->getPCL(); theSUBNodes.append(thNode); } qDebug() << QString("setSUBThreads MAXQTHREADS= %1").arg(getSUBThreadsNumber()); int i = 0; QVector<CapturSUBThread*>::iterator itGeom = theSUBNodes.begin(); while (itGeom != theSUBNodes.end()) { CapturSUBThread* thNode = (*itGeom); // qDebug() << QString("name=%1 worker=%2").arg(thNode->getName()).arg(thNode->getWorker()->getName()); qDebug() << QString("name=%1 ").arg(thNode->getName()); qDebug() << QString("SafeMain::setSUBThreads i=%1 mypcl_size=%2 mypcl_pointer=%3").arg(i).arg(_msize(mypcl[i])).arg((qlonglong)mypcl[i]); ++itGeom; i++; } } void SafeMain::destroySUBThreads() { QVector<CapturSUBThread*>::iterator it = theSUBNodes.begin(); while (it != theSUBNodes.end()) { it = theSUBNodes.erase(it); } qDebug() << QString("VRtogetherWidget::destroySUBThreads size=%1 ==== ").arg(theSUBNodes.size()); } void SafeMain::setUseSUBThreads(bool value) { //#define USE_CUDA_TREADS //#define USE_CUDA_NOTH //#define USE_CPU // doneCurrent(); if (!value) { stopSUBThreads(); } // makeCurrent(); if (value) { destroySUBThreads(); setSUBThreads(); startSUBThreads(); } } //***************************************************************************** void SafeMain::normalizeAngle(int *angle) { while (*angle < 0) *angle += 360 * 16; while (*angle > 360 * 16) *angle -= 360 * 16; } void SafeMain::setXRotation(int angle) { normalizeAngle(&angle); if (angle != xRot) { xRot = angle; emit xRotationChanged(angle); updateGL(); } } void SafeMain::setYRotation(int angle) { normalizeAngle(&angle); if (angle != yRot) { yRot = angle; emit yRotationChanged(angle); updateGL(); } } void SafeMain::setZRotation(int angle) { normalizeAngle(&angle); if (angle != zRot) { zRot = angle; emit zRotationChanged(angle); updateGL(); } } void SafeMain::setYElev(int elev) { yElev += elev; updateGL(); } void SafeMain::animate() { // qDebug() << QString("VRtogetherWidget::animate ------ initialized=%1 allocated=%2 plyloaded=%3 ").arg(initialized).arg(allocated).arg(plyloaded); if(!getInitialized() || !getAllocated())return; // qDebug() << QString("animate %1").arg(drawed); //theGLMessage.startAnimate(); paintGL(); addIncMov(); // gear1Rot += 2 * 16; drawed++; //frameRate.newFrame(); update(); } void SafeMain::initializeGL() { /* static const GLfloat lightPos[4] = { 5.0f, 5.0f, 10.0f, 1.0f }; static const GLfloat reflectance1[4] = { 0.8f, 0.1f, 0.0f, 1.0f }; static const GLfloat reflectance2[4] = { 0.0f, 0.8f, 0.2f, 1.0f }; static const GLfloat reflectance3[4] = { 0.2f, 0.2f, 1.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_POSITION, lightPos); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); gear1 = makeGear(reflectance1, 1.0, 4.0, 1.0, 0.7, 20); gear2 = makeGear(reflectance2, 0.5, 2.0, 2.0, 0.7, 10); gear3 = makeGear(reflectance3, 1.3, 2.0, 0.5, 0.7, 10); glEnable(GL_NORMALIZE); glClearColor(1.0f, 0.5f, 0.0f, 1.0f); //*/ // Declare RealSense pipeline, encapsulating the actual device and sensors //rs2::pipeline pipe; // Start streaming with default recommended configuration // pipe.start(); setFocus(); qDebug() << QString("SafeMain::initializeGL _____________________________________________________ "); glClearColor(1.0, 0.0, 0.5, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); #ifdef USE_CUDA_TREADS for(int i=0; i<iThreadsNumber; i++) { ViewerVertexBufferTh[i] = new GLVertexBuffers; ViewerVertexBufferTh[i]->setParams(i);// create vertexBuffer, colorBuffer and indexBuffer. } #else ViewerVertexBuffer1 = new GLVertexBuffers; ViewerVertexBuffer1->setParams(iBufferID);// create vertexBuffer, colorBuffer and indexBuffer. #endif setBuffers();// create the buffers posns, colors and indices. #ifdef USE_CUDA_TREADS int iPosBlock = 0;//iIndex * BUFFERMEM; int iMaxMem2 = (iMaxMem / iThreadsNumber) * 1; for(int i=0; i<iThreadsNumber; i++) { IndexType *indices = ViewerVertexBufferTh[i]->getIndices(iPosBlock); // qDebug() << QString("........................ pointer to indices=%1 ").arg((uint)indices); Q_ASSERT(indices); qDebug() << QString("Filling indices.........."); int iIndex = 0; for (int i1 = 0; i1 < MAX_Y / iThreadsNumber; i1++) { for (int j1 = 0; j1 < MAX_X; j1++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } num_elemsTh[i] = iIndex; qDebug() << QString("................................ th=%1 num_elemsTh=%2 ").arg(i).arg(num_elemsTh[i]); ViewerVertexBufferTh[i]->allocVertexBuffer(iMaxMem2); ViewerVertexBufferTh[i]->allocColorBuffer(iMaxMem2); ViewerVertexBufferTh[i]->allocIndexBuffer(iMaxMem2); } // m_iNumVertices = iIndex; // m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; //*/ #else IndexType *indices = ViewerVertexBuffer1->getIndices(); // qDebug() << QString("........................ pointer to indices=%1 ").arg((uint)indices); Q_ASSERT(indices); ViewerVertexBuffer1->allocVertexBuffer(iMaxMem); ViewerVertexBuffer1->allocColorBuffer(iMaxMem); //ViewerVertexBuffer1->allocAllBuffer(iMaxMem); ViewerVertexBuffer1->allocIndexBuffer(iMaxMem); qDebug() << QString("Filling indices.......... iMaxMem=%1 indices_size=%2 ").arg(iMaxMem).arg(_msize(indices)); int iIndex = 0; for (int i = 0; i < MAX_Y; i++) { for (int j = 0; j < MAX_X; j++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } qDebug() << QString("Idices filled................................ "); num_elems = iIndex; m_iNumVertices = iIndex; m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; qDebug() << QString("................................ num_elems=%1 ").arg(num_elems); #ifndef THREADSUB mySUB01->read_ini(0); mySUB02->read_ini(1); mySUB03->read_ini(2); #endif #endif //#define USE_CUDA_TREADS //#define USE_CUDA_NOTH //#define USE_CPU #ifdef USE_CUDA #ifdef USE_CUDA_NOTH setCudaParam(); allocVerticesCUDA(); #endif #ifdef USE_CUDA_TREADS setCudaParamThreads(); for(int i=0; i<iThreadsNumber; i++) { allocVerticesCUDAThreads(i); } #endif #ifdef USE_CUDA_TREADS_ONE setCudaParamMulti(); allocVerticesCUDA(); #endif #endif // qDebug() << QString("Filling indices.........."); // int iIndex = 0; // for (int i = 0; i < MAX_Y; i++) { // for (int j = 0; j < MAX_X; j++) { // indices[iIndex] = IndexType(iIndex); // iIndex++; // } // } // num_elems = iIndex; // m_iNumVertices = iIndex; // m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; // qDebug() << QString("................................ num_elems=%1 ").arg(num_elems); ////*/ #ifdef USE_CUDA_TREADS setUseThreads(true); #endif // setUseSUBThreads(true); // oneAvatar(); initialized = true; /// The devices was initialized allocated = true; /// The memory was allocated plyloaded = true; /// The file PLY was loaded } void SafeMain::processGeomCUDA(float despX, float despY, float despZ) { QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); QVector4Du* vColor = ViewerVertexBuffer1->getColors(); IndexType* vIndices = ViewerVertexBuffer1->getIndices(); bool bDraw = false; int iTest = 0; int iNumAvat = 6; FrameInfo* timestampInfo[NUMPCL]; for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; iTest = iAvatar & 16; if (iTest && i == 4)bDraw = true; iTest = iAvatar & 32; if (iTest && i == 5)bDraw = true; iTest = iAvatar & 64; if (iTest && i == 6)bDraw = true; iTest = iAvatar & 128; if (iTest && i == 7)bDraw = true; iTest = iAvatar & 256; if (iTest && i == 8)bDraw = true; iTest = iAvatar & 512; if (iTest && i == 9)bDraw = true; iTest = iAvatar & 1024; if (iTest && i == 10)bDraw = true; iTest = iAvatar & 2048; if (iTest && i == 11)bDraw = true; // qDebug() << QString("SafeMain::processGeom th=%2 bDraw=%3 ").arg(i).arg(bDraw); // qDebug() << QString("iAvatar=%1 th=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { //ViewerVertexBuffer1->clearVertexBufferMem(64536, 1); //ViewerVertexBuffer1->clearColorBufferMem(64536, 1); int iposmat = 0; mypcl[i] = thNode->getPCL(); timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; iNumPointsPrev[i][iPosPrev] = iNumPoints[i]; // qDebug() << QString("th=%1 iNumPoints=%2 iAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(QString::number( iAvatar, 16)); if (iNumPoints[i] > 0 && mypcl[i]) { int iNumAvatar = 5; if (bOnlyOne)bDraw = false; if (iAvatar == 1 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } if (iAvatar == 2 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } if (iAvatar == 4 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } //if (bOnlyOne) iNumAvatar = 1; //qDebug() << QString("SafeMain::processGeomTh th=%1 iNumPoints=%2 iNumAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(iNumAvatar); for (int j1 = 0; j1 < iNumAvatar; j1++) { if (bDraw) { iposmat = (i * 5) + j1; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (!bOnlyOne) { vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif int uio = 0; } } if (i >= 2 && bDraw) { iposmat = (i * 5) + 5; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif } } if (iPosPrev >= 10)iPosPrev = -1; iPosPrev++; } bDraw = false; } } void SafeMain::processGeomTh(float despX, float despY, float despZ) { QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); QVector4Du* vColor = ViewerVertexBuffer1->getColors(); IndexType* vIndices = ViewerVertexBuffer1->getIndices(); bool bDraw = false; int iTest = 0; int iNumAvat = 6; FrameInfo* timestampInfo[NUMPCL]; for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; iTest = iAvatar & 16; if (iTest && i == 4)bDraw = true; iTest = iAvatar & 32; if (iTest && i == 5)bDraw = true; iTest = iAvatar & 64; if (iTest && i == 6)bDraw = true; iTest = iAvatar & 128; if (iTest && i == 7)bDraw = true; iTest = iAvatar & 256; if (iTest && i == 8)bDraw = true; iTest = iAvatar & 512; if (iTest && i == 9)bDraw = true; iTest = iAvatar & 1024; if (iTest && i == 10)bDraw = true; iTest = iAvatar & 2048; if (iTest && i == 11)bDraw = true; // qDebug() << QString("SafeMain::processGeom th=%2 bDraw=%3 ").arg(i).arg(bDraw); // qDebug() << QString("iAvatar=%1 th=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { //ViewerVertexBuffer1->clearVertexBufferMem(64536, 1); //ViewerVertexBuffer1->clearColorBufferMem(64536, 1); int iposmat = 0; mypcl[i] = thNode->getPCL(); timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; iNumPointsPrev[i][iPosPrev] = iNumPoints[i]; // qDebug() << QString("th=%1 iNumPoints=%2 iAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(QString::number( iAvatar, 16)); if (iNumPoints[i] > 0 && mypcl[i]) { int iNumAvatar = 5; if (bOnlyOne)bDraw = false; if (iAvatar == 1 && bOnlyOne) { bDraw = true; iNumAvatar = 1; }; if (iAvatar == 2 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } if (iAvatar == 4 && bOnlyOne) { bDraw = true; iNumAvatar = 1; } //if (bOnlyOne) iNumAvatar = 1; //qDebug() << QString("SafeMain::processGeomTh th=%1 iNumPoints=%2 iNumAvatar=%3 ").arg(i).arg(iNumPoints[i]).arg(iNumAvatar); for (int j1 = 0; j1 < iNumAvatar; j1++) { if (bDraw) { iposmat = (i * 5) + j1; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (!bOnlyOne) { vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif int uio = 0; } } if (i >= 2 && bDraw) { iposmat = (i * 5) + 5; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); #ifdef USE_CPU ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); #endif } } if (iPosPrev >= 10)iPosPrev = -1; iPosPrev++; } bDraw = false; } } void SafeMain::processGeom(float despX, float despY, float despZ) { #ifndef THREADSUB QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); QVector4Du* vColor = ViewerVertexBuffer1->getColors(); IndexType* vIndices = ViewerVertexBuffer1->getIndices(); bool bDraw = false; int iTest = 0; int iNumAvat = 6; FrameInfo* timestampInfo[NUMPCL]; int iposmat = 0; int i = 0; mypcl[i] = mySUB01->getPCL(); timestampInfo[i] = mySUB01->getInfo(); iNumPoints[i] = mySUB01->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (!bOnlyOne) { vx += despX; vy += despY; vz += despZ; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } } //*/ vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); } #endif } void SafeMain::paintGL() { if(!getInitialized() || !getAllocated())return; /* void (TVMReceiver::* ptfptr)(uint, DMesh) = &TVMReceiver::micasa; fnOnReceivedMesh(TVMReceiver::* tvmptr)(uint, DMesh) = &TVMReceiver::michoza; fnOnConnectionError(TVMReceiver::* errorptr)(uint) = &TVMReceiver::mierror; myTVMReceiver->myMesh.nVertices = 0; myTVMReceiver->myMesh.nTextures = 0; myTVMReceiver->myMesh.nTriangles = 0; //*/ // Wait for the next set of frames from the camera //auto frames = pipe.wait_for_frames(); //auto depth = frames.get_depth_frame(); #ifdef THREADSUB QMutex doStopMutex; #endif Timer time01; iTotalPoints = 0; theGLMessage.startDevices(); theGLMessage.startCPU(); glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1, 1); glDisable(GL_TEXTURE_2D); glEnable(GL_COLOR_MATERIAL); //qDebug() << QString("SafeMain::paintGL m_fDistEye=%1 yElev=%2 ").arg(m_fDistEye).arg(yElev); int iW = (width() * 0.5) + m_fDistEye; int iH = (height() * 0.5) + m_fDistEye; // glPushMatrix(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-iW, iW , -iH, iH, -10000, 10000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, yElev, 0); // qDebug() << QString("m_fDistEye=%1 yElev=%2 ").arg(m_fDistEye).arg(yElev); //glRotated(xRot / 16.0, 1.0, 0.0, 0.0); //glRotated(yRot / 16.0, 0.0, 1.0, 0.0); //glRotated(zRot / 16.0, 0.0, 0.0, 1.0); glRotated(xRot, 1.0, 0.0, 0.0); glRotated(yRot, 0.0, 1.0, 0.0); glRotated(zRot, 0.0, 0.0, 1.0); float fScale = 200.0; glScalef(fScale, fScale, fScale); yRot += 2.0; // qDebug() << QString("xRot=%1 yRot=%2 zRot=%3 ").arg(xRot).arg(yRot).arg(zRot); /* drawGear(gear1, -3.0, -2.0, 0.0, gear1Rot / 16.0); drawGear(gear2, +3.1, -2.0, 0.0, -2.0 * (gear1Rot / 16.0) - 9.0); glRotated(+90.0, 1.0, 0.0, 0.0); drawGear(gear3, -3.1, -1.8, -2.2, +2.0 * (gear1Rot / 16.0) - 2.0); //*/ float fPointThick = 3.0f; glPointSize(fPointThick); //float brt = 1.5; //float con = 2.0; //float sat = 1.5; #ifdef USE_CPU //GenerateCloud();// leer nuve de puntos de SUB Q_ASSERT(ViewerVertexBuffer1); //doStopM02.lock(); //for (int i = 0; i < 20; i++) { // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=0 ").arg(i).arg(mypcl[0][i].x).arg(mypcl[0][i].y).arg(mypcl[0][i].z).arg(mypcl[0][i].r).arg(mypcl[0][i].g).arg(mypcl[0][i].b); // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=1 ").arg(i).arg(mypcl[1][i].x).arg(mypcl[1][i].y).arg(mypcl[1][i].z).arg(mypcl[1][i].r).arg(mypcl[1][i].g).arg(mypcl[1][i].b); // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=2 ").arg(i).arg(mypcl[2][i].x).arg(mypcl[2][i].y).arg(mypcl[2][i].z).arg(mypcl[2][i].r).arg(mypcl[2][i].g).arg(mypcl[2][i].b); // qDebug() << QString("safeMain i=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 uID=3 ").arg(i).arg(mypcl[3][i].x).arg(mypcl[3][i].y).arg(mypcl[3][i].z).arg(mypcl[3][i].r).arg(mypcl[3][i].g).arg(mypcl[3][i].b); //} //doStopM02.unlock(); filePos = 0; //QVector3D* vVertex = ViewerVertexBuffer1->getPosns(); //QVector4Du* vColor = ViewerVertexBuffer1->getColors(); //IndexType* vIndices = ViewerVertexBuffer1->getIndices(); // float* vVertexFloat = ViewerVertexBuffer1->getPosnsFloat(); //ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); //ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); // qDebug() << QString("paintGL ---------------------------------- "); #ifdef THREADSUB doStopMutex.lock(); #endif // glColor3f(1.0, 0.0, 0.0); theGLMessage.startPaint(); //bool bDraw = false; //int iTest = 0; //int iNumAvat = 6; //FrameInfo* timestampInfo[NUMPCL]; #ifdef THREADSUB //processGeom(0.0, 12.0, 0.0); //processGeom(-10.0, 0.0, 0.0); processGeomTh(0.0, 0.0, 0.0); // processGeom(0.0, 0.0, 0.0); //void CapturSUB::processGeom(GLVertexBuffers *ViewerVertexBuffer1, GLMessages* theGLMessage, bool bSeeColor, float despX, float despY, float despZ) //processGeom(10.0, 0.0, 0.0); //processGeom(0.0, -12.0, 0.0); //processGeom(10.0, 12.0, 0.0); //processGeom(-10.0, 12.0, 0.0); //processGeom(10.0, -12.0, 0.0); //processGeom(-10.0, -12.0, 0.0); #else float despX1 = 1.5; mySUB01->read(0); mySUB01->processGeom(ViewerVertexBuffer1, &theGLMessage, bSeeColor, -1.2 + despX1, 0, 0); //mySUB02->read(1); //mySUB02->processGeom(ViewerVertexBuffer1, &theGLMessage, bSeeColor, 0 + despX1, 0, 0); //mySUB03->read(2); //mySUB03->processGeom(ViewerVertexBuffer1, &theGLMessage, bSeeColor, 1.2 + despX1, 0, 0); #endif /* for (int i = 0; i < getSUBThreadsNumber(); i++) { CapturSUBThread* thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; iTest = iAvatar & 16; if (iTest && i == 4)bDraw = true; iTest = iAvatar & 32; if (iTest && i == 5)bDraw = true; iTest = iAvatar & 64; if (iTest && i == 6)bDraw = true; iTest = iAvatar & 128; if (iTest && i == 7)bDraw = true; iTest = iAvatar & 256; if (iTest && i == 8)bDraw = true; iTest = iAvatar & 512; if (iTest && i == 9)bDraw = true; iTest = iAvatar & 1024; if (iTest && i == 10)bDraw = true; iTest = iAvatar & 2048; if (iTest && i == 11)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { //ViewerVertexBuffer1->clearVertexBufferMem(64536, 1); //ViewerVertexBuffer1->clearColorBufferMem(64536, 1); int iposmat = 0; mypcl[i] = thNode->getPCL(); timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { for (int j1 = 0; j1 < 5; j1++) { iposmat = (i * 5) + j1; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } if (i >= 2) { iposmat = (i * 5) + 5; iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} theGLMessage.startOpenCL(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (iposmat == 0) { vx -= 1.5; vy -= 1.5; } if (iposmat == 1) { vx -= 1.5; vy += 1.5; } if (iposmat == 2) { vx += 1.5; vy -= 1.5; } if (iposmat == 3) { vx += 1.5; vy += 1.5; } if (iposmat == 4) { vx -= 3.0; vy -= 1.5; } if (iposmat == 5) { vx += 3.0; vy -= 1.5; } if (iposmat == 6) { vx -= 3.0; vy += 1.5; } if (iposmat == 7) { vx += 3.0; vy += 1.5; } if (iposmat == 8) { vx -= 1.5; vy -= 4.0; } if (iposmat == 9) { vx += 1.5; vy -= 4.0; } if (iposmat == 10) { vx -= 1.5; vy += 4.0; } if (iposmat == 11) { vx += 1.5; vy += 4.0; } if (iposmat == 12) { vx -= 3.0; vy -= 4.0; } if (iposmat == 13) { vx += 3.0; vy -= 4.0; } if (iposmat == 14) { vx -= 3.0; vy += 4.0; } if (iposmat == 15) { vx += 3.0; vy += 4.0; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = (mypcl[i][i1].r) * 0.5; uint8_t cg = (mypcl[i][i1].g) * 0.5; uint8_t cb = (mypcl[i][i1].b) * 0.5; uint8_t ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } theGLMessage.stopOpenCL(); // qDebug() << QString("time=%1 us").arg(time01.getElapsedTimeInMicroSec()); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); } } } bDraw = false; } //*/ theGLMessage.stopPaint(); /* int i = 0; CapturSUBThread* thNode = theSUBNodes.at(i); int iTest = 0; bDraw = false; iTest = iAvatar & 1; if (iTest && i == 0)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); FrameInfo* timestampInfo[NUMPCL]; timestampInfo[i] = thNode->getInfo(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } //*/ /* template <class T, class T2> T mix(const T &a, const T &b, const T2 &interp) { static constexpr T2 one = ((T2)1); return (a * (one - interp)) + (b * interp); } OPENCL __constant float3 LumCoeff = (float3)(0.2125, 0.7154, 0.0721); __constant float3 AvgLumin = (float3)(0.5, 0.5, 0.5); float3 brtColor = pixel1.xyz * brt; float3 intensity = (float3)(dot(brtColor, LumCoeff)); float3 satColor = mix(intensity, brtColor, sat); pixel1 = (float4)(mix(AvgLumin, satColor, con), 1.0); pixel1 = clamp(pixel1, 0.0, 1.0); CUDA float3 brtColor = pixel1 * brt; float3 intensity = make_float3(dot(brtColor, LumCoeff)); float3 satColor = lerp(intensity, brtColor, sat); pixel1 = lerp(AvgLumin, satColor, con); #define DOTPROD(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]) Procedure Truncate(value) If value < 0 Then value = 0 If value > 255 Then value = 255 Return value EndProcedure factor = (259 * (contrast + 255)) / (255 * (259 - contrast)) colour = GetPixelColour(x, y) newRed = Truncate(factor * (Red(colour) - 128) + 128) newGreen = Truncate(factor * (Green(colour) - 128) + 128) newBlue = Truncate(factor * (Blue(colour) - 128) + 128) PutPixelColour(x, y) = RGB(newRed, newGreen, newBlue) */ /* //uint8_t cr = (255 - mypcl[i][i1].r) * 0.299; //uint8_t cg = (255 - mypcl[i][i1].g) * 0.587; //uint8_t cb = (255 - mypcl[i][i1].b) * 0.114; float crB = mypcl[i][i1].r * brt; float cgB = mypcl[i][i1].g * brt; float cbB = mypcl[i][i1].b * brt; float intR = crB * 0.215; float intG = cgB * 0.7154; float intB = cbB * 0.0721; // float3 satColor = lerp(intensity, brtColor, sat); float satR = mix(intR, crB, sat); float satG = mix(intG, cgB, sat); float satB = mix(intB, cbB, sat); // pixel1 = (float4)(mix(AvgLumin, satColor, con), 1.0); float outR = mix(0.5, satR, con); float outG = mix(0.5, satG, con); float outB = mix(0.5, satB, con); uint8_t cr = (uint8_t)outR; uint8_t cg = (uint8_t)outG; uint8_t cb = (uint8_t)outB; uint8_t ca = 255; if (i1 < 12) { qDebug() << QString("outR=%1 outG=%2 outB=%3 cr=%4 cg=%5 cb=%6 ").arg(outR).arg(outG).arg(outB).arg(cr).arg(cb).arg(cb); } //*/ /* uint8_t cr = (mypcl[i][i1].r) * (0.299 * 1.5); uint8_t cg = (mypcl[i][i1].g) * (0.3 * 1.5);// 0.587; uint8_t cb = (mypcl[i][i1].b) * (0.3 * 1.5);// 0.114; uint8_t ca = 255; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); // cr = 0; cg = 255; cb = 0; ca = 255; vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); vColor[i1].setW(ca); if (i1 < 12) { qDebug() << QString("paintGL i1=%0 color=%1 %2 %3 %4 timestamp=%5 vColor=%6 %7 %8 %9 ") .arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()).arg(vColor[i1].w()).arg(timestampInfo[i]->timestamp) .arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()).arg(vColor[i1].w()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(4.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, true); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, false); // ViewerVertexBuffer1->printSizes(); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } //*/ /* i++; thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 2; if (iTest && i == 1)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = mypcl[i][i1].r; uint8_t cg = mypcl[i][i1].g; uint8_t cb = mypcl[i][i1].b; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, filePos, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } i++; thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 4; if (iTest && i == 2)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = mypcl[i][i1].r; uint8_t cg = mypcl[i][i1].g; uint8_t cb = mypcl[i][i1].b; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, filePos, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } i++; thNode = theSUBNodes.at(i); bDraw = false; iTest = iAvatar & 8; if (iTest && i == 3)bDraw = true; // qDebug() << QString("iAvatar=%1 i=%2 bDraw=%3 ").arg(QString::number(iAvatar, 16)).arg(i).arg(bDraw); if (bDraw) { mypcl[i] = thNode->getPCL(); iNumPoints[i] = thNode->getNumPoints(); num_elems = iNumPoints[i]; if (iNumPoints[i] > 0) { iTotalPoints += iNumPoints[i]; //qDebug() << QString("........................ paintGL i=%1 iNumPoint=%2 mypcl=%3 size=%4 cwipc_point=%5 filePos=%6 ").arg(i).arg(iNumPoints[i]).arg((qlonglong)mypcl[i]).arg(_msize(mypcl[i])).arg(sizeof(cwipc_point)).arg(filePos); //for (int n = 0; n < 30; n++) { // qDebug() << QString("paintGL n=%1 pcl=%2 %3 %4 rgb=%5 %6 %7 ").arg(n).arg(mypcl[i][n].x).arg(mypcl[i][n].y).arg(mypcl[i][n].z).arg(mypcl[i][n].r).arg(mypcl[i][n].g).arg(mypcl[i][n].b); //} time01.start(); for (int i1 = 0; i1 < iNumPoints[i]; i1++) { float vx = mypcl[i][i1].x; float vy = mypcl[i][i1].y; float vz = mypcl[i][i1].z; if (i == 0) { vx -= 1.5; vy -= 1.5; } if (i == 1) { vx -= 1.5; vy += 1.5; } if (i == 2) { vx += 1.5; vy -= 1.5; } if (i == 3) { vx += 1.5; vy += 1.5; } vVertex[i1].setX(vx); vVertex[i1].setY(vy); vVertex[i1].setZ(vz); // if (i1 < 20) { qDebug() << QString("i1=%0 vertex=%1 %2 %3 ").arg(i1).arg(vVertex[i1].x()).arg(vVertex[i1].y()).arg(vVertex[i1].z()); } uint8_t cr = mypcl[i][i1].r; uint8_t cg = mypcl[i][i1].g; uint8_t cb = mypcl[i][i1].b; //vColor[i1].setX(cb); //vColor[i1].setY(cg); //vColor[i1].setZ(cr); vColor[i1].setX(cr); vColor[i1].setY(cg); vColor[i1].setZ(cb); // if (i1 < 20) { qDebug() << QString("i1=%0 color=%1 %2 %3 ").arg(i1).arg(vColor[i1].x()).arg(vColor[i1].y()).arg(vColor[i1].z()); } } time01.stop(); // qDebug() << QString("time=%1 ").arg(time01.getElapsedTimeInMicroSec()); // ViewerVertexBuffer1->writeAllBuffer((uchar*)mypcl[i], iNumPoints[i], true); glPointSize(3.0); ViewerVertexBuffer1->writeVertexBuffer(vVertex, num_elems, filePos, false); ViewerVertexBuffer1->writeColorBuffer(vColor, num_elems, filePos, false); ViewerVertexBuffer1->writeIndexBuffer(vIndices, num_elems, filePos, false); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); if (bSeeColor)ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); else ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, false); int uio = 0; } } //*/ glDisable(GL_POLYGON_OFFSET_FILL); theGLMessage.stopCPU(); // float time02 = theGLMessage.getTimeMicrosegCPU(); #ifdef THREADSUB doStopMutex.unlock(); #endif //ViewerVertexBuffer1->bindVertexBuffer(); //ViewerVertexBuffer1->bindColorBuffer(); //ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false); //cwipc_point* mypcl[NUMPCL]; //int iNumPoints[NUMPCL]; //ViewerVertexBuffer1->bindIndexBufferAll(iNumPoints[0], (char*)mypcl[0], false, false, false); #endif #ifdef USE_CUDA_NOTH num_elems = MAX_X * MAX_Y; qDebug() << QString("num_elems=%1 ").arg(num_elems); // qDebug() << QString("VRtogetherWidget::paintGL vertexID=%1 colorID=%2 indicesID=%3 ").arg(vertexBuffer->bufferId()).arg(colorBuffer->bufferId()).arg(indicesBuffer->bufferId()); setVerticesCUDA(); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false); #endif #ifdef USE_CUDA_TREADS_ONE //unsigned int m = blockIdx.x * blockDim.x + threadIdx.x; //unsigned int n = blockIdx.y * blockDim.y + threadIdx.y; //if (m < MAX_X && n < MAX_Y2) //{ // uint iIndex = (n * MAX_X) + m; // uint iIndex1 = iPosStart + (iIndex * 3); // uint iIndex2 = iColStart + (iIndex * 4); qDebug() << QString("USE_CUDA_TREADS_ONE "); setVerticesCUDAMulti(); ViewerVertexBuffer1->bindVertexBuffer(); ViewerVertexBuffer1->bindColorBuffer(); ViewerVertexBuffer1->bindIndexBuffer(num_elems, false, false, true); #endif // qDebug() << QString("VRtogetherWidget::paintGL num_elems=%1 m_fDistEye=%2 ").arg(num_elems).arg(m_fDistEye); //*/ //glPopMatrix(); /* (myTVMReceiver->*ptfptr)(drawed, myTVMReceiver->myMesh); myTVMReceiver->p_RegisterOnReceivedMeshCallBack(clientID, (myTVMReceiver->*tvmptr)(clientID, myTVMReceiver->myMesh)); qDebug() << QString("nVertices=%1 nTextures=%2 nTriangles=%3 ").arg(myTVMReceiver->myMesh.nVertices).arg(myTVMReceiver->myMesh.nTextures).arg(myTVMReceiver->myMesh.nTriangles); myTVMReceiver->p_RegisterOnConnectionErrorCallBack(clientID, (myTVMReceiver->*errorptr)(clientID) ); //*/ } void SafeMain::resizeGL(int width, int height) { qDebug() << QString("SafeMain::resizeGL w=%1 h=%2 ...................................... ").arg(width).arg(height); int side = qMin(width, height); glViewport((width - side) / 2, (height - side) / 2, side, side); int iW = (width * 0.5) + m_fDistEye; int iH = (height * 0.5) + m_fDistEye; glMatrixMode(GL_PROJECTION); glLoadIdentity(); // glFrustum(-1.0, +1.0, -1.0, 1.0, 0.1, 10000.0); // glOrtho(0, iW , 0, iH, -5000, 5000); glOrtho(-iW, iW, -iH, iH, -5000, 5000); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // glTranslated(0.0, 0.0, -40.0); } void SafeMain::addIncMov() { incMov += moveUp; if (incMov >= 800)moveUp = -20; if (incMov <= -800)moveUp = +20; } //************************************************************************** void SafeMain::mousePressEvent(QMouseEvent *event) { setFocus(); lastPos = event->pos(); updateGL(); } void SafeMain::mouseMoveEvent(QMouseEvent *event) { setFocus(); int dx = event->x() - lastPos.x(); int dy = event->y() - lastPos.y(); dx *= 0.25; dy *= 0.25; if (event->buttons() & Qt::LeftButton) { setXRotation(xRot + dy);// +8 * dy); setYRotation(yRot + dx);// +8 * dx); } else if (event->buttons() & Qt::RightButton) { //setXRotation(xRot + dy);// +8 * dy); //setZRotation(zRot + dx);// +8 * dx); setYElev(-dy); } lastPos = event->pos(); updateGL(); } void SafeMain::wheelEvent(QWheelEvent* ptEvent) { setFocus(); QMutex doStopMutex; doStopMutex.lock(); setFocus(); int iNumDegrees = ptEvent->delta() / 8; int iDelta = (float)(iNumDegrees / 15); if (iDelta > 0) { incZoom(); } else { decZoom(); } doStopMutex.unlock(); updateGL(); } void SafeMain::keyPressEvent(QKeyEvent *e) { setFocus(); int iMod = e->modifiers(); if (e->key() == Qt::Key_Escape) { close(); } if (e->key() == Qt::Key_Space) { } if (iMod == Qt::NoModifier) { if (e->key() == Qt::Key_Plus) { /** Increments the wheel zoom factor */ m_fViewportZoomFactor = CONTROLLER_ZOOM_FACTOR; m_fDistEye += m_fViewportZoomFactor * 0.1f; } if (e->key() == Qt::Key_Minus) { /** Decremets the wheel zoom factor */ m_fViewportZoomFactor = -CONTROLLER_ZOOM_FACTOR; m_fDistEye += m_fViewportZoomFactor * 0.1f; } if (e->key() == Qt::Key_O) { if (bSeeColor)bSeeColor = false; else bSeeColor = true; update(); } if (e->key() == Qt::Key_0) { qDebug() << QString("Todos los Avatares "); glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (iAvatar == 0) iAvatar = 0xffffffff; else iAvatar = 0; bOnlyOne = false; //m_fDistEye = 150; m_fDistEye = 700.0; // m_fDistEye = 3150.0; yElev = -200; update(); } if (e->key() == Qt::Key_1) { qDebug() << QString("Avatar 1 "); glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 1; qDebug() << QString("iAvatar=%1 iTest=%2 ").arg(QString::number(iAvatar, 16)).arg(iTest); if (iTest) { qDebug() << QString("Avatar 1 in1 %1").arg(QString::number(iAvatar, 16)); iAvatar = iAvatar & 0xfffffffffffffffe; } else { qDebug() << QString("Avatar 1 in2 %1").arg(QString::number(iAvatar, 16)); iAvatar = iAvatar | 1; } qDebug() << QString("Avatar 1 out %1").arg(QString::number(iAvatar, 16)); update(); } if (e->key() == Qt::Key_2) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 2; if (iTest) iAvatar = iAvatar & 0xfffffffd; else iAvatar = iAvatar | 2; } if (e->key() == Qt::Key_3) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 4; if (iTest) iAvatar = iAvatar & 0xfffffffb; else iAvatar = iAvatar | 4; } if (e->key() == Qt::Key_4) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); int iTest = iAvatar & 8; if (iTest) iAvatar = iAvatar & 0xfffffff7; else iAvatar = iAvatar | 8; } if (e->key() == Qt::Key_A) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 1; if (iTest) iAvatar = iAvatar & 0xfffffffe; else iAvatar = iAvatar | 1; iAvatar = 1; bOnlyOne = true; m_fDistEye = -150; yElev = -200; } if (e->key() == Qt::Key_B) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 2; if (iTest) iAvatar = iAvatar & 0xfffffffd; else iAvatar = iAvatar | 2; iAvatar = 2; bOnlyOne = true; m_fDistEye = -150; yElev = -200; } if (e->key() == Qt::Key_C) { glClearColor(1.0, 0.5, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); iNumBlocks = 1; filePos = 0; QVector3D* posns = ViewerVertexBuffer1->getPosns(); QVector4Du* colors = ViewerVertexBuffer1->getColors(); // clear the Vertex Buffer ViewerVertexBuffer1->clearVertexBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeVertexBuffer(posns, iMaxMem, false); // Clear the Color Buffer ViewerVertexBuffer1->clearColorBufferMem(iMaxMem, iNumBlocks); ViewerVertexBuffer1->writeColorBuffer(colors, iMaxMem, false); int iTest = iAvatar & 4; if (iTest) iAvatar = iAvatar & 0xfffffffb; else iAvatar = iAvatar | 4; iAvatar = 4; bOnlyOne = true; m_fDistEye = -140; yElev = -200; } } if (iMod == Qt::ShiftModifier) { if (e->key() == Qt::Key_Up) { yElev += 10; update(); } if (e->key() == Qt::Key_Down) { yElev -= 10; update(); } } if (iMod == Qt::ControlModifier) { if (e->key() == Qt::Key_1) { xRot = 225.0; yRot = 0.0; zRot = 30.0; update(); } if (e->key() == Qt::Key_2) { xRot = 270.0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_3) { xRot = 315.0; yRot = 0.0; zRot = 30.0; update(); } if (e->key() == Qt::Key_4) { xRot = 180.0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_5) { xRot = 0.0; yRot = 90.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_6) { xRot = 0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_7) { xRot = 135.0; yRot = 0.0; zRot = 30.0; update(); } if (e->key() == Qt::Key_8) { xRot = 270.0; yRot = 0.0; zRot = 0.0; update(); } if (e->key() == Qt::Key_9) { xRot = 45.0; yRot = 0.0; zRot = 30.0; update(); } } QWidget::keyPressEvent(e); } //*/ void SafeMain::setBuffers() { iNumBlocks = NUMVERTICES; iMaxMem = 1024 * 1024 * 2; iFileMaxSize = 50000;//68000000;//5745000; if(iFileMaxSize > (BUFFERMEM * 1) && iFileMaxSize < (BUFFERMEM * 2))iMaxMem = BUFFERMEM * 2; if(iFileMaxSize > (BUFFERMEM * 2) && iFileMaxSize < (BUFFERMEM * 4))iMaxMem = BUFFERMEM * 4; if(iFileMaxSize > (BUFFERMEM * 4) && iFileMaxSize < (BUFFERMEM * 6))iMaxMem = BUFFERMEM * 6; // if(iFileMaxSize > (BUFFERMEM * 6) && iFileMaxSize < (BUFFERMEM * 8))iMaxMem = BUFFERMEM * 8; // if(iFileMaxSize > (BUFFERMEM * 8) && iFileMaxSize < (BUFFERMEM * 10))iMaxMem = BUFFERMEM * 10; // if(iFileMaxSize > (BUFFERMEM * 10) && iFileMaxSize < (BUFFERMEM * 12))iMaxMem = BUFFERMEM * 12; // if(iFileMaxSize > (BUFFERMEM * 12) && iFileMaxSize < (BUFFERMEM * 14))iMaxMem = BUFFERMEM * 14; // if(iFileMaxSize > (BUFFERMEM * 14) && iFileMaxSize < (BUFFERMEM * 16))iMaxMem = BUFFERMEM * 16; // if(iFileMaxSize > (BUFFERMEM * 16) && iFileMaxSize < (BUFFERMEM * 18))iMaxMem = BUFFERMEM * 18; // if(iFileMaxSize > (BUFFERMEM * 18) && iFileMaxSize < (BUFFERMEM * 20))iMaxMem = BUFFERMEM * 20; // if(iFileMaxSize > (BUFFERMEM * 20) && iFileMaxSize < (BUFFERMEM * 22))iMaxMem = BUFFERMEM * 22; // if(iFileMaxSize > (BUFFERMEM * 22) && iFileMaxSize < (BUFFERMEM * 24))iMaxMem = BUFFERMEM * 24; // if(iFileMaxSize > (BUFFERMEM * 24) && iFileMaxSize < (BUFFERMEM * 26))iMaxMem = BUFFERMEM * 26; // if(iFileMaxSize > (BUFFERMEM * 26) && iFileMaxSize < (BUFFERMEM * 28))iMaxMem = BUFFERMEM * 28; // if(iFileMaxSize > (BUFFERMEM * 28) && iFileMaxSize < (BUFFERMEM * 30))iMaxMem = BUFFERMEM * 30; // if(iFileMaxSize > (BUFFERMEM * 30) && iFileMaxSize < (BUFFERMEM * 32))iMaxMem = BUFFERMEM * 32; // if(iFileMaxSize > (BUFFERMEM * 32) && iFileMaxSize < (BUFFERMEM * 34))iMaxMem = BUFFERMEM * 34; // if(iFileMaxSize > (BUFFERMEM * 34) && iFileMaxSize < (BUFFERMEM * 36))iMaxMem = BUFFERMEM * 36; // if(iFileMaxSize > (BUFFERMEM * 36) && iFileMaxSize < (BUFFERMEM * 38))iMaxMem = BUFFERMEM * 38; // if(iFileMaxSize > (BUFFERMEM * 38) && iFileMaxSize < (BUFFERMEM * 40))iMaxMem = BUFFERMEM * 40; // if(iFileMaxSize > (BUFFERMEM * 40) && iFileMaxSize < (BUFFERMEM * 42))iMaxMem = BUFFERMEM * 42; // if(iFileMaxSize > (BUFFERMEM * 42) && iFileMaxSize < (BUFFERMEM * 44))iMaxMem = BUFFERMEM * 44; // if(iFileMaxSize > (BUFFERMEM * 44) && iFileMaxSize < (BUFFERMEM * 46))iMaxMem = BUFFERMEM * 46; // if(iFileMaxSize > (BUFFERMEM * 46) && iFileMaxSize < (BUFFERMEM * 48))iMaxMem = BUFFERMEM * 48; // if(iFileMaxSize > (BUFFERMEM * 48) && iFileMaxSize < (BUFFERMEM * 50))iMaxMem = BUFFERMEM * 50; // if(iFileMaxSize > (BUFFERMEM * 50) && iFileMaxSize < (BUFFERMEM * 52))iMaxMem = BUFFERMEM * 52; // if(iFileMaxSize > (BUFFERMEM * 52) && iFileMaxSize < (BUFFERMEM * 54))iMaxMem = BUFFERMEM * 54; // if(iFileMaxSize > (BUFFERMEM * 54) && iFileMaxSize < (BUFFERMEM * 56))iMaxMem = BUFFERMEM * 56; // if(iFileMaxSize > (BUFFERMEM * 56) && iFileMaxSize < (BUFFERMEM * 58))iMaxMem = BUFFERMEM * 58; // if(iFileMaxSize > (BUFFERMEM * 58) && iFileMaxSize < (BUFFERMEM * 60))iMaxMem = BUFFERMEM * 60; // if(iFileMaxSize > (BUFFERMEM * 60) && iFileMaxSize < (BUFFERMEM * 62))iMaxMem = BUFFERMEM * 62; // if(iFileMaxSize > (BUFFERMEM * 62) && iFileMaxSize < (BUFFERMEM * 64))iMaxMem = BUFFERMEM * 64; // if(iFileMaxSize > (BUFFERMEM * 64) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 66; // if(iFileMaxSize > (BUFFERMEM * 66) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 68; // if(iFileMaxSize > (BUFFERMEM * 68) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 70; // if(iFileMaxSize > (BUFFERMEM * 70) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 72; // if(iFileMaxSize > (BUFFERMEM * 72) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 74; // if(iFileMaxSize > (BUFFERMEM * 74) && iFileMaxSize < (BUFFERMEM * 66))iMaxMem = BUFFERMEM * 76; //qDebug() << QString("posns_size=%1").arg(iNumBlocks * iMaxMem * 3); //qDebug() << QString("colors_size=%1").arg(iNumBlocks * iMaxMem); //qDebug() << QString("indices_size=%1").arg(iNumBlocks * iMaxMem); #ifdef USE_CUDA_TREADS int iMaxMem2 = iMaxMem / iThreadsNumber; qDebug() << QString(" iFileMaxSize=%1 iNumBlocks=%2 iMaxMem2=%3 iThreadsNumber=%4 " ).arg(iFileMaxSize).arg(iNumBlocks).arg(iMaxMem2).arg(iThreadsNumber); qDebug(); for(int i=0; i<iThreadsNumber; i++){ ViewerVertexBufferTh[i]->allocVertexBufferMem(iMaxMem2, iNumBlocks);// posns ViewerVertexBufferTh[i]->allocColorBufferMem(iMaxMem2, iNumBlocks);// colors ViewerVertexBufferTh[i]->allocIndexBufferMem(iMaxMem2, iNumBlocks);// indices } #else // qDebug() << QString(" iFileMaxSize=%1 iNumBlocks=%2 iMaxMem=%3 sizeQVector3D=%4 " ).arg(iFileMaxSize).arg(iNumBlocks).arg(iMaxMem).arg(sizeof(QVector3D)); // qDebug(); ViewerVertexBuffer1->allocVertexBufferMem(iMaxMem + 1024, iNumBlocks);// posns ViewerVertexBuffer1->allocColorBufferMem(iMaxMem + 1024, iNumBlocks);// colors // ViewerVertexBuffer1->allocAllBufferMem(iMaxMem + 1024, iNumBlocks); ViewerVertexBuffer1->allocIndexBufferMem(iMaxMem + 1024, iNumBlocks);// indices #endif // qDebug("//********************************************************************** "); // ViewerVertexBuffer1->printSizes(); // qDebug("//********************************************************************** "); } void SafeMain::paintEvent(QPaintEvent *event) { //updateGL(); // QPainter painter(this); painter.begin(this); QFont serifFont("Times", 10, QFont::Bold); painter.setFont(serifFont); theGLMessage.setColorTextGL(7); float fpscap = 0.0; int iNumCapFrame = 0; qreal fps = 1.0 / theGLMessage.getTimeSegCPU(); // qDebug() << QString("fps=%1").arg(fps); // setVars1(100, 1000, 99000); theGLMessage.drawGLText(&painter, fps, fpscap, iTotalPoints, iNumCapFrame); painter.end(); } void SafeMain::setVars1(int iVal1, int iVal2, int iVal3) { theGLMessage.setSizePCL1comp(iVal1); theGLMessage.setReadedPCL1comp(iVal2); theGLMessage.setUncomp1(iVal3); } void SafeMain::cudaInfo() { #ifdef USE_CUDA int deviceCount = 0; cudaError_t error_id = cudaGetDeviceCount(&deviceCount); qDebug() << QString("............................ cudaInfo ................................ "); if (error_id != cudaSuccess) { // printf("cudaGetDeviceCount returned %d\n-> %s\n", (int)error_id, cudaGetErrorString(error_id)); // printf("Result = FAIL\n"); qDebug() << QString("cudaGetDeviceCount returned %1\n-> %2\n").arg((int)error_id).arg(cudaGetErrorString(error_id)); qDebug() << QString("Result = FAIL\n"); exit(EXIT_FAILURE); } // This function call returns 0 if there are no CUDA capable devices. if (deviceCount == 0) { //printf("There are no available device(s) that support CUDA\n"); qDebug("There are no available device(s) that support CUDA\n"); } else { // printf("Detected %d CUDA Capable device(s)\n", deviceCount); qDebug() << QString("Detected %1 CUDA Capable device(s)\n").arg(deviceCount); } int dev, driverVersion = 0, runtimeVersion = 0; for (dev = 0; dev < deviceCount; ++dev) { cudaSetDevice(dev); cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, dev); // printf("\nDevice %d: \"%s\"\n", dev, deviceProp.name); qDebug() << QString("\nDevice %1: \"%2\"\n").arg( dev).arg( deviceProp.name); // Console log cudaDriverGetVersion(&driverVersion); cudaRuntimeGetVersion(&runtimeVersion); // printf(" CUDA Driver Version / Runtime Version %d.%d / %d.%d\n", driverVersion/1000, (driverVersion%100)/10, runtimeVersion/1000, (runtimeVersion%100)/10); // printf(" CUDA Capability Major/Minor version number: %d.%d\n", deviceProp.major, deviceProp.minor); qDebug() << QString(" CUDA Driver Version / Runtime Version %1.%2 / %3.%4\n").arg( driverVersion/1000).arg( (driverVersion%100)/10).arg( runtimeVersion/1000).arg( (runtimeVersion%100)/10); qDebug() << QString(" CUDA Capability Major/Minor version number: %1.%2\n").arg( deviceProp.major).arg( deviceProp.minor); char msg[256]; sprintf(msg, " Total amount of global memory: %.0f MBytes (%llu bytes)\n", (float)deviceProp.totalGlobalMem/1048576.0f, (unsigned long long) deviceProp.totalGlobalMem); qDebug() << QString("%1").arg( msg); qDebug() << QString(" (%1) Multiprocessors, (%2) CUDA Cores/MP: %3 CUDA Cores\n") .arg(deviceProp.multiProcessorCount) .arg(_ConvertSMVer2Cores(deviceProp.major, deviceProp.minor)) .arg(_ConvertSMVer2Cores(deviceProp.major, deviceProp.minor) * deviceProp.multiProcessorCount); qDebug() << QString(" GPU Clock rate: %1 MHz (%2 GHz)\n").arg( deviceProp.clockRate * 1e-3f).arg( deviceProp.clockRate * 1e-6f); #if CUDART_VERSION >= 5000 // This is supported in CUDA 5.0 (runtime API device properties) qDebug() << QString(" Memory Clock rate: %1 Mhz\n").arg( deviceProp.memoryClockRate * 1e-3f); qDebug() << QString(" Memory Bus Width: %2-bit\n").arg(deviceProp.memoryBusWidth); if (deviceProp.l2CacheSize) { qDebug() << QString(" L2 Cache Size: %1 bytes\n").arg( deviceProp.l2CacheSize); } #else // This only available in CUDA 4.0-4.2 (but these were only exposed in the CUDA Driver API) int memoryClock; getCudaAttribute<int>(&memoryClock, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, dev); printf(" Memory Clock rate: %.0f Mhz\n", memoryClock * 1e-3f); int memBusWidth; getCudaAttribute<int>(&memBusWidth, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, dev); printf(" Memory Bus Width: %d-bit\n", memBusWidth); int L2CacheSize; getCudaAttribute<int>(&L2CacheSize, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, dev); if (L2CacheSize) { printf(" L2 Cache Size: %d bytes\n", L2CacheSize); } #endif qDebug() << QString(" Maximum Texture Dimension Size (x,y,z) 1D=(%1), 2D=(%2, %3), 3D=(%4, %5, %6)\n") .arg(deviceProp.maxTexture1D ).arg( deviceProp.maxTexture2D[0], deviceProp.maxTexture2D[1]) .arg(deviceProp.maxTexture3D[0]).arg( deviceProp.maxTexture3D[1]).arg( deviceProp.maxTexture3D[2]); qDebug() << QString(" Maximum Layered 1D Texture Size, (num) layers 1D=(%1), %2 layers\n") .arg(deviceProp.maxTexture1DLayered[0]).arg( deviceProp.maxTexture1DLayered[1]); qDebug() << QString(" Maximum Layered 2D Texture Size, (num) layers 2D=(%1, %2), %3 layers\n") .arg(deviceProp.maxTexture2DLayered[0]).arg( deviceProp.maxTexture2DLayered[1]).arg( deviceProp.maxTexture2DLayered[2]); qDebug() << QString(" Total amount of constant memory: %1 bytes\n").arg( deviceProp.totalConstMem); qDebug() << QString(" Total amount of shared memory per block: %1 bytes\n").arg( deviceProp.sharedMemPerBlock); qDebug() << QString(" Total number of registers available per block: %1\n").arg( deviceProp.regsPerBlock); qDebug() << QString(" Warp size: %1\n").arg( deviceProp.warpSize); qDebug() << QString(" Maximum number of threads per multiprocessor: %1\n").arg( deviceProp.maxThreadsPerMultiProcessor); qDebug() << QString(" Maximum number of threads per block: %1\n").arg( deviceProp.maxThreadsPerBlock); qDebug() << QString(" Max dimension size of a thread block (x,y,z): (%1, %2, %3)\n") .arg(deviceProp.maxThreadsDim[0]) .arg(deviceProp.maxThreadsDim[1]) .arg(deviceProp.maxThreadsDim[2]); qDebug() << QString(" Max dimension size of a grid size (x,y,z): (%1, %2, %3)\n") .arg(deviceProp.maxGridSize[0]) .arg(deviceProp.maxGridSize[1]) .arg(deviceProp.maxGridSize[2]); qDebug() << QString(" Maximum memory pitch: %1 bytes\n").arg( deviceProp.memPitch); qDebug() << QString(" Texture alignment: %1 bytes\n").arg( deviceProp.textureAlignment); qDebug() << QString(" Concurrent copy and kernel execution: %1 with %2 copy engine(s)\n").arg( (deviceProp.deviceOverlap ? "Yes" : "No")).arg( deviceProp.asyncEngineCount); qDebug() << QString(" Run time limit on kernels: %1\n").arg( deviceProp.kernelExecTimeoutEnabled ? "Yes" : "No"); qDebug() << QString(" Integrated GPU sharing Host Memory: %1\n").arg( deviceProp.integrated ? "Yes" : "No"); qDebug() << QString(" Support host page-locked memory mapping: %1\n").arg( deviceProp.canMapHostMemory ? "Yes" : "No"); qDebug() << QString(" Alignment requirement for Surfaces: %1\n").arg( deviceProp.surfaceAlignment ? "Yes" : "No"); qDebug() << QString(" Device has ECC support: %1\n").arg( deviceProp.ECCEnabled ? "Enabled" : "Disabled"); #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) qDebug() << QString(" CUDA Device Driver Mode (TCC or WDDM): %1\n").arg( deviceProp.tccDriver ? "TCC (Tesla Compute Cluster Driver)" : "WDDM (Windows Display Driver Model)"); #endif qDebug() << QString(" Device supports Unified Addressing (UVA): %1\n").arg( deviceProp.unifiedAddressing ? "Yes" : "No"); qDebug() << QString(" Device PCI Bus ID / PCI location ID: %1 / %2\n").arg( deviceProp.pciBusID).arg( deviceProp.pciDeviceID); const char *sComputeMode[] = { "Default (multiple host threads can use ::cudaSetDevice() with device simultaneously)", "Exclusive (only one host thread in one process is able to use ::cudaSetDevice() with this device)", "Prohibited (no host thread can use ::cudaSetDevice() with this device)", "Exclusive Process (many threads in one process is able to use ::cudaSetDevice() with this device)", "Unknown", NULL }; qDebug() << QString(" Compute Mode:\n"); qDebug() << QString(" < %1 >\n").arg( sComputeMode[deviceProp.computeMode]); } // csv masterlog info // ***************************** // exe and CUDA driver name qDebug() << QString("\n"); std::string sProfileString = "deviceQuery, CUDA Driver = CUDART"; char cTemp[16]; // driver version sProfileString += ", CUDA Driver Version = "; #if defined(_MSC_VER) sprintf_s(cTemp, 10, "%d.%d", driverVersion/1000, (driverVersion%100)/10); #else sprintf(cTemp, "%d.%d", driverVersion/1000, (driverVersion%100)/10); #endif sProfileString += cTemp; // Runtime version sProfileString += ", CUDA Runtime Version = "; #if defined(_MSC_VER) sprintf_s(cTemp, 10, "%d.%d", runtimeVersion/1000, (runtimeVersion%100)/10); #else sprintf(cTemp, "%d.%d", runtimeVersion/1000, (runtimeVersion%100)/10); #endif sProfileString += cTemp; // Device count sProfileString += ", NumDevs = "; #if defined(_MSC_VER) sprintf_s(cTemp, 10, "%d", deviceCount); #else sprintf(cTemp, "%d", deviceCount); #endif sProfileString += cTemp; // Print Out all device Names for (dev = 0; dev < deviceCount; ++dev) { #if defined(_MSC_VER) sprintf_s(cTemp, 13, ", Device%d = ", dev); #else sprintf(cTemp, ", Device%d = ", dev); #endif cudaDeviceProp deviceProp; cudaGetDeviceProperties(&deviceProp, dev); sProfileString += cTemp; sProfileString += deviceProp.name; } sProfileString += "\n"; // printf("%s", sProfileString.c_str()); qDebug() << QString("%1").arg(sProfileString.c_str()); qDebug() << QString("Result = PASS\n"); // finish // cudaDeviceReset causes the driver to clean up all state. While // not mandatory in normal operation, it is good practice. It is also // needed to ensure correct operation when the application is being // profiled. Calling cudaDeviceReset causes all profile data to be // flushed before the application exits cudaDeviceReset(); qDebug() << QString("\n\n"); #endif } #ifdef USE_CUDA /** * @brief BezierWidget3x3::setCudaParam */ void SafeMain::setCudaParam() { // int m_iUsize = drawParams->getUsize(); // int m_iVsize = drawParams->getVsize(); qDebug() << QString("VRtogetherWidget::setCudaParam Start ,,,,,,,,,,,,,,,,,,,,,,,,,, "); CUresult error; // Initialize CUDA Driver API error = cuInit(0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } setUseCUDA(true); // Get number of devices supporting CUDA int deviceCount = 0; error = cuDeviceGetCount(&deviceCount); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } if (deviceCount == 0) { qDebug() << QString("There is no device supporting CUDA.\r\n"); exit(0); } error = cuDeviceGet(&cuDevice, 0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to get the first device CUDA.\r\n"); exit(0); } // Create context error = cuGLCtxCreate(&cuContext, 0, cuDevice); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al crear contexto CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContext); cuCtxDestroy(cuContext); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParam cuContext=%1 cuDevice=%2 ").arg((ulong)cuContext).arg((ulong)cuDevice); // CU_FUNC_CACHE_PREFER_NONE CU_FUNC_CACHE_PREFER_SHARED CU_FUNC_CACHE_PREFER_L1 CU_FUNC_CACHE_PREFER_EQUAL error = cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_EQUAL); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to Set Cache Config CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContext); cuCtxDestroy(cuContext); exit(0); } // D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx #ifdef Q_OS_WIN error = cuModuleLoad(&cuModule, "D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx"); #else error = cuModuleLoad(&cuModule, "/home/juanpinto/QT_OpenCL/qt-labs-opencl_matrix3x3/demos/temp/bezierpatch3x3.ptx"); #endif if (error != CUDA_SUCCESS) { qDebug() << QString("Error al leer el archivo PTX error=%1 \r\n").arg(error); error = cuCtxDetach(cuContext); cuCtxDestroy(cuContext); exit(0); } // _Z7vrtogCUPfPcPif // _Z7vrtogCUPfPcPif error = cuModuleGetFunction(&vrtogCU, cuModule, "_Z7vrtogCUPfPcPif"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); exit(0); } /* sizeCU = 100 * sizeof(int); error= cuMemAlloc(&nothingmemCU, sizeCU); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc nothingmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); exit(0); } //*/ qDebug() << QString("PTX loaded ......................................................... "); #ifdef DEBUGVR sizeCU10 = 10000 * sizeof(int); debugmemCUbytes0 = (int *)malloc(sizeCU10); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU0, sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU0, reinterpret_cast<const void *>(debugmemCUbytes0), sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU11 = 10000 * sizeof(int); debugmemCUbytes1 = (int *)malloc(sizeCU11); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU1, sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU1, reinterpret_cast<const void *>(debugmemCUbytes1), sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU12 = 10000 * sizeof(int); debugmemCUbytes2 = (int *)malloc(sizeCU12); memset(debugmemCUbytes2, 0, sizeCU12); error = cuMemAlloc(&debugmemCU2, sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU2, reinterpret_cast<const void *>(debugmemCUbytes2), sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU20 = 10000 * sizeof(float); debugmemFloatCUbytes0 = (float *)malloc(sizeCU20); memset(debugmemFloatCUbytes0, 0, sizeCU20); error = cuMemAlloc(&debugmemFloatCU0, sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU0, reinterpret_cast<const void *>(debugmemFloatCUbytes0), sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU21 = 10000 * sizeof(float); debugmemFloatCUbytes1 = (float *)malloc(sizeCU21); memset(debugmemFloatCUbytes1, 0, sizeCU21); error = cuMemAlloc(&debugmemFloatCU1, sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU1, reinterpret_cast<const void *>(debugmemFloatCUbytes1), sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU22 = 10000 * sizeof(float); debugmemFloatCUbytes2 = (float *)malloc(sizeCU22); memset(debugmemFloatCUbytes2, 0, sizeCU22); error = cuMemAlloc(&debugmemFloatCU2, sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU2, reinterpret_cast<const void *>(debugmemFloatCUbytes2), sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU30 = 10000 * sizeof(char); debugmemCharCUbytes0 = (char *)malloc(sizeCU30); memset(debugmemCharCUbytes0, 0, sizeCU30); error = cuMemAlloc(&debugmemCharCU0, sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU0, reinterpret_cast<const void *>(debugmemCharCUbytes0), sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU31 = 10000 * sizeof(char); debugmemCharCUbytes1 = (char *)malloc(sizeCU31); memset(debugmemCharCUbytes1, 0, sizeCU31); error = cuMemAlloc(&debugmemCharCU1, sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU1, reinterpret_cast<const void *>(debugmemCharCUbytes1), sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU32 = 10000 * sizeof(char); debugmemCharCUbytes2 = (char *)malloc(sizeCU32); memset(debugmemCharCUbytes2, 0, sizeCU32); error = cuMemAlloc(&debugmemCharCU2, sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU2, reinterpret_cast<const void *>(debugmemCharCUbytes2), sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } #endif //*/ int n = 0; seedmemCUbytes = (int *)malloc(MAX_X * sizeof(int)); for (int j = 0; j < MAX_X; j++) { seedmemCUbytes[n] = rand(); n++; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } //*/ /* int iFrameWidth = commonParams->getFrameWidth(); int iFrameHeight = commonParams->getFrameHeight(); bufferSize = iFrameWidth * iFrameHeight * sizeof(uchar3); error= cuMemAlloc(&bufferEffects1cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error= cuMemAlloc(&bufferEffects2cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } //*/ // setPBOcu(); qDebug() << QString("VRtogetherWidget::setCudaParam End "); qDebug() << QString("deviceCount=%1 \r\n").arg(deviceCount); } #endif #ifdef USE_CUDA /** * @brief BezierWidget3x3::setCudaParamMulti */ void SafeMain::setCudaParamMulti() { // int m_iUsize = drawParams->getUsize(); // int m_iVsize = drawParams->getVsize(); qDebug() << QString("VRtogetherWidget::setCudaParamMulti Start ,,,,,,,,,,,,,,,,,,,,,,,,,, "); CUresult error; // Initialize CUDA Driver API error = cuInit(0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } setUseCUDA(true); // Get number of devices supporting CUDA int deviceCount = 0; error = cuDeviceGetCount(&deviceCount); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } if (deviceCount == 0) { qDebug() << QString("There is no device supporting CUDA.\r\n"); exit(0); } error = cuDeviceGet(&cuDevice, 0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to get the first device CUDA.\r\n"); exit(0); } // Create context error = cuGLCtxCreate(&cuContextMulti, 0, cuDevice); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al crear contexto CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextMulti); cuCtxDestroy(cuContextMulti); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParamMulti cuContextMulti=%1 cuDevice=%2 ").arg((uint)cuContextMulti).arg((uint)cuDevice); // CU_FUNC_CACHE_PREFER_NONE CU_FUNC_CACHE_PREFER_SHARED CU_FUNC_CACHE_PREFER_L1 CU_FUNC_CACHE_PREFER_EQUAL error = cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_EQUAL); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to Set Cache Config CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextMulti); cuCtxDestroy(cuContextMulti); exit(0); } // D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx #ifdef Q_OS_WIN error = cuModuleLoad(&cuModule, "D:/i2cat_vrtogether/v30_stable_qt5/getSUB/vrtg01_cooda.ptx"); #else error = cuModuleLoad(&cuModule, "/home/juanpinto/QT_OpenCL/qt-labs-opencl_matrix3x3/demos/temp/bezierpatch3x3.ptx"); #endif if (error != CUDA_SUCCESS) { qDebug() << QString("Error al leer el archivo PTX error=%1 \r\n").arg(error); error = cuCtxDetach(cuContextMulti); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU01, cuModule, "_Z9vrtogCU01PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU01 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU02, cuModule, "_Z9vrtogCU02PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU02 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU03, cuModule, "_Z9vrtogCU03PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU03 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } error = cuModuleGetFunction(&vrtogCU04, cuModule, "_Z9vrtogCU04PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU04 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); exit(0); } //*/ qDebug() << QString("PTX loaded ......................................................... "); #ifdef DEBUGVR sizeCU10 = 10000 * sizeof(int); debugmemCUbytes0 = (int *)malloc(sizeCU10); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU0, sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU0, reinterpret_cast<const void *>(debugmemCUbytes0), sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU11 = 10000 * sizeof(int); debugmemCUbytes1 = (int *)malloc(sizeCU11); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU1, sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU1, reinterpret_cast<const void *>(debugmemCUbytes1), sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU12 = 10000 * sizeof(int); debugmemCUbytes2 = (int *)malloc(sizeCU12); memset(debugmemCUbytes2, 0, sizeCU12); error = cuMemAlloc(&debugmemCU2, sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU2, reinterpret_cast<const void *>(debugmemCUbytes2), sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU20 = 10000 * sizeof(float); debugmemFloatCUbytes0 = (float *)malloc(sizeCU20); memset(debugmemFloatCUbytes0, 0, sizeCU20); error = cuMemAlloc(&debugmemFloatCU0, sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU0, reinterpret_cast<const void *>(debugmemFloatCUbytes0), sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU21 = 10000 * sizeof(float); debugmemFloatCUbytes1 = (float *)malloc(sizeCU21); memset(debugmemFloatCUbytes1, 0, sizeCU21); error = cuMemAlloc(&debugmemFloatCU1, sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU1, reinterpret_cast<const void *>(debugmemFloatCUbytes1), sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU22 = 10000 * sizeof(float); debugmemFloatCUbytes2 = (float *)malloc(sizeCU22); memset(debugmemFloatCUbytes2, 0, sizeCU22); error = cuMemAlloc(&debugmemFloatCU2, sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU2, reinterpret_cast<const void *>(debugmemFloatCUbytes2), sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU30 = 10000 * sizeof(char); debugmemCharCUbytes0 = (char *)malloc(sizeCU30); memset(debugmemCharCUbytes0, 0, sizeCU30); error = cuMemAlloc(&debugmemCharCU0, sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU0, reinterpret_cast<const void *>(debugmemCharCUbytes0), sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU31 = 10000 * sizeof(char); debugmemCharCUbytes1 = (char *)malloc(sizeCU31); memset(debugmemCharCUbytes1, 0, sizeCU31); error = cuMemAlloc(&debugmemCharCU1, sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU1, reinterpret_cast<const void *>(debugmemCharCUbytes1), sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU32 = 10000 * sizeof(char); debugmemCharCUbytes2 = (char *)malloc(sizeCU32); memset(debugmemCharCUbytes2, 0, sizeCU32); error = cuMemAlloc(&debugmemCharCU2, sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU2, reinterpret_cast<const void *>(debugmemCharCUbytes2), sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } #endif //*/ int n = 0; seedmemCUbytes = (int *)malloc(MAX_X * sizeof(int)); for (int j = 0; j < MAX_X; j++) { seedmemCUbytes[n] = rand(); n++; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextMulti); return; } //*/ /* int iFrameWidth = commonParams->getFrameWidth(); int iFrameHeight = commonParams->getFrameHeight(); bufferSize = iFrameWidth * iFrameHeight * sizeof(uchar3); error= cuMemAlloc(&bufferEffects1cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error= cuMemAlloc(&bufferEffects2cu, bufferSize); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc bufferEffects1cu error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } //*/ // setPBOcu(); qDebug() << QString("VRtogetherWidget::setCudaParamMulti End "); qDebug() << QString("deviceCount=%1 \r\n").arg(deviceCount); } #endif void SafeMain::setVerticesCUDA() { #ifdef USE_CUDA int n = 0; bool useCUDA = getUseCUDA(); if (useCUDA == true) { qDebug() << QString("VRtogetherWidget::setVerticesCUDA ............... incMov=%1 ").arg(incMov); gmr = cuGraphicsMapResources(1, &positionCUDABuffer, 0); gmr = cuGraphicsMapResources(1, &posColorCUDABuffer, 0); cuGraphicsResourceGetMappedPointer(&pDevPtr[0], &num_bytes[0], positionCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[1], &num_bytes[1], posColorCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[2], &num_bytes[2], indicesCUDABuffer); uint argTestSize; void *argsTest[64]; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // void *config[] = { // CU_LAUNCH_PARAM_BUFFER_POINTER, argsTest, // CU_LAUNCH_PARAM_BUFFER_SIZE, &argTestSize, // CU_LAUNCH_PARAM_END // }; int iValXocl = MAX_X; int iValYocl = MAX_Y; unsigned int blqY = iValYocl / block_size; unsigned int blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; gmr = cuLaunchKernel(vrtogCU, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error cuLaunchKernel=%1").arg(gmr); } cuGraphicsUnmapResources(1, &positionCUDABuffer, 0); cuGraphicsUnmapResources(1, &posColorCUDABuffer, 0); cuGraphicsUnmapResources(1, &indicesCUDABuffer, 0); // theGLMessage.stopCUDA(); #ifdef DEBUGVR // copy result from device to host gmr = cuMemcpyDtoH((int *)debugmemCUbytes0, debugmemCU0, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error10 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes1, debugmemCU1, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error11 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes2, debugmemCU2, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error12 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes0, debugmemFloatCU0, sizeCU20); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error20 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes1, debugmemFloatCU1, sizeCU21); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error21 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes2, debugmemFloatCU2, sizeCU22); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error22 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes0, debugmemCharCU0, sizeCU30); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error30 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes1, debugmemCharCU1, sizeCU31); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error31 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes2, debugmemCharCU2, sizeCU32); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error32 cuMemcpyDtoH=%1").arg(gmr); } #endif // for (int i = 1024; i < 1024+16; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 char=%8 %9 %10").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]) // .arg((uchar)debugmemCharCUbytes0[i]).arg((uchar)debugmemCharCUbytes1[i]).arg((uchar)debugmemCharCUbytes2[i]); // } // qDebug("\n"); } #endif } void SafeMain::freeVerticesCUDA() { qDebug("Deallocating Memory........................"); #ifdef USE_CUDA qDebug("Freeing CUDA buffers "); cuGraphicsUnregisterResource(positionCUDABuffer); cuGraphicsUnregisterResource(posColorCUDABuffer); cuGraphicsUnregisterResource(indicesCUDABuffer); #endif m_iNumVertices = 0; qDebug("Deallocated Memory........................"); } void SafeMain::setVerticesCUDAMulti() { #ifdef USE_CUDA int n = 0; ulong ulPosStart = 0; ulong ulColStart = 0; bool useCUDA = getUseCUDA(); if (useCUDA == true) { qDebug() << QString("VRtogetherWidget::setVerticesCUDAMulti ............... incMov=%1 ").arg(incMov); gmr = cuGraphicsMapResources(1, &positionCUDABuffer, 0); gmr = cuGraphicsMapResources(1, &posColorCUDABuffer, 0); gmr = cuGraphicsMapResources(1, &indicesCUDABuffer, 0); cuGraphicsResourceGetMappedPointer(&pDevPtr[0], &num_bytes[0], positionCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[1], &num_bytes[1], posColorCUDABuffer); cuGraphicsResourceGetMappedPointer(&pDevPtr[2], &num_bytes[2], indicesCUDABuffer); QGLBuffer *vertexBuffer = ViewerVertexBuffer1->getVertexBuffer(); QGLBuffer *colorBuffer = ViewerVertexBuffer1->getColorBuffer(); QGLBuffer *indexBuffer = ViewerVertexBuffer1->getIndexBuffer(); if (vertexBuffer) { vertexBuffer->bind(); glVertexPointer(3, GL_FLOAT, 0, 0); QVector3D *mappedV = (QVector3D *)vertexBuffer->map(QGLBuffer::WriteOnly); if (mappedV) { for (int q = 0; q < 32; q++)//iNumIndices; q++) { // if((q%3) == 0)qDebug(" \n"); // if((q % 4) == 0)qDebug() << " \n"; qDebug() << QString("GLVertexBuffers::bindVertexBuffer q=%0 vertex=%1 %2 %3 ").arg(q).arg(mappedV[q].x()).arg(mappedV[q].y()).arg(mappedV[q].z()); } } vertexBuffer->unmap(); vertexBuffer->release(); } pDevPtr[0][0]; uint argTestSize; void *argsTest[64]; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // void *config[] = { // CU_LAUNCH_PARAM_BUFFER_POINTER, argsTest, // CU_LAUNCH_PARAM_BUFFER_SIZE, &argTestSize, // CU_LAUNCH_PARAM_END // }; // glTranslatef(200, -100, 0); int iValXocl = MAX_X; int iValYocl = MAX_Y / 4; unsigned int blqY = iValYocl / block_size; unsigned int blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 1 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 1) { gmr = cuLaunchKernel(vrtogCU01, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 1 Error cuLaunchKernel=%1").arg(gmr); } } ulPosStart = iValYocl * iValXocl; ulColStart = ulPosStart; n = 0; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); iValXocl = MAX_X; iValYocl = MAX_Y / 4; blqY = iValYocl / block_size; blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 2 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 2) { gmr = cuLaunchKernel(vrtogCU02, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 2 Error cuLaunchKernel=%1").arg(gmr); } } ulPosStart = (iValYocl * iValXocl) * 2; ulColStart = ulPosStart; n = 0; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); iValXocl = MAX_X; iValYocl = MAX_Y / 4; blqY = iValYocl / block_size; blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 3 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 3) { gmr = cuLaunchKernel(vrtogCU03, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 3 Error cuLaunchKernel=%1").arg(gmr); } } ulPosStart = (iValYocl * iValXocl) * 3; ulColStart = ulPosStart; n = 0; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &pDevPtr[2]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // glTranslatef(-200, 100, 0); iValXocl = MAX_X; iValYocl = MAX_Y / 4; blqY = iValYocl / block_size; blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; qDebug() << QString("setVerticesCUDAMulti 4 iValYocl=%1 iValXocl=%2 blqY=%3 bkqX=%4 block_size=%5 ulPosStart=%6 ulColStart=%7 ") .arg(iValYocl).arg(iValXocl).arg(blqY).arg(blqX).arg(block_size).arg(ulPosStart).arg(ulColStart); if (!iAvatar || iAvatar == 4) { gmr = cuLaunchKernel(vrtogCU04, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAMulti 4 Error cuLaunchKernel=%1").arg(gmr); } } //*/ //***************************************************************************************************************************** cuGraphicsUnmapResources(1, &positionCUDABuffer, 0); cuGraphicsUnmapResources(1, &posColorCUDABuffer, 0); cuGraphicsUnmapResources(1, &indicesCUDABuffer, 0); // theGLMessage.stopCUDA(); #ifdef DEBUGVR // copy result from device to host gmr = cuMemcpyDtoH((int *)debugmemCUbytes0, debugmemCU0, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error10 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes1, debugmemCU1, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error11 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes2, debugmemCU2, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error12 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes0, debugmemFloatCU0, sizeCU20); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error20 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes1, debugmemFloatCU1, sizeCU21); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error21 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes2, debugmemFloatCU2, sizeCU22); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error22 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes0, debugmemCharCU0, sizeCU30); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error30 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes1, debugmemCharCU1, sizeCU31); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error31 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes2, debugmemCharCU2, sizeCU32); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error32 cuMemcpyDtoH=%1").arg(gmr); } #endif // for (int i = 1024; i < 1024+16; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 char=%8 %9 %10").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]) // .arg((uchar)debugmemCharCUbytes0[i]).arg((uchar)debugmemCharCUbytes1[i]).arg((uchar)debugmemCharCUbytes2[i]); // } // qDebug("\n"); } #endif } void SafeMain::allocVerticesCUDA() { #ifdef USE_CUDA IndexType *indices = ViewerVertexBuffer1->getIndices(); int iIndex = 0; for (int i = 0; i < MAX_Y; i++) { for (int j = 0; j < MAX_X; j++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } num_elems = iIndex; m_iNumVertices = iIndex; m_iNumVerticesPerThread = m_iNumVertices / iThreadsNumber; qDebug() << QString("VRtogetherWidget::allocVerticesCUDA ............................... m_iNumVertices=%1 m_iNumVerticesPerThread=%2").arg(m_iNumVertices).arg(m_iNumVerticesPerThread); filePos = 0; ViewerVertexBuffer1->writeIndexBuffer(indices, num_elems, false); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA Allocating CUDA Buffers..."); QGLBuffer *vertexBuffer = ViewerVertexBuffer1->getVertexBuffer(); QGLBuffer *colorBuffer = ViewerVertexBuffer1->getColorBuffer(); QGLBuffer *indexBuffer = ViewerVertexBuffer1->getIndexBuffer(); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA Setting CUDA interoperability ....."); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA vertexID=%1 colorID=%2 ").arg(vertexBuffer->bufferId()).arg(colorBuffer->bufferId()); cuGraphicsGLRegisterBuffer(&positionCUDABuffer, vertexBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); cuGraphicsGLRegisterBuffer(&posColorCUDABuffer, colorBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); cuGraphicsGLRegisterBuffer(&indicesCUDABuffer, indexBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); qDebug() << QString("VRtogetherWidget::allocVerticesCUDA Finished CUDA interoperability setting ....."); #endif setAllocated(true); } #ifdef USE_CUDA /** * @brief BezierWidget3x3::setCudaParamThreads */ void SafeMain::setCudaParamThreads() { // int m_iUsize = drawParams->getUsize(); // int m_iVsize = drawParams->getVsize(); qDebug() << QString("VRtogetherWidget::setCudaParamThreads Start ,,,,,,,,,,,,,,,,,,,,,,,,,, "); CUresult error; // Initialize CUDA Driver API error = cuInit(0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } setUseCUDA(true); // Get number of devices supporting CUDA int deviceCount = 0; error = cuDeviceGetCount(&deviceCount); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al inicializar el CUDA \r\n"); exit(0); } if (deviceCount == 0) { qDebug() << QString("There is no device supporting CUDA.\r\n"); exit(0); } error = cuDeviceGet(&cuDevice, 0); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to get the first device CUDA.\r\n"); exit(0); } // Create context error = cuCtxCreate(&cuContextThread, 0, cuDevice); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al crear contexto CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextThread); cuCtxDestroy(cuContextThread); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParamThreads cuContext=%1 cuDevice=%2 ").arg((uint)cuContextThread).arg((uint)cuDevice); HGLRC myContext1 = wglGetCurrentContext(); qDebug() << QString("VRtogetherWidget::setCudaParamThreads glContext1=%2 cuDevice=%1 ").arg(cuDevice).arg((qlonglong)myContext1); CUcontext cuContextT; cuCtxGetCurrent(&cuContextT); qDebug() << QString("VRtogetherWidget::setCudaParamThreads cuCtxGetCurrent=%1 ").arg((ulong)cuContextT); // CU_FUNC_CACHE_PREFER_NONE CU_FUNC_CACHE_PREFER_SHARED CU_FUNC_CACHE_PREFER_L1 CU_FUNC_CACHE_PREFER_EQUAL error = cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_EQUAL); if (error != CUDA_SUCCESS) { qDebug() << QString("Error to Set Cache Config CUDA %1 error=%2 \r\n").arg(cuDevice).arg(error); error = cuCtxDetach(cuContextThread); cuCtxDestroy(cuContextThread); exit(0); } // D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx #ifdef Q_OS_WIN error = cuModuleLoad(&cuModule, "D:/i2cat_vrtogether/VRtogetherCUDA/vrtg01_cooda.ptx"); #else error = cuModuleLoad(&cuModule, "/home/juanpinto/QT_OpenCL/qt-labs-opencl_matrix3x3/demos/temp/bezierpatch3x3.ptx"); #endif if (error != CUDA_SUCCESS) { qDebug() << QString("Error al leer el archivo PTX error=%1 \r\n").arg(error); error = cuCtxDetach(cuContextThread); cuCtxDestroy(cuContextThread); exit(0); } // _Z7vrtogCUPfPcPif // _Z7vrtogCUPfPcPif error = cuModuleGetFunction(&vrtogCU, cuModule, "_Z7vrtogCUPfPcPif"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); exit(0); } error = cuModuleGetFunction(&vrtogCU01, cuModule, "_Z9vrtogCU01PfPcPifjj"); if (error != CUDA_SUCCESS) { qDebug() << QString("Error al cargar funcion vrtogCU01 error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); exit(0); } //error = cuMemAlloc(&pDevPtr[0], MAX_X * (MAX_Y / 4) * 3 * sizeof(float)); //if (error != CUDA_SUCCESS) { // qDebug() << QString("Error cuMemAlloc pDevPtr[0] error=%1 \r\n").arg(error); // cuCtxDestroy(cuContext); // return; //} /* sizeCU = 100 * sizeof(int); error= cuMemAlloc(&nothingmemCU, sizeCU); if (error != CUDA_SUCCESS){ qDebug() << QString("Error cuMemAlloc nothingmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); exit(0); } //*/ qDebug() << QString("PTX loaded ......................................................... "); #ifdef DEBUGVR sizeCU10 = 10000 * sizeof(int); debugmemCUbytes0 = (int *)malloc(sizeCU10); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU0, sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU0, reinterpret_cast<const void *>(debugmemCUbytes0), sizeCU10); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU11 = 10000 * sizeof(int); debugmemCUbytes1 = (int *)malloc(sizeCU11); memset(debugmemCUbytes0, 0, sizeCU10); error = cuMemAlloc(&debugmemCU1, sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU1, reinterpret_cast<const void *>(debugmemCUbytes1), sizeCU11); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU12 = 10000 * sizeof(int); debugmemCUbytes2 = (int *)malloc(sizeCU12); memset(debugmemCUbytes2, 0, sizeCU12); error = cuMemAlloc(&debugmemCU2, sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCU2, reinterpret_cast<const void *>(debugmemCUbytes2), sizeCU12); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU20 = 10000 * sizeof(float); debugmemFloatCUbytes0 = (float *)malloc(sizeCU20); memset(debugmemFloatCUbytes0, 0, sizeCU20); error = cuMemAlloc(&debugmemFloatCU0, sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU0, reinterpret_cast<const void *>(debugmemFloatCUbytes0), sizeCU20); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU21 = 10000 * sizeof(float); debugmemFloatCUbytes1 = (float *)malloc(sizeCU21); memset(debugmemFloatCUbytes1, 0, sizeCU21); error = cuMemAlloc(&debugmemFloatCU1, sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU1, reinterpret_cast<const void *>(debugmemFloatCUbytes1), sizeCU21); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU22 = 10000 * sizeof(float); debugmemFloatCUbytes2 = (float *)malloc(sizeCU22); memset(debugmemFloatCUbytes2, 0, sizeCU22); error = cuMemAlloc(&debugmemFloatCU2, sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemFloatCU2, reinterpret_cast<const void *>(debugmemFloatCUbytes2), sizeCU22); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemFloatCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU30 = 10000 * sizeof(char); debugmemCharCUbytes0 = (char *)malloc(sizeCU30); memset(debugmemCharCUbytes0, 0, sizeCU30); error = cuMemAlloc(&debugmemCharCU0, sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU0, reinterpret_cast<const void *>(debugmemCharCUbytes0), sizeCU30); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU0 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU31 = 10000 * sizeof(char); debugmemCharCUbytes1 = (char *)malloc(sizeCU31); memset(debugmemCharCUbytes1, 0, sizeCU31); error = cuMemAlloc(&debugmemCharCU1, sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU1, reinterpret_cast<const void *>(debugmemCharCUbytes1), sizeCU31); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU1 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } sizeCU32 = 10000 * sizeof(char); debugmemCharCUbytes2 = (char *)malloc(sizeCU32); memset(debugmemCharCUbytes2, 0, sizeCU32); error = cuMemAlloc(&debugmemCharCU2, sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } error = cuMemcpyHtoD(debugmemCharCU2, reinterpret_cast<const void *>(debugmemCharCUbytes2), sizeCU32); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD debugmemCharCU2 error=%1 \r\n").arg(error); cuCtxDestroy(cuContext); return; } #endif //*/ int n = 0; seedmemCUbytes = (int *)malloc(MAX_X * sizeof(int)); for (int j = 0; j < MAX_X; j++) { seedmemCUbytes[n] = rand(); n++; } error = cuMemAlloc(&seedmemCU, MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemAlloc seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); return; } error = cuMemcpyHtoD(seedmemCU, reinterpret_cast<const void *>(seedmemCUbytes), MAX_X * sizeof(int)); if (error != CUDA_SUCCESS) { qDebug() << QString("Error cuMemcpyHtoD seedmemCU error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); return; } //*/ // Here we must release the CUDA context from the thread context error = cuCtxPopCurrent(NULL); if (CUDA_SUCCESS != error) { qDebug() << QString("cuCtxPopCurrent failed error=%1 \r\n").arg(error); cuCtxDestroy(cuContextThread); exit(0); } qDebug() << QString("VRtogetherWidget::setCudaParamThreads End "); qDebug() << QString("deviceCount=%1 \r\n").arg(deviceCount); } #endif void SafeMain::setVerticesCUDAThreads(uint uThID) { Q_UNUSED(uThID); #ifdef USE_CUDAaaa int n = 0; ulong ulPosStart = 0; ulong ulColStart = 0; bool useCUDA = getUseCUDA(); if (useCUDA == true) { gmr = cuCtxPushCurrent(cuContext); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDAThreads Error cuCtxPushCurrent=%1").arg(gmr); } qDebug() << QString("VRtogetherWidget::setVerticesCUDAThreads ............... incMov=%1 ").arg(incMov); gmr = cuGraphicsMapResources(1, &positionCUDABufferTh[uThID], 0); gmr = cuGraphicsMapResources(1, &posColorCUDABufferTh[uThID], 0); cuGraphicsResourceGetMappedPointer(&pDevPtr[0], &num_bytes[0], positionCUDABufferTh[uThID]); cuGraphicsResourceGetMappedPointer(&pDevPtr[1], &num_bytes[1], posColorCUDABufferTh[uThID]); uint argTestSize; void *argsTest[64]; memset(argsTest, 0, sizeof(argsTest)); argsTest[n] = &pDevPtr[0]; n++; argsTest[n] = &pDevPtr[1]; n++; argsTest[n] = &seedmemCU; n++; argsTest[n] = &incMov; n++; argsTest[n] = &ulPosStart; n++; argsTest[n] = &ulColStart; n++; #ifdef DEBUGVR argsTest[n] = &debugmemCU0; n++; argsTest[n] = &debugmemCU1; n++; argsTest[n] = &debugmemCU2; n++; argsTest[n] = &debugmemFloatCU0; n++; argsTest[n] = &debugmemFloatCU1; n++; argsTest[n] = &debugmemFloatCU2; n++; argsTest[n] = &debugmemCharCU0; n++; argsTest[n] = &debugmemCharCU1; n++; argsTest[n] = &debugmemCharCU2; n++; #endif argTestSize = sizeof(argsTest); // void *config[] = { // CU_LAUNCH_PARAM_BUFFER_POINTER, argsTest, // CU_LAUNCH_PARAM_BUFFER_SIZE, &argTestSize, // CU_LAUNCH_PARAM_END // }; int iValXocl = MAX_X; int iValYocl = MAX_Y / 4; unsigned int blqY = iValYocl / block_size; unsigned int blqX = iValXocl / block_size; if (((int)blqX * block_size) < iValXocl)blqX++; if (((int)blqY * block_size) < iValYocl)blqY++; gmr = cuLaunchKernel(vrtogCU01, blqX, blqY, 1, block_size, block_size, 1, 0, NULL, argsTest, NULL); if (gmr != CUDA_SUCCESS) { qDebug() << QString(" VRtogetherWidget::setVerticesCUDAThreads Error cuLaunchKernel=%1 ID=%2").arg(gmr).arg(iBufferIDTh[uThID]); } cuCtxSynchronize(); cuGraphicsUnmapResources(1, &positionCUDABufferTh[uThID], 0); cuGraphicsUnmapResources(1, &posColorCUDABufferTh[uThID], 0); // theGLMessage.stopCUDA(); #ifdef DEBUGVR // copy result from device to host gmr = cuMemcpyDtoH((int *)debugmemCUbytes0, debugmemCU0, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error10 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes1, debugmemCU1, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error11 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCUbytes2, debugmemCU2, sizeCU10); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error12 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes0, debugmemFloatCU0, sizeCU20); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error20 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes1, debugmemFloatCU1, sizeCU21); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error21 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((float *)debugmemFloatCUbytes2, debugmemFloatCU2, sizeCU22); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error22 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes0, debugmemCharCU0, sizeCU30); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error30 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes1, debugmemCharCU1, sizeCU31); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error31 cuMemcpyDtoH=%1").arg(gmr); } gmr = cuMemcpyDtoH((int *)debugmemCharCUbytes2, debugmemCharCU2, sizeCU32); if (gmr != CUDA_SUCCESS) { qDebug() << QString("setVerticesCUDA Error32 cuMemcpyDtoH=%1").arg(gmr); } #endif cuCtxPopCurrent(NULL); // for (int i = 1024; i < 1024+16; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 ").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]); // } // qDebug("\n"); // for (int i = 0; i < 32; i++) { // qDebug() << QString("i=%1 val=%2 %3 %4 float=%5 %6 %7 char=%8 %9 %10").arg(i) // .arg(debugmemCUbytes0[i]).arg(debugmemCUbytes1[i]).arg(debugmemCUbytes2[i]) // .arg(debugmemFloatCUbytes0[i]).arg(debugmemFloatCUbytes1[i]).arg(debugmemFloatCUbytes2[i]) // .arg((uchar)debugmemCharCUbytes0[i]).arg((uchar)debugmemCharCUbytes1[i]).arg((uchar)debugmemCharCUbytes2[i]); // } // qDebug("\n"); } #endif if (drawed > 12)exit(0); } void SafeMain::allocVerticesCUDAThreads(uint uThID) { #ifdef USE_CUDA IndexType *indices = ViewerVertexBufferTh[uThID]->getIndices(); int iIndex = 0; for (int i = 0; i < MAX_Y / iThreadsNumber; i++) { for (int j = 0; j < MAX_X; j++) { indices[iIndex] = IndexType(iIndex); iIndex++; } } num_elems = iIndex; m_iNumVertices = iIndex; m_iNumVerticesPerThread = m_iNumVertices;// / iThreadsNumber; qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads ............................... m_iNumVertices=%1 m_iNumVerticesPerThread=%2").arg(m_iNumVertices).arg(m_iNumVerticesPerThread); // filePos = 0; // ViewerVertexBufferTh[uThID]->writeIndexBuffer(indices, num_elems, filePos, false); // for(int i=0; i < iThreadsNumber; i++) // { qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads Allocating CUDA Buffers....... uThID=%1 ").arg(uThID); QGLBuffer *vertexBuffer = ViewerVertexBufferTh[uThID]->getVertexBuffer(); QGLBuffer *colorBuffer = ViewerVertexBufferTh[uThID]->getColorBuffer(); if (vertexBuffer->bind()) { if (vertexBuffer->map(QGLBuffer::WriteOnly)) { qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads vertexBuffer allocated ....................................... size=%1 ID=%2").arg(vertexBuffer->size()).arg(vertexBuffer->bufferId()); vertexBuffer->unmap(); vertexBuffer->release(); } } if (colorBuffer->bind()) { if (colorBuffer->map(QGLBuffer::WriteOnly)) { qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads colorBuffer allocated ....................................... size=%1 ID=%2").arg(colorBuffer->size()).arg(colorBuffer->bufferId()); colorBuffer->unmap(); colorBuffer->release(); } } qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads Setting CUDA interoperability ....."); qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads vertexID=%1 colorID=%2 ").arg(vertexBuffer->bufferId()).arg(colorBuffer->bufferId()); cuGraphicsGLRegisterBuffer(&positionCUDABufferTh[uThID], vertexBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); cuGraphicsGLRegisterBuffer(&posColorCUDABufferTh[uThID], colorBuffer->bufferId(), CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD); qDebug() << QString("VRtogetherWidget::allocVerticesCUDAThreads Finished CUDA interoperability setting ....."); // } #endif setAllocated(true); } void SafeMain::freeVerticesCUDAThreads(uint uThID) { Q_UNUSED(uThID) qDebug("Deallocating Memory........................"); #ifdef USE_CUDA qDebug("Freeing CUDA buffers "); cuGraphicsUnregisterResource(positionCUDABuffer); cuGraphicsUnregisterResource(posColorCUDABuffer); cuGraphicsUnregisterResource(indicesCUDABuffer); #endif m_iNumVertices = 0; qDebug("Deallocated Memory........................"); } //****************************************************************************
[ "juan@alestilodepinto.com" ]
juan@alestilodepinto.com
df50e9bf58037695343a33cd0d1609864e3308d6
e7c4e1edff2fd264f66d16f6261bf3ac5c9ce80c
/src/Step1_Models.cpp
377bf75aa6c617e0ecb621e6fb0328efde6a8f8e
[ "MIT", "BSL-1.0" ]
permissive
QinFinnUK/regenie
e5aa7757ee6d86429c370afeebac86bda7c67764
934b7352018d1c4328982845e7d1563c6c9ea737
refs/heads/master
2023-07-13T17:15:54.680946
2021-08-13T13:08:27
2021-08-13T13:08:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
46,015
cpp
/* This file is part of the regenie software package. Copyright (c) 2020-2021 Joelle Mbatchou, Andrey Ziyatdinov & Jonathan Marchini 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 "Regenie.hpp" #include "Files.hpp" #include "Geno.hpp" #include "Joint_Tests.hpp" #include "Step1_Models.hpp" #include "Step2_Models.hpp" #include "HLM.hpp" #include "Pheno.hpp" #include "Masks.hpp" #include "Data.hpp" using namespace std; using namespace Eigen; using namespace boost; void fit_null_logistic(const int& chrom, struct param* params, struct phenodt* pheno_data, struct ests* m_ests, struct in_files* files, mstream& sout) { sout << " -fitting null logistic regression on binary phenotypes..." << flush; auto t1 = std::chrono::high_resolution_clock::now(); ArrayXd betaold, etavec, pivec, loco_offset, wvec; MatrixXd XtW; if(params->w_interaction || params->firth) m_ests->bhat_start.resize(pheno_data->new_cov.cols(), params->n_pheno); for(int i = 0; i < params->n_pheno; ++i ){ MapArXd Y (pheno_data->phenotypes_raw.col(i).data(), pheno_data->phenotypes_raw.rows()); MapArXb mask (pheno_data->masked_indivs.col(i).data(), pheno_data->masked_indivs.rows()); if(params->test_mode) loco_offset = m_ests->blups.col(i).array() * mask.cast<double>(); else loco_offset = ArrayXd::Zero(Y.size(), 1); // starting values pivec = ( 0.5 + Y ) / 2; etavec = mask.select( log(pivec/ (1-pivec)), 0); betaold = ArrayXd::Zero(pheno_data->new_cov.cols()); betaold(0) = etavec.mean() - loco_offset.mean(); if(!fit_logistic(Y, pheno_data->new_cov, loco_offset, mask, pivec, etavec, betaold, params, sout)) throw "logistic regression did not converge for phenotype " + files->pheno_names[i] + ". Perhaps increase --niter?"; else if( (mask && (pivec < params->numtol_eps || pivec > 1 - params->numtol_eps)).any() ) sout << "\n WARNING: Fitted probabilities numerically 0/1 occured (phenotype #" << files->pheno_names[i] <<")."; if(params->test_mode){ m_ests->Y_hat_p.col(i) = pivec.matrix() ; get_wvec(pivec, wvec, mask, params->l1_ridge_eps); m_ests->Gamma_sqrt.col(i) = wvec.sqrt().matrix(); m_ests->X_Gamma[i] = ( pheno_data->new_cov.array().colwise() * (m_ests->Gamma_sqrt.col(i).array() * mask.cast<double>()) ).matrix(); m_ests->Xt_Gamma_X_inv[i] = (m_ests->X_Gamma[i].transpose() * m_ests->X_Gamma[i]).colPivHouseholderQr().inverse(); if(params->w_interaction || params->firth) m_ests->bhat_start.col(i) = betaold.matrix(); } else m_ests->offset_logreg.col(i) = etavec; /* Files fstar; fstar.openForWrite("offsets.txt", sout); fstar << etavec; fstar.closeFile(); */ } sout << "done"; auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); sout << " (" << duration.count() << "ms) "<< endl; } bool fit_logistic(const Ref<const ArrayXd>& Y1, const Ref<const MatrixXd>& X1, const Ref<const ArrayXd>& offset, const Ref<const ArrayXb>& mask, ArrayXd& pivec, ArrayXd& etavec, ArrayXd& betavec, struct param const* params, mstream& sout) { int niter_cur = 0; double dev_old, dev_new=0; ArrayXd score, betanew, wvec_sqrt, wvec, zvec; MatrixXd XtW, XtWX; dev_old = get_logist_dev(Y1, pivec, mask); //cerr << dev_old << endl << pivec.head(5)<<"\n--\n"; while(niter_cur++ < params->niter_max){ // p*(1-p) and check for zeroes if( get_wvec(pivec, wvec, mask, params->numtol_eps) ){ if(params->verbose) sout << "ERROR: Zeros occured in Var(Y) during logistic regression.\n"; return false; } wvec_sqrt = mask.select(wvec.sqrt(), 0); XtW = X1.transpose() * wvec_sqrt.matrix().asDiagonal(); XtWX = XtW * XtW.transpose(); // working vector z = X*beta + (Y-p)/(p*(1-p)) // and multiply by sqrt(p*(1-p)) zvec = wvec_sqrt * mask.select(etavec - offset + (Y1 - pivec) / wvec, 0); // parameter estimate betanew = ( XtWX ).colPivHouseholderQr().solve( XtW * zvec.matrix() ).array(); // start step-halving for( int niter_search = 1; niter_search <= params->niter_max_line_search; niter_search++ ){ get_pvec(etavec, pivec, betanew, offset, X1, params->numtol_eps); dev_new = get_logist_dev(Y1, pivec, mask); /* cerr << "\n\n" << std::boolalpha << ((pivec > 0) && (pivec < 1)).all() << " " << pivec.minCoeff() << "-" << pivec.maxCoeff() << "-> " << betanew.head(3).matrix().transpose() << "--" << dev_new << " #" << niter_cur << "(" << niter_search << ")\n"; */ if( ((pivec > 0) && (pivec < 1)).all() ) break; // adjust step size betanew = (betavec + betanew) / 2; } score = X1.transpose() * mask.select(Y1 - pivec, 0).matrix(); // stopping criterion if( (score.abs().maxCoeff() < params->tol) || (abs(dev_new - dev_old)/(0.1 + abs(dev_new)) < params->tol) ) break; betavec = betanew; dev_old = dev_new; } //sout << "Took "<< niter_cur << " iterations." << endl; // If didn't converge if(niter_cur > params->niter_max) return false; betavec = betanew; //cerr << endl << betavec.matrix().transpose() << "\n\n" << score.matrix().transpose() << "\n\n"; return true; } double get_logist_dev(const Ref<const ArrayXd>& Y, const Ref<const ArrayXd>& pi, const Ref<const ArrayXb>& mask){ double dev = 0; for( int i = 0; i < Y.size(); i++){ if(mask(i)) dev -= (Y(i) == 1) ? log(pi(i)) : log(1-pi(i)); } return 2 * dev; // -2 log.lik } ///////////////////////////////////////////////// ///////////////////////////////////////////////// //// level 0 models ///////////////////////////////////////////////// ///////////////////////////////////////////////// void ridge_level_0(const int& block, struct in_files* files, struct param* params, struct filter* filters, struct ests* m_ests, struct geno_block* Gblock, struct phenodt* pheno_data, vector<snp>& snpinfo, struct ridgel0* l0, struct ridgel1* l1, vector<MatrixXb>& masked_in_folds, mstream& sout) { sout << " -calc level 0 ridge..." << flush; auto t2 = std::chrono::high_resolution_clock::now(); int bs = l0->GGt.rows(); int block_eff = params->write_l0_pred ? 0 : block; string op_name, out_pheno; ofstream ofile; MatrixXd ww1, ww2, beta, pred, vmat, dvec, Xout; MatrixXd ident_l0 = MatrixXd::Identity(bs, bs); MatrixXd p_sum = MatrixXd::Zero(params->n_ridge_l0, params->n_pheno); MatrixXd p_sum2 = MatrixXd::Zero(params->n_ridge_l0, params->n_pheno); if(!params->within_sample_l0 && params->print_block_betas) { for(int ph = 0; ph < params->n_pheno; ++ph ) params->beta_print_out[ph] = MatrixXd::Zero(params->n_ridge_l0, bs); } uint32_t cum_size_folds = 0; for(int i = 0; i < params->cv_folds; ++i ) { // assign masking within folds masked_in_folds[i] = pheno_data->masked_indivs.block(cum_size_folds, 0, params->cv_sizes(i), pheno_data->masked_indivs.cols()); ww1 = l0->GGt - l0->G_folds[i]; SelfAdjointEigenSolver<MatrixXd> eig(ww1); vmat = eig.eigenvectors(); dvec = eig.eigenvalues(); //if(i == 0)sout << ww1 << endl; ww2 = vmat.transpose() * (l0->GTY - l0->GtY[i]); for(int j = 0; j < params->n_ridge_l0; ++j ) { // b = U (D+sI)^(-1) U^t GtY beta = vmat * (dvec.array() + params->lambda[j]).inverse().matrix().asDiagonal() * ww2; // save beta for each phenotype (only when using out-of-sample pred) if(!params->within_sample_l0 && params->print_block_betas) for(int ph = 0; ph < params->n_pheno; ++ph ) params->beta_print_out[ph].row(j) += beta.col(ph).transpose(); // out-of-sample predictions (mask missing) pred = ( (beta.transpose() * Gblock->Gmat.block(0, cum_size_folds, bs, params->cv_sizes(i))).array() * masked_in_folds[i].transpose().array().cast<double>() ).matrix(); p_sum.row(j) += pred.rowwise().sum(); p_sum2.row(j) += pred.rowwise().squaredNorm(); // store predictions for(int ph = 0; ph < params->n_pheno; ++ph ) { l1->test_mat[ph][i].col(block_eff * params->n_ridge_l0 + j) = pred.row(ph).transpose(); l1->test_pheno[ph][i].col(0) = pheno_data->phenotypes.block(cum_size_folds, ph, params->cv_sizes(i), 1); if (params->binary_mode && (block == 0) && (j == 0) ) { l1->test_pheno_raw[ph][i].col(0) = pheno_data->phenotypes_raw.block(cum_size_folds, ph, params->cv_sizes(i), 1); l1->test_offset[ph][i].col(0) = m_ests->offset_logreg.block(cum_size_folds, ph, params->cv_sizes(i), 1); } } } cum_size_folds += params->cv_sizes(i); } // center and scale using the whole sample for(int ph = 0; ph < params->n_pheno; ++ph ) { RowVectorXd p_mean, p_invsd; p_mean = p_sum.col(ph).transpose() / pheno_data->Neff(ph); p_invsd = sqrt( (pheno_data->Neff(ph) - 1) / (p_sum2.col(ph).transpose().array() - pheno_data->Neff(ph) * p_mean.array().square()) ); // scale printed estimates by the sd if(params->print_block_betas) params->beta_print_out[ph].array().colwise() *= p_invsd.transpose().array(); if(params->write_l0_pred) Xout = MatrixXd::Zero(params->n_samples, params->n_ridge_l0); cum_size_folds = 0; for(int i = 0; i < params->cv_folds; ++i ) { l1->test_mat[ph][i].block(0, block_eff * params->n_ridge_l0, params->cv_sizes(i), params->n_ridge_l0).rowwise() -= p_mean; l1->test_mat[ph][i].block(0, block_eff * params->n_ridge_l0, params->cv_sizes(i), params->n_ridge_l0).array().rowwise() *= p_invsd.array(); if(params->write_l0_pred) { Xout.block(cum_size_folds, 0, params->cv_sizes(i), params->n_ridge_l0) = l1->test_mat[ph][i].block(0, block_eff * params->n_ridge_l0, params->cv_sizes(i), params->n_ridge_l0); cum_size_folds += params->cv_sizes(i); } } // write predictions to file if specified if(params->write_l0_pred) { write_l0_file(files->write_preds_files[ph].get(), Xout, sout); //if(block ==0 && ph == 0 ) sout << endl << "Out " << endl << Xout.block(0, 0, 3, 3) << endl; } } // if printing betas to file (average over folds) [assume snp IDs are unique] // -> separate file for each block (params->n_ridge_l0 rows & (2+bs) columns) if(!params->within_sample_l0 && params->print_block_betas) { op_name = files->out_file + "_block" + to_string(block+1) + ".betas"; openStream(&ofile, op_name, std::ios::out, sout); // Header: [TRAIT PARAM snpID1 ... snpIDk] ofile << "TRAIT PARAM " ; for(int i = 0; i < bs; ++i ) ofile << snpinfo[params->print_snpcount++].ID << " "; ofile << endl; // Each line: [pheno# ridge# beta1 ... betak] for(int ph = 0; ph < params->n_pheno; ++ph ){ params->beta_print_out[ph] /= params->cv_folds; for(int j = 0; j < params->n_ridge_l0; ++j ) { ofile << ph + 1 << " " << j + 1 << " "; for(int i = 0; i < bs; ++i ) ofile << params->beta_print_out[ph](j,i) << " "; ofile << endl; } } ofile.close(); } sout << "done"; auto t3 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2); sout << " (" << duration.count() << "ms) "<< endl; } void ridge_level_0_loocv(const int block, struct in_files* files, struct param* params, struct filter* filters, struct ests* m_ests, struct geno_block* Gblock, struct phenodt* pheno_data, vector<snp>& snpinfo, struct ridgel0* l0, struct ridgel1* l1, mstream& sout) { sout << " -calc level 0 ridge..." << flush; auto t2 = std::chrono::high_resolution_clock::now(); int bs = l0->GGt.rows(); int block_eff = params->write_l0_pred ? 0 : block; // if writing to file string out_pheno; ofstream ofile; VectorXd z1, gvec; MatrixXd VtG, z2, pred, Xout; RowVectorXd p_mean, p_sd; /* if(bs > params->n_samples) throw "block size must be smaller than the number of samples to perform LOOCV!"; */ // make matrix of (eigen-value + lambda)^(-1) Map<RowVectorXd> Lmap(params->lambda.data(), params->n_ridge_l0); MatrixXd dl = l0->GGt_eig_val.asDiagonal() * MatrixXd::Ones(bs, params->n_ridge_l0); dl.rowwise() += Lmap; MatrixXd DL_inv = dl.array().inverse().matrix(); uint64 max_bytes = params->chunk_mb * 1e6; // amount of RAM used < max_mb [ creating (bs * target_size) matrix ] int nchunk = ceil( params->cv_folds * bs * sizeof(double) * 1.0 / max_bytes ); if (params->verbose) sout << nchunk << " chunks..." << flush; int chunk, size_chunk, target_size = params->cv_folds / nchunk; int j_start; for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = chunk == nchunk - 1? params->cv_folds - target_size * chunk : target_size; j_start = chunk * target_size; VtG = l0->GGt_eig_vec.transpose() * Gblock->Gmat.block(0, j_start, bs, size_chunk); for(int i = 0; i < size_chunk; ++i ) { z1 = VtG.col(i); z2 = DL_inv.array().colwise() * z1.array(); gvec = z2.transpose() * z1; pred = z2.transpose() * l0->Wmat - gvec * pheno_data->phenotypes.row(j_start + i); pred.array().colwise() /= 1 - gvec.array(); for(int ph = 0; ph < params->n_pheno; ++ph ) l1->test_mat_conc[ph].block(j_start + i, block_eff * params->n_ridge_l0, 1, params->n_ridge_l0) = pred.col(ph).transpose(); } } // center and scale within the block for(int ph = 0; ph < params->n_pheno; ++ph ) { // mask missing first l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).array().colwise() *= pheno_data->masked_indivs.col(ph).array().cast<double>(); p_mean = l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).colwise().sum() / pheno_data->Neff(ph); //if(i == 0)sout << i << " " << p_mean << endl; l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).rowwise() -= p_mean; // mask missing again l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).array().colwise() *= pheno_data->masked_indivs.col(ph).array().cast<double>(); p_sd = l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).colwise().norm() / sqrt(pheno_data->Neff(ph) -1); //if(i == 0)sout << i << " " << p_sd << endl; l1->test_mat_conc[ph].block(0, block_eff * params->n_ridge_l0, params->n_samples, params->n_ridge_l0).array().rowwise() /= p_sd.array(); if(params->write_l0_pred) { Xout = l1->test_mat_conc[ph].block(0, 0, params->n_samples, params->n_ridge_l0); write_l0_file(files->write_preds_files[ph].get(), Xout, sout); //if(block < 2 && ph == 0 ) sout << endl << "Out " << endl << Xout.block(0, 0, 5, Xout.cols()) << endl; } } sout << "done"; auto t3 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2); sout << " (" << duration.count() << "ms) "<< endl; } void write_l0_file(ofstream* ofs, MatrixXd& Xout, mstream& sout){ ofs->write( reinterpret_cast<char *> (&Xout(0,0)), Xout.size() * sizeof(double) ); if( ofs->fail() ) throw "cannot successfully write temporary level 0 predictions to disk"; } ///////////////////////////////////////////////// ///////////////////////////////////////////////// //// level 1 models ///////////////////////////////////////////////// ///////////////////////////////////////////////// void set_mem_l1(struct in_files* files, struct param* params, struct filter* filters, struct ests* m_ests, struct geno_block* Gblock, struct phenodt* pheno_data, struct ridgel1* l1, vector<MatrixXb>& masked_in_folds, mstream& sout){ // when l0 was run in parallel // store pheno info for l1 if(!params->use_loocv) { uint32_t low = 0, high = 0; uint32_t i_total = 0, cum_size_folds = 0; for(int i = 0; i < params->cv_folds; ++i ) { // assign masking within folds for(int j = 0; j < params->cv_sizes(i); ++j) { masked_in_folds[i].row(j) = pheno_data->masked_indivs.row(i_total); i_total++; } // set lower and upper index bounds for fold if(i>0) low += params->cv_sizes(i-1); high += params->cv_sizes(i); // store predictions uint32_t jj = 0; for(size_t k = 0; k < params->n_samples; ++k ) { if( (k >= low) && (k < high) ) { for(int ph = 0; ph < params->n_pheno; ++ph ) { l1->test_pheno[ph][i](jj, 0) = pheno_data->phenotypes(k, ph); if (params->binary_mode) { l1->test_pheno_raw[ph][i](jj, 0) = pheno_data->phenotypes_raw(k, ph); l1->test_offset[ph][i](jj, 0) = m_ests->offset_logreg(k, ph); } } jj++; } } cum_size_folds += params->cv_sizes(i); } } } void ridge_level_1(struct in_files* files, struct param* params, struct ridgel1* l1, mstream& sout) { sout << endl << " Level 1 ridge..." << endl << flush; int bs_l1 = params->total_n_block * params->n_ridge_l0; int ph_eff; string in_pheno; ifstream infile; MatrixXd X1, X2, beta_l1, p1, vmat, dvec, dl_inv; VectorXd VtX2; MatrixXd XtX_sum, XtY_sum; MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); Map<RowVectorXd> Lmap(params->tau.data(), params->n_ridge_l1); // to compute Rsq and MSE of predictions for (int i = 0; i < 5; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 <<" (" << files->pheno_names[ph] << ")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory if(ph == 0) { for( int i = 0; i < params->cv_folds; ++i ) l1->test_mat[ph_eff][i] = MatrixXd::Zero(params->cv_sizes(i), bs_l1); } read_l0(ph, ph_eff, files, params, l1, sout); //if(ph == 0) sout << endl << "In:\n" << l1->test_mat[ph_eff][0].block(0,0,5,6) << endl; } // compute XtX and Xty for each fold and cum. sum using test_mat's if (!params->within_sample_l0){ XtX_sum.setZero(bs_l1, bs_l1); XtY_sum.setZero(bs_l1, 1); for( int i = 0; i < params->cv_folds; ++i ) { l1->X_folds[i] = l1->test_mat[ph_eff][i].transpose() * l1->test_mat[ph_eff][i]; l1->XtY[i] = l1->test_mat[ph_eff][i].transpose() * l1->test_pheno[ph][i]; XtX_sum += l1->X_folds[i]; XtY_sum += l1->XtY[i]; } } for(int i = 0; i < params->cv_folds; ++i ) { // use either in-sample or out-of-sample predictions if (params->within_sample_l0) { X1 = l1->pred_mat[ph][i].transpose() * l1->pred_mat[ph][i]; X2 = l1->pred_mat[ph][i].transpose() * l1->pred_pheno[ph][i]; } else{ X1 = XtX_sum - l1->X_folds[i]; X2 = XtY_sum - l1->XtY[i]; } SelfAdjointEigenSolver<MatrixXd> eigX1(X1); vmat = eigX1.eigenvectors(); dvec = eigX1.eigenvalues(); VtX2 = vmat.transpose() * X2; // compute solutions for all ridge parameters at once // p1 is Nfold x nridge_l1 matrix dl_inv = ( (dvec.asDiagonal() * MatrixXd::Ones(bs_l1, params->n_ridge_l1)).rowwise() + Lmap).array().inverse().matrix(); dl_inv.array().colwise() *= VtX2.array(); beta_l1 = vmat * dl_inv; if(!params->within_sample_l0) l1->beta_hat_level_1[ph][i] = beta_l1; p1 = l1->test_mat[ph_eff][i] * beta_l1; l1->cumsum_values[0].row(ph) += p1.colwise().sum(); l1->cumsum_values[1].row(ph).array() += l1->test_pheno[ph][i].array().sum(); l1->cumsum_values[2].row(ph) += p1.array().square().matrix().colwise().sum(); l1->cumsum_values[3].row(ph).array() += l1->test_pheno[ph][i].array().square().sum(); l1->cumsum_values[4].row(ph) += (p1.array().colwise() * l1->test_pheno[ph][i].col(0).array()).matrix().colwise().sum() ; } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } sout << endl; } void ridge_level_1_loocv(struct in_files* files, struct param* params, struct phenodt* pheno_data, struct ridgel1* l1, mstream& sout) { sout << endl << " Level 1 ridge..." << flush; int bs_l1 = params->total_n_block * params->n_ridge_l0; int ph_eff; string in_pheno; ifstream infile; MatrixXd Xmat_chunk, Yvec_chunk, Z1, Z2, dl, dl_inv, xtx; VectorXd wvec, zvec; RowVectorXd calFactor, pred; for (int i = 0; i < 5; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); // make matrix of (eigen-values + tau)^(-1) Map<RowVectorXd> Lmap(params->tau.data(), params->n_ridge_l1); uint64 max_bytes = params->chunk_mb * 1e6; // amount of RAM used < max_mb [ creating (target_size * bs_l1) matrix ] int nchunk = ceil( params->cv_folds * bs_l1 * sizeof(double) * 1.0 / max_bytes ); if (params->verbose) sout << nchunk << " chunks..."; sout << endl; int chunk, size_chunk, target_size = params->cv_folds / nchunk; int j_start; for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 <<" (" << files->pheno_names[ph] <<")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory (re-use same matrix for all traits) if(ph == 0) l1->test_mat_conc[ph_eff] = MatrixXd::Zero(params->n_samples, bs_l1); read_l0(ph, ph_eff, files, params, l1, sout); } xtx = l1->test_mat_conc[ph_eff].transpose() * l1->test_mat_conc[ph_eff]; SelfAdjointEigenSolver<MatrixXd> eigX(xtx); dl = eigX.eigenvalues().asDiagonal() * MatrixXd::Ones(bs_l1, params->n_ridge_l1); dl.rowwise() += Lmap; dl_inv = dl.array().inverse().matrix(); zvec = l1->test_mat_conc[ph_eff].transpose() * pheno_data->phenotypes.col(ph); wvec = eigX.eigenvectors().transpose() * zvec; for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = chunk == nchunk - 1? params->cv_folds - target_size * chunk : target_size; j_start = chunk * target_size; Xmat_chunk = l1->test_mat_conc[ph_eff].block(j_start, 0, size_chunk, bs_l1); Yvec_chunk = pheno_data->phenotypes.block(j_start, ph, size_chunk, 1); Z1 = (Xmat_chunk * eigX.eigenvectors()).transpose(); for(int i = 0; i < size_chunk; ++i ) { Z2 = (dl_inv.array().colwise() * Z1.col(i).array()).matrix(); calFactor = Z1.col(i).transpose() * Z2; pred = wvec.transpose() * Z2; pred -= Yvec_chunk(i, 0) * calFactor; pred.array() /= 1 - calFactor.array(); //if( ph == 0) sout << pred.head(5) << endl; // compute mse and rsq l1->cumsum_values[0].row(ph) += pred; // Sx // Y is centered so Sy = 0 l1->cumsum_values[2].row(ph) += pred.array().square().matrix(); // Sx2 // Y is scaled so Sy2 = params->n_samples - ncov l1->cumsum_values[4].row(ph).array() += pred.array() * Yvec_chunk(i,0); // Sxy } } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } l1->cumsum_values[3].array().colwise() += pheno_data->Neff - params->ncov; // Sy2 sout << endl; } // Logistic models void ridge_logistic_level_1(struct in_files* files, struct param* params, struct phenodt* pheno_data, struct ridgel1* l1, vector<MatrixXb>& masked_in_folds, mstream& sout) { sout << endl << " Level 1 ridge with logistic regression..." << endl << flush; int niter_cur; int bs_l1 = params->total_n_block * params->n_ridge_l0; int ph_eff; string in_pheno; ifstream infile; ArrayXd Y1, W1, p1, score; ArrayXd betaold, etavec, pivec, wvec, zvec, betanew, etatest; MatrixXd X1, XtW, XtWX, XtWZ; l1->pheno_l1_not_converged = ArrayXb::Constant(params->n_pheno, false); MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); for (int i = 0; i < 6; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 <<" (" << files->pheno_names[ph] <<")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory if(ph == 0) { for( int i = 0; i < params->cv_folds; ++i ) l1->test_mat[ph_eff][i] = MatrixXd::Zero(params->cv_sizes(i), bs_l1); } read_l0(ph, ph_eff, files, params, l1, sout); } for(int i = 0; i < params->cv_folds; ++i ) { if( l1->pheno_l1_not_converged(ph) ) break; if( params->within_sample_l0 ){ X1 = l1->pred_mat[ph][i]; Y1 = l1->pred_pheno_raw[ph][i]; W1 = l1->pred_offset[ph][i]; } // starting values for each trait betaold = betanew = ArrayXd::Zero(bs_l1); for(int j = 0; j < params->n_ridge_l1; ++j ) { if( l1->pheno_l1_not_converged(ph) ) break; niter_cur = 0; // use warm starts (i.e. set final beta of previous ridge param // as initial beta for current ridge param) betaold = betanew; while(niter_cur++ < params->niter_max_ridge){ if(params->within_sample_l0) { etavec = W1 + (X1 * betaold.matrix()).array(); pivec = 1 - 1/(etavec.exp() + 1); wvec = pivec * (1 - pivec); // check none of the values are 0 if( ( wvec == 0 ).count() > 0 ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression! (Try with --loocv)" << endl; l1->pheno_l1_not_converged(ph) = true; break; } zvec = (etavec - W1) + (Y1 - pivec) / wvec; XtW = X1.transpose() * wvec.matrix().asDiagonal(); betanew = (XtW * X1 + params->tau[j] * ident_l1).colPivHouseholderQr().solve(XtW * zvec.matrix()).array(); // get the score etavec = W1 + (X1 * betanew.matrix()).array(); pivec = 1 - 1/(etavec.exp() + 1); score = (X1.transpose() * (Y1 - pivec).matrix()).array() - params->tau[j] * betanew; } else { XtWX = MatrixXd::Zero(bs_l1, bs_l1); XtWZ = MatrixXd::Zero(bs_l1, 1); for(int k = 0; k < params->cv_folds; ++k ) { if( k != i) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betaold, l1->test_offset[ph][k].array(), l1->test_mat[ph_eff][k], params->numtol_eps); if( get_wvec(pivec, wvec, masked_in_folds[k].col(ph).array(), params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression! (Try with --loocv)" << endl; l1->pheno_l1_not_converged(ph) = true; break; } zvec = (masked_in_folds[k].col(ph).array()).select((etavec - l1->test_offset[ph][k].array()) + (l1->test_pheno_raw[ph][k].array() - pivec) / wvec, 0); XtW = l1->test_mat[ph_eff][k].transpose() * wvec.matrix().asDiagonal(); XtWX += XtW * l1->test_mat[ph_eff][k]; XtWZ += XtW * zvec.matrix(); } } if( l1->pheno_l1_not_converged(ph) ) break; betanew = ((XtWX + params->tau[j] * ident_l1).llt().solve(XtWZ)).array(); // start step-halving for( int niter_search = 1; niter_search <= params->niter_max_line_search_ridge; niter_search++ ){ bool invalid_wvec = false; for(int k = 0; k < params->cv_folds; ++k ) { if( k != i) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betanew, l1->test_offset[ph][k].array(), l1->test_mat[ph_eff][k], params->numtol_eps); invalid_wvec = get_wvec(pivec, wvec, masked_in_folds[k].col(ph).array(), params->l1_ridge_eps); if( invalid_wvec ) break; // do another halving } } if( !invalid_wvec ) break; // halve step size betanew = (betaold + betanew) / 2; } // compute score score = ArrayXd::Zero(bs_l1); for(int k = 0; k < params->cv_folds; ++k ) { if( k != i) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betanew, l1->test_offset[ph][k].array(), l1->test_mat[ph_eff][k], params->numtol_eps); if( get_wvec(pivec, wvec, masked_in_folds[k].col(ph).array(), params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression! (Try with --loocv)" << endl; l1->pheno_l1_not_converged(ph) = true; break; } score += (l1->test_mat[ph_eff][k].transpose() * masked_in_folds[k].col(ph).array().select(l1->test_pheno_raw[ph][k].array() - pivec, 0).matrix()).array(); } } score -= params->tau[j] * betanew; } // stopping criterion if( (score.abs().maxCoeff() < params->l1_ridge_tol) || l1->pheno_l1_not_converged(ph)) break; betaold = betanew; } //cerr << "\nFold=" << i << " tau = " << params->tau[j] << " beta=" << betanew.matrix().transpose().array() << endl; //if(i==1) exit(EXIT_FAILURE); if(niter_cur > params->niter_max_ridge){ sout << "WARNING: Penalized logistic regression did not converge! (Increase --niter)\n"; l1->pheno_l1_not_converged(ph) = true; break; } else if(l1->pheno_l1_not_converged(ph)) break; //sout << "Converged in "<< niter_cur << " iterations. Score max = " << score.abs().maxCoeff() << endl; etatest = l1->test_offset[ph][i].array() + (l1->test_mat[ph_eff][i] * betanew.matrix()).array(); p1 = (1 - 1/(etatest.exp() + 1)); if(!params->within_sample_l0) l1->beta_hat_level_1[ph][i].col(j) = betanew; // compute mse for(int l = 0; l < params->cv_sizes(i); l++){ if(!masked_in_folds[i](l,ph)) continue; // if p is within eps of 0/1, set to eps/1-eps if( p1(l) < params->l1_ridge_eps ) p1(l) = params->l1_ridge_eps; else if( p1(l) > (1-params->l1_ridge_eps) ) p1(l) = 1 - params->l1_ridge_eps; l1->cumsum_values[0](ph,j) += p1(l); // Sx l1->cumsum_values[1](ph,j) += l1->test_pheno_raw[ph][i](l,0); // Sy l1->cumsum_values[2](ph,j) += p1(l) * p1(l); // Sx2 l1->cumsum_values[3](ph,j) += l1->test_pheno_raw[ph][i](l,0) * l1->test_pheno_raw[ph][i](l,0); // Sy2 l1->cumsum_values[4](ph,j) += p1(l) * l1->test_pheno_raw[ph][i](l,0); // Sxy l1->cumsum_values[5](ph,j) += compute_log_lik(l1->test_pheno_raw[ph][i](l,0), p1(l)); // LL } } } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } sout << endl; } void ridge_logistic_level_1_loocv(struct in_files* files, struct param* params, struct phenodt* pheno_data, struct ests* m_ests, struct ridgel1* l1, mstream& sout) { sout << endl << " Level 1 ridge with logistic regression..." << flush; int ph_eff, bs_l1 = params->total_n_block * params->n_ridge_l0; double v2, pred, p1; string in_pheno; ifstream infile; ArrayXd beta, pivec, wvec; MatrixXd XtWX, V1, b_loo; LLT<MatrixXd> Hinv; l1->pheno_l1_not_converged = ArrayXb::Constant(params->n_pheno, false); MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); for (int i = 0; i < 6; i++) l1->cumsum_values[i].setZero(params->n_pheno, params->n_ridge_l1); uint64 max_bytes = params->chunk_mb * 1e6; // amount of RAM used < max_mb [ creating (bs_l1 * target_size) matrix ] int nchunk = ceil( params->cv_folds * bs_l1 * sizeof(double) * 1.0 / max_bytes ); int j_start, chunk, size_chunk, target_size = params->cv_folds / nchunk; sout << (params->verbose ? to_string(nchunk) + " chunks..." : "" ) << endl; for(int ph = 0; ph < params->n_pheno; ++ph ) { sout << " -on phenotype " << ph+1 << " (" << files->pheno_names[ph] <<")..." << flush; auto ts1 = std::chrono::high_resolution_clock::now(); ph_eff = params->write_l0_pred ? 0 : ph; // read in level 0 predictions from file if(params->write_l0_pred){ // allocate memory (re-use same matrix for all traits) if(ph == 0) l1->test_mat_conc[ph_eff] = MatrixXd::Zero(params->n_samples, bs_l1); read_l0(ph, ph_eff, files, params, l1, sout); } MapArXd Y (pheno_data->phenotypes_raw.col(ph).data(), pheno_data->phenotypes_raw.rows()); MapMatXd X (l1->test_mat_conc[ph_eff].data(), pheno_data->phenotypes_raw.rows(), bs_l1); MapArXd offset (m_ests->offset_logreg.col(ph).data(), pheno_data->phenotypes_raw.rows()); MapArXb mask (pheno_data->masked_indivs.col(ph).data(), pheno_data->masked_indivs.rows()); // starting values for each trait beta = ArrayXd::Zero(bs_l1); for(int j = 0; j < params->n_ridge_l1; ++j ) { // using warm starts (i.e. set final beta of previous ridge param // as initial beta for current ridge param) if( params->use_adam ) // run ADAM to get close to max run_log_ridge_loocv_adam(ph, params->tau[j], beta, pivec, wvec, Y, X, offset, mask, params, sout); if(!run_log_ridge_loocv(params->tau[j], target_size, nchunk, beta, pivec, wvec, Y, X, offset, mask, params, sout)){ sout << "WARNING: Ridge logistic regression did not converge! (Increase --niter)\n"; l1->pheno_l1_not_converged(ph) = true; break; } // compute Hinv // zvec = (pheno_data->masked_indivs.col(ph).array()).select( (etavec - m_ests->offset_logreg.col(ph).array()) + (pheno_data->phenotypes_raw.col(ph).array() - pivec) / wvec, 0); XtWX = MatrixXd::Zero(bs_l1, bs_l1); for(chunk = 0; chunk < nchunk; ++chunk){ size_chunk = ( chunk == nchunk - 1 ? params->cv_folds - target_size * chunk : target_size ); j_start = chunk * target_size; Ref<MatrixXd> Xmat_chunk = X.block(j_start, 0, size_chunk, bs_l1); // n x k Ref<MatrixXd> w_chunk = wvec.matrix().block(j_start, 0, size_chunk,1); XtWX += Xmat_chunk.transpose() * w_chunk.asDiagonal() * Xmat_chunk; } Hinv.compute( XtWX + params->tau[j] * ident_l1 ); // LOOCV estimates for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = ( chunk == nchunk - 1 ? params->cv_folds - target_size * chunk : target_size ); j_start = chunk * target_size; Ref<MatrixXd> Xmat_chunk = X.block(j_start, 0, size_chunk, bs_l1); // n x k Ref<MatrixXd> Yvec_chunk = Y.matrix().block(j_start, 0, size_chunk, 1); Ref<MatrixXb> mask_chunk = mask.matrix().block(j_start, 0, size_chunk,1); V1 = Hinv.solve( Xmat_chunk.transpose() ); // k x n for(int i = 0; i < size_chunk; ++i ) { if(!mask_chunk(i,0)) continue; v2 = Xmat_chunk.row(i) * V1.col(i); v2 *= wvec(j_start + i); b_loo = (beta - V1.col(i).array() * (Yvec_chunk(i,0) - pivec(j_start + i)) / (1 - v2)).matrix(); pred = Xmat_chunk.row(i) * b_loo.col(0); pred += offset(j_start + i); p1 = 1 - 1/ ( exp(pred) + 1 ); // if p is within eps of 0/1, set to eps/1-eps if( p1 < params->l1_ridge_eps ) p1 = params->l1_ridge_eps; else if( p1 > (1-params->l1_ridge_eps) ) p1 = 1 - params->l1_ridge_eps; // compute mse and rsq l1->cumsum_values[0](ph,j) += p1; // Sx l1->cumsum_values[1](ph,j) += Yvec_chunk(i,0); // Sy l1->cumsum_values[2](ph,j) += p1 * p1; // Sx2 l1->cumsum_values[3](ph,j) += Yvec_chunk(i,0) * Yvec_chunk(i,0); // Sy2 l1->cumsum_values[4](ph,j) += p1 * Yvec_chunk(i,0); // Sxy l1->cumsum_values[5](ph,j) += compute_log_lik(Yvec_chunk(i,0), p1); // Sxy } } } sout << "done"; auto ts2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(ts2 - ts1); sout << " (" << duration.count() << "ms) "<< endl; } sout << endl; } bool run_log_ridge_loocv(const double& lambda, const int& target_size, const int& nchunk, ArrayXd& betaold, ArrayXd& pivec, ArrayXd& wvec, const Ref<const ArrayXd>& Y, Ref<MatrixXd> X, const Ref<const ArrayXd>& offset, const Ref<const ArrayXb>& mask, struct param* params, mstream& sout) { int bs_l1 = params->total_n_block * params->n_ridge_l0; int niter_cur = 0, j_start, chunk, size_chunk; ArrayXd etavec, zvec, betanew, score; MatrixXd XtWX, XtWZ, V1; LLT<MatrixXd> Hinv; MatrixXd ident_l1 = MatrixXd::Identity(bs_l1,bs_l1); while(niter_cur++ < params->niter_max_ridge) { // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betaold, offset, X, params->numtol_eps); if( get_wvec(pivec, wvec, mask, params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression.\n"; return false; } zvec = mask.select( (etavec - offset) + (Y - pivec) / wvec, 0); // compute XtWX and XtWZ in chunks XtWX = MatrixXd::Zero(bs_l1, bs_l1); XtWZ = MatrixXd::Zero(bs_l1, 1); for(chunk = 0; chunk < nchunk; ++chunk ) { size_chunk = ( chunk == nchunk - 1 ? params->cv_folds - target_size * chunk : target_size ); j_start = chunk * target_size; Ref<MatrixXd> Xmat_chunk = X.block(j_start, 0, size_chunk, bs_l1); // n x k Ref<MatrixXd> w_chunk = wvec.matrix().block(j_start, 0, size_chunk,1); Ref<MatrixXd> z_chunk = zvec.matrix().block(j_start, 0, size_chunk,1); V1 = Xmat_chunk.transpose() * w_chunk.asDiagonal(); XtWX += V1 * Xmat_chunk; XtWZ += V1 * z_chunk; } Hinv.compute( XtWX + lambda * ident_l1 ); betanew = Hinv.solve(XtWZ).array(); // get w=p*(1-p) and check none of the values are 0 get_pvec(etavec, pivec, betanew, offset, X, params->numtol_eps); if( get_wvec(pivec, wvec, mask, params->l1_ridge_eps) ){ sout << "ERROR: Zeros occured in Var(Y) during ridge logistic regression.\n"; return false; } // get the score score = ( X.transpose() * mask.select(Y - pivec, 0).matrix()).array() ; score -= lambda * betanew; if( score.abs().maxCoeff() < params->l1_ridge_tol ) break; betaold = betanew; } if(niter_cur > params->niter_max_ridge) return false; //sout << "Converged in "<< niter_cur << " iterations. Score max = " << score.abs().maxCoeff() << endl; betaold = betanew; return true; } // Ridge logistic with ADAM using mini batch void run_log_ridge_loocv_adam(const int& ph, const double& lambda, ArrayXd& betavec, ArrayXd& pivec, ArrayXd& wvec, const Ref<const ArrayXd>& Y, Ref<MatrixXd> X, const Ref<const ArrayXd>& offset, const Ref<const ArrayXb>& mask, struct param* params, mstream& sout) { int niter_cur = 0, index; double p_alpha = params->adam_alpha, p_beta1 = params->adam_beta1, p_beta2 = params->adam_beta2, p_eps = params->adam_eps, p_alpha_t; double eta, phat; //cerr << p_alpha << " " << p_beta1 << " " << p_beta2 << " " << p_eps << endl; std::uniform_int_distribution<> d(0, mask.count() - 1); std::mt19937 gen; ArrayXd etavec, gradient_f, mt, vt, step_size; // starting values for ADAM params mt = vt = betavec * 0; gradient_f.resize( betavec.size() ); while(niter_cur++ < params->niter_max_ridge_adam) { gradient_f = lambda * betavec; if(params->adam_mini){ // ADAM using mini-batch for (int i = 0; i < params->adam_batch_size; i++){ index = params->adam_indices[ph](d(gen)); eta = offset(index) + X.row(index) * betavec.matrix(); phat = 1 - 1/(exp(eta) + 1); gradient_f -= X.row(index).transpose().array() * (Y(index)-phat); } gradient_f /= params->adam_batch_size; } else { get_pvec(etavec, pivec, betavec, offset, X, params->numtol_eps); gradient_f -= ( X.transpose() * mask.select(Y - pivec, 0).matrix()).array() ; } //if(niter_cur%100 == 1) sout << "At iteration #"<< niter_cur << "; score max = " << gradient_f.abs().maxCoeff() << endl; mt = p_beta1 * mt + (1 - p_beta1) * gradient_f; vt = p_beta2 * vt + (1 - p_beta2) * gradient_f.square(); p_alpha_t = p_alpha * sqrt(1 - pow(p_beta2, niter_cur)) / (1 - pow(p_beta1, niter_cur)); step_size = p_alpha_t * mt / (vt.sqrt() + p_eps); if( step_size.abs().maxCoeff() < params->numtol ) break; betavec -= step_size; } if(params->verbose) sout << "ADAM took "<< niter_cur << " iterations (score max = " << gradient_f.abs().maxCoeff() << ")..."; } bool get_wvec(ArrayXd& pivec, ArrayXd& wvec, const Ref<const ArrayXb>& mask, const double& tol){ wvec = ArrayXd::Ones( mask.size() );// set all entries to 1 // avoid 0 weights by setting w to eps when p is within eps of 0/1 // (strategy used in glmnet) for (int i = 0; i < mask.size(); i++){ if( !mask(i) ) continue; if( pivec(i) < tol) { pivec(i) = 0; wvec(i) = tol; } else if ( pivec(i) > (1-tol) ){ pivec(i) = 1; wvec(i) = tol; } else wvec(i) = pivec(i) * (1-pivec(i)); } //wvec = masks.col(ph).array().select(pivec * (1 - pivec), 1); return (wvec == 0).any(); } void get_pvec(ArrayXd& etavec, ArrayXd& pivec, const Ref<const ArrayXd>& beta, const Ref<const ArrayXd>& offset, const Ref<const MatrixXd>& Xmat, double const& eps){ etavec = offset + (Xmat * beta.matrix()).array(); pivec.resize(etavec.size(),1); // strategy used in glm for (int i = 0; i < pivec.size(); i++){ if(etavec(i) > ETAMAXTHR) pivec(i) = 1 / (1 + eps); else if(etavec(i) < ETAMINTHR) pivec(i) = eps / (1 + eps); else pivec(i) = 1 - 1/(exp(etavec(i)) + 1); } } double compute_log_lik(const double& y, const double& p){ // negative log likelihood for bernoulli double ll; ll = - y * log(p) - (1 - y) * log(1-p); return(ll); } void read_l0(int const& ph, int const& ph_eff, struct in_files* files, struct param* params, struct ridgel1* l1, mstream& sout){ int start, np; string fin; // all blocks in same file if(!params->run_l1_only){ start = 0; np = params->total_n_block * params->n_ridge_l0; fin = files->loco_tmp_prefix; read_l0_chunk(ph, ph_eff, start, np, fin, params, l1, sout); } else { // blocks in separate file for(size_t i = 0; i < files->bstart.size(); i++){ start = files->bstart[i] * params->n_ridge_l0; np = files->btot[i] * params->n_ridge_l0; fin = files->mprefix[i]; read_l0_chunk(ph, ph_eff, start, np, fin, params, l1, sout); } } } // read in l0 predictors in columns [start,start+np) void read_l0_chunk(int const& ph, int const& ph_eff, int const& start, int const& np, const string& prefix, struct param* params, struct ridgel1* l1, mstream& sout){ string in_pheno = prefix + "_l0_Y" + to_string(ph+1); ifstream infile; openStream(&infile, in_pheno, ios::in | ios::binary, sout); if( getSize(in_pheno) != (sizeof(double) * params->n_samples * np )) throw "file " + in_pheno + " is not the right size." ; //cerr << in_pheno << " " << getSize(in_pheno) << endl; // store back values in test_mat if(params->use_loocv) { infile.read( reinterpret_cast<char *> (&l1->test_mat_conc[ph_eff](0, start)), params->n_samples * np * sizeof(double) ); //if(ph == 0) sout << endl << "In:\n" << l1->test_mat_conc[ph_eff].block(0,0,5,6) << endl; } else { int nt = 0; for( int m = start; nt < np; nt++, m++ ) for( int i = 0; i < params->cv_folds; ++i ) for( int k = 0; k < params->cv_sizes(i); ++k ) infile.read( reinterpret_cast<char *> (&l1->test_mat[ph_eff][i](k,m)), sizeof(double) ); //if(start==0) cerr << endl <<l1->test_mat[ph_eff][0].block(0,0,3,3) << endl; } infile.close(); } uint64 getSize(string const& fname){ struct stat stat_buf; int rc = stat(fname.c_str(), &stat_buf); return ( rc == 0 ? stat_buf.st_size : 0); }
[ "joelle.mbatchou@regeneron.com" ]
joelle.mbatchou@regeneron.com
2e4c9e80618ad5092697754b076045e4061b35f6
d9c3dc8d5cf025f4eda593990befc2de0bbcff62
/plugin/Source/NPClickOnce/plugin/NPApplicationLauncher.h
544d0c7287965893d2bbca9ef3ed341e94038e5f
[]
no_license
rajkosto/ChromeClickOnce
c6dbf12cd42acba851092a5650f2b02e9b3d19e6
53e1d7846af4b71a9f73f9856e7c23730b76ff22
refs/heads/master
2020-06-04T15:02:53.551335
2014-03-12T22:52:30
2014-03-12T22:52:30
17,578,073
3
2
null
null
null
null
UTF-8
C++
false
false
542
h
#pragma once #include "NPScriptableObject.h" class NPApplicationLauncher : public NPScriptableObject<NPApplicationLauncher> { public: NPApplicationLauncher(NPP instance); virtual ~NPApplicationLauncher(void); bool HasMethod(NPIdentifier method); bool Invoke(NPIdentifier method,const NPVariant* args,uint32_t argc,NPVariant* result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name,NPVariant* result); private: NPIdentifier launchIdentifier; NPIdentifier versionString; NPIdentifier clrVersionString; };
[ "admin@rajko.info" ]
admin@rajko.info
c5cb4baa3ed9e237fa15c99ded9c22e39f42b194
7acc93d31b1fad7f0f71625116a7d372ca37c80c
/thirdparty/vilib/visual_lib/test/src/test_base.cpp
e3108fe1300bc0645810f10a349daa7b16aecc68
[ "MIT", "BSD-3-Clause" ]
permissive
KMS-TEAM/vi_slam
bcb4b4b7393e395d8861e1c4aae24622f0b0d7b0
4cb5ae94bfecef5758f809d84e135e574b4fb860
refs/heads/main
2023-06-14T18:21:14.431529
2021-07-12T17:08:56
2021-07-12T17:08:56
384,636,583
1
1
null
null
null
null
UTF-8
C++
false
false
10,199
cpp
/* * Base class for testing various functionalities * test_base.cpp * * Copyright (c) 2019-2020 Balazs Nagy, * Robotics and Perception Group, University of Zurich * 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. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <fstream> #include <sys/types.h> #include <sys/stat.h> #include <opencv2/highgui.hpp> #include "test/test_base.h" #include "test/common.h" #include "test/arguments.h" #include "vilib/benchmark.h" #include "vilib/feature_detection/detector_benchmark.h" using namespace vilib; TestBase::TestBase(const char * name, const char * file_path, const int max_image_num): name_(name), file_path_(file_path), max_image_num_(max_image_num), success_(true), evaluated_(false) { // std::cout << file_path << std::endl; is_list_ = is_list_file(file_path); } TestBase::~TestBase(void) { } bool TestBase::evaluate(void) { std::cout << "### " << name_ << std::endl; success_ = this->run(); // std::cerr << "error" << std::endl; std::cout << " Success: " << (success_?TEXT_OK:TEXT_FAIL) << std::endl; evaluated_ = true; return success_; } void TestBase::load_image(int load_flags, bool display_image, bool display_info) { this->load_image_to(file_path_,load_flags,image_); if(display_image) { this->display_image(image_,"Original image"); } image_width_ = image_.cols; image_height_ = image_.rows; image_channels_ = image_.channels(); image_size_ = image_width_ * image_height_ * image_channels_; if(display_info) { std::cout << "Image width: " << image_width_ << " px" << std::endl; std::cout << "Image height: " << image_height_ << " px" << std::endl; std::cout << "Image channels: " << image_channels_ << std::endl; std::cout << "Image size: " << image_size_ << " bytes" << std::endl; } } bool TestBase::load_image_dimensions(const std::size_t & width_default, const std::size_t & height_default) { if(!verify_path(file_path_)) { std::cout << " The specified file does not exist (" << file_path_ << ")" << std::endl; return false; } if(is_list_) { // this is a list file, read out the resolution from the first 2 lines std::ifstream list_file(file_path_); std::string list_line; for(int i=0;i<2;++i) { if(!std::getline(list_file,list_line)) { // error reading the line image_width_ = 0; image_height_ = 0; } if(i==0) { image_width_ = std::stoi(list_line); } else if(i==1) { image_height_ = std::stoi(list_line); } } } else if(file_path_ != NULL) { // this is a regular image cv::Mat temp_img; load_image_to(file_path_,cv::IMREAD_GRAYSCALE,temp_img); image_width_ = temp_img.cols; image_height_ = temp_img.rows; } else { assert(width_default > 0); assert(height_default > 0); // use the default arguments image_width_ = width_default; image_height_ = height_default; } return true; } void TestBase::load_image_to(const char * image_path, int load_flags, cv::Mat & dst_image) { // modify image path if it is not an absolute path std::string image_path_abs; if(image_path[0] != '/') { // relative path was given image_path_abs = get_executable_folder_path(); image_path_abs += '/'; image_path_abs += image_path; } else { // absolute path was given image_path_abs = image_path; } dst_image = cv::imread(image_path_abs.c_str(),load_flags); } void TestBase::save_image(const cv::Mat & image, const char * image_path) const { cv::imwrite(image_path,image); } void TestBase::display_image(const cv::Mat & image, const char * image_title) const { cv::imshow(image_title, image); cv::waitKey(); } bool TestBase::compare_images(const cv::Mat & image1, const cv::Mat & image2, unsigned int diff_threshold, bool display_difference, bool display_difference_image, int skip_first_n_rows, int skip_first_n_cols, int skip_last_n_rows, int skip_last_n_cols) const { std::size_t difference_count = 0; cv::Mat difference_image; if(display_difference_image) { difference_image = cv::Mat(image1.rows,image1.cols,CV_8UC1); } bool success = true; do { if (image1.empty() && image2.empty()) { break; } if (image1.cols != image2.cols || image1.rows != image2.rows) { success = false; break; } for(int r=skip_first_n_rows;r<(image1.rows-skip_last_n_rows);++r) { for(int c=skip_first_n_cols;c<(image1.cols-skip_last_n_cols);++c) { unsigned int diff = std::abs(((int)image1.at<unsigned char>(r,c)) - ((int)image2.at<unsigned char>(r,c))); if(diff > diff_threshold) { success = false; if(display_difference) { std::cout << diff << std::endl; } if(display_difference_image) { difference_image.at<unsigned char>(r,c) = 0xFF; } ++difference_count; } } } } while(0); if(!success) { if(display_difference_image) { display_image(difference_image,"Difference image"); } std::cout << " Difference count: " << difference_count << std::endl; } return success; } bool TestBase::compare_image_pyramid(const std::vector<cv::Mat> & image_pyramid1, const std::vector<cv::Mat> & image_pyramid2, unsigned int diff_threshold) const { if(image_pyramid1.size() != image_pyramid2.size()) { std::cout << " Number of pyramid levels differs (image_pyramid1=" << image_pyramid1.size() << ",image_pyramid2=" << image_pyramid2.size() << ")" << std::endl; return false; } for(unsigned int l=0;l<image_pyramid1.size();++l) { if(!this->compare_images(image_pyramid1[l], image_pyramid2[l], diff_threshold)) { std::cout << " Difference on level " << l << std::endl; return false; } } return true; } bool TestBase::run_benchmark(std::vector<Statistics> &, std::vector<Statistics> &) { // Descendant test suites should add proper implementation return true; } bool TestBase::is_list_file(const char * file_path) { const char * list_extensions[] = {".txt"}; const std::size_t list_extension_n = sizeof(list_extensions)/sizeof(char*); // find the extension const char * file_extension = NULL; { const char * cur_file_path = file_path; while(cur_file_path != NULL) { file_extension = cur_file_path; cur_file_path = strchr(cur_file_path+1,'.'); } } if(file_extension == NULL) { return false; } for(std::size_t i=0;i<list_extension_n;++i) { if(!strcmp(list_extensions[i],file_extension)) { return true; } } return false; } bool TestBase::verify_path(const char * path) { struct stat info; return (stat(path,&info) == 0); } bool TestBase::run_benchmark_suite(std::vector<Statistics> & stat_cpu, std::vector<Statistics> & stat_gpu) { bool result = true; #if BENCHMARK_ENABLE DetectorBenchmark::init(); #endif /* BENCHMARK_ENABLE */ if(is_list_) { // Evaluate the entire list instead of 1 image // file_path_ holds the path to the list std::ifstream list_file(file_path_); std::string list_line; unsigned int line_count = 0, image_count = 0; while(std::getline(list_file,list_line) && image_count < (unsigned int)max_image_num_) { // skip first 2 lines because they encode the image resolution ++line_count; if(line_count <= 2) { continue; } // load image ++image_count; load_image_to(list_line.c_str(),cv::IMREAD_GRAYSCALE,image_); // run benchmark result = run_benchmark(stat_cpu,stat_gpu) && result; } } else { // Load image 1x this->load_image(cv::IMREAD_GRAYSCALE,false,false); result = result && run_benchmark(stat_cpu,stat_gpu); } // Display all statistics if(stat_cpu.size()) { std::cout << " CPU ---" << std::endl; for(Statistics & stat : stat_cpu) { stat.display(); } } if(stat_gpu.size()) { std::cout << " GPU ---" << std::endl; for(Statistics & stat : stat_gpu) { stat.display(); } } // Display all benchmarks #if BENCHMARK_ENABLE DetectorBenchmark::displayAll(); #endif /* BENCHMARK_ENABLE */ return result; }
[ "00sao00ios00@gmail.com" ]
00sao00ios00@gmail.com
9d510591b91ce6941c2614dcf27a5aeccb578e9f
bfdc2ece38402bab75a83149cd09b16a67bc32fa
/ParseDataFile/DB_pwShuntSreact.cpp
dbb2b16b29468df3e30d11d37d792280aff411be
[]
no_license
wangdi190/avc_deyang
b6bc3c8051824a37c2ff147110b243d205101f1b
68dc6cc27caf8c76f928aff7450a82bf12461591
refs/heads/master
2021-01-19T04:49:10.599642
2016-09-28T09:19:24
2016-09-28T09:19:24
69,438,892
0
1
null
null
null
null
GB18030
C++
false
false
15,267
cpp
// DB_pwShuntSreact.cpp: implementation of the DB_pwShuntSreact class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ParseDataFile.h" #include "DB_pwShuntSreact.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// extern bool g_firstrun; DB_pwShuntSreact::DB_pwShuntSreact() { } DB_pwShuntSreact::~DB_pwShuntSreact() { } bool SortByShuntNu(PositionShunt a, PositionShunt b) { if(a.nu<b.nu) return true; else return false; } bool SortBySreactNu(PositionSreact a, PositionSreact b) { if(a.nu<b.nu) return true; else return false; } bool DB_pwShuntSreact::InitParam() { InitParam_Shunt(); InitParam_Sreact(); return true; } bool DB_pwShuntSreact::InitParam_Shunt() { m_nTableID_Shunt = g_DB.GetTableID("visualpw", "Shunt"); m_VecShunt.clear(); visualpw_Shunt *pDBShunt = (visualpw_Shunt*)g_DB.QueryRecord(m_nTableID_Shunt,NULL,m_recn); if(m_recn<0) return false; PositionShunt posShunt; for (int i=0; i<m_recn; i++) { memset(&posShunt, 0 , sizeof(PositionShunt)); posShunt.nPos = i; memcpy(&posShunt.rec, &pDBShunt[i], sizeof(visualpw_Shunt)); posShunt.nu = pDBShunt[i].NU; m_VecShunt.push_back(posShunt); } std::sort(m_VecShunt.begin(), m_VecShunt.end(), SortByShuntNu); return true; } bool DB_pwShuntSreact::InitParam_Sreact() { m_nTableID_Sreact = g_DB.GetTableID("visualpw", "Sreact"); m_VecSreact.clear(); visualpw_Sreact *pDBSreact = (visualpw_Sreact*)g_DB.QueryRecord(m_nTableID_Sreact,NULL,m_recn); if(m_recn<0) return false; PositionSreact posSreact; for (int i=0; i<m_recn; i++) { memset(&posSreact, 0 , sizeof(PositionSreact)); posSreact.nPos = i; memcpy(&posSreact.rec, &pDBSreact[i], sizeof(visualpw_Sreact)); posSreact.nu = pDBSreact[i].NU; m_VecSreact.push_back(posSreact); } std::sort(m_VecSreact.begin(), m_VecSreact.end(), SortBySreactNu); return true; } int DB_pwShuntSreact::BinaryFindShuntByNu(DWORD nu) { long lMin=0;long lMid=0; long lMax=m_VecShunt.size()-1; DWORD lid; while(lMin<=lMax) { lMid = (lMin+lMax)/2; if (lMid>=0) { lid= m_VecShunt.at(lMid).nu; if (lid<nu) lMin = lMid+1; else if(lid>nu) lMax = lMid-1; else return lMid; } else break; } return -1; } int DB_pwShuntSreact::BinaryFindSreactByNu(DWORD nu) { long lMin=0;long lMid=0; long lMax=m_VecSreact.size()-1; DWORD lid; while(lMin<=lMax) { lMid = (lMin+lMax)/2; if (lMid>=0) { lid= m_VecSreact.at(lMid).nu; if (lid<nu) lMin = lMid+1; else if(lid>nu) lMax = lMid-1; else return lMid; } else break; } return -1; } void DB_pwShuntSreact::RefreshModel(char *pData, int bufSize) { RC_DEVICE_Model *pRec = (RC_DEVICE_Model*)pData; visualpw_Shunt DBrec1, *pDBrec1; visualpw_Sreact DBrec2, *pDBrec2; visualpw_Station *pSta; bool bAddNew_Shunt = false, bAddNew_Sreact = false; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Model); i++) { pSta = g_DataBase.m_pwStation.GetSubStationNameByID(pRec[i].fac_id); if(MatchKeyNo(pRec[i].rc_id, RC_DEVICE_MODEL) == false) { break; } if (pRec[i].rc_type == 1 || pRec[i].rc_type == 3) //电容 { ZeroMemory(&DBrec1, sizeof(DBrec1)); m_nRet = BinaryFindShuntByNu(pRec[i].rc_id); if (m_nRet == -1) { DBrec1.NU = pRec[i].rc_id; sprintf(DBrec1.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec1.Station = pRec[i].fac_id; DBrec1.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(DBrec1.ID, "%d", pRec[i].rc_id); DBrec1.ele = 1-pRec[i].run_state; DBrec1.sta = 0; if (pRec[i].nd1_no<0) DBrec1.Node = 0; else DBrec1.Node = pRec[i].nd1_no; DBrec1.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec1.Qmax=pRec[i].qnom; DBrec1.RVol=pRec[i].vnom; //DBrec1.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Shunt", &DBrec1); bAddNew_Shunt = true; } else { pDBrec1 = &m_VecShunt.at(m_nRet).rec; sprintf(pDBrec1->Name, "%s.%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); pDBrec1->Station = pRec[i].fac_id; pDBrec1->ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(pDBrec1->ID, "%d", pRec[i].rc_id); pDBrec1->ele = 1-pRec[i].run_state; if (pRec[i].nd1_no<0) pDBrec1->Node = 0; else pDBrec1->Node = pRec[i].nd1_no; pDBrec1->VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); pDBrec1->Qmax=pRec[i].qnom; pDBrec1->RVol=pRec[i].vnom; g_DB.UpdateRealRecord("Shunt", m_VecShunt.at(m_nRet).nPos, &m_VecShunt.at(m_nRet).rec, "visualpw"); } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { m_nRet = BinaryFindSreactByNu(pRec[i].rc_id); if (m_nRet == -1) { DBrec2.NU = pRec[i].rc_id; sprintf(DBrec2.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec2.Station = pRec[i].fac_id; DBrec2.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(DBrec2.ID, "%d", pRec[i].rc_id); DBrec2.ele = 1-pRec[i].run_state; DBrec2.sta = 1; if (pRec[i].nd1_no<0) DBrec2.Node1 = 0; else DBrec2.Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) DBrec2.Node2 = 0; else DBrec2.Node2 = pRec[i].nd2_no; DBrec2.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec2.Qmax=pRec[i].qnom; DBrec2.RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Sreact", &DBrec2); bAddNew_Sreact = true; } else { pDBrec2 = &m_VecSreact.at(m_nRet).rec; sprintf(pDBrec2->Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); pDBrec2->Station = pRec[i].fac_id; pDBrec2->ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(pDBrec2->ID, "%d", pRec[i].rc_id); pDBrec2->ele = 1-pRec[i].run_state; pDBrec2->sta = 1; if (pRec[i].nd1_no<0) pDBrec2->Node1 = 0; else pDBrec2->Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) pDBrec2->Node2 = 0; else pDBrec2->Node2 = pRec[i].nd2_no; pDBrec2->VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); pDBrec2->Qmax=pRec[i].qnom; pDBrec2->RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; g_DB.UpdateRealRecord("Sreact", m_VecSreact.at(m_nRet).nPos, &m_VecSreact.at(m_nRet).rec, "visualpw"); } } } if(bAddNew_Shunt) InitParam_Shunt(); if(bAddNew_Sreact) InitParam_Sreact(); } /*void DB_pwShuntSreact::RefreshModel(char *pData, int bufSize) { RC_DEVICE_Model *pRec = (RC_DEVICE_Model*)pData; visualpw_Shunt DBrec1, *pDBrec1; visualpw_Sreact DBrec2, *pDBrec2; visualpw_Station *pSta; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Model); i++) { pSta = g_DataBase.m_pwStation.GetSubStationNameByID(pRec[i].fac_id); if(MatchKeyNo(pRec[i].rc_id, RC_DEVICE_MODEL) == false) { break; } if (pRec[i].rc_type == 1 || pRec[i].rc_type == 3) //电容 { ZeroMemory(&DBrec1, sizeof(DBrec1)); m_szTmp.Format("TABLE(visualpw.Shunt),WHERE(NU=%d)", pRec[i].rc_id); pDBrec1 = (visualpw_Shunt*)g_DB.QueryRecord("Shunt",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec1 == NULL) { DBrec1.NU = pRec[i].rc_id; sprintf(DBrec1.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec1.Station = pRec[i].fac_id; DBrec1.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(DBrec1.ID, "%d", pRec[i].rc_id); DBrec1.ele = 1-pRec[i].run_state; DBrec1.sta = 0; if (pRec[i].nd1_no<0) DBrec1.Node = 0; else DBrec1.Node = pRec[i].nd1_no; DBrec1.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec1.Qmax=pRec[i].qnom; DBrec1.RVol=pRec[i].vnom; //DBrec1.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Shunt", &DBrec1); } else { memcpy(&DBrec1, pDBrec1, sizeof(DBrec1)); sprintf(DBrec1.Name, "%s.%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec1.Station = pRec[i].fac_id; DBrec1.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec1.Station); sprintf(DBrec1.ID, "%d", pRec[i].rc_id); DBrec1.ele = 1-pRec[i].run_state; if (pRec[i].nd1_no<0) DBrec1.Node = 0; else DBrec1.Node = pRec[i].nd1_no; DBrec1.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec1.Qmax=pRec[i].qnom; DBrec1.RVol=pRec[i].vnom; //DBrec1.CtrlType=pRec[i].q_status; g_DB.UpdateRecord("Shunt", m_szTmp.GetBuffer(0), &DBrec1, "visualpw"); } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { ZeroMemory(&DBrec2, sizeof(DBrec2)); m_szTmp.Format("TABLE(visualpw.Sreact),WHERE(NU=%d)", pRec[i].rc_id); pDBrec2 = (visualpw_Sreact*)g_DB.QueryRecord("Sreact",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec2 == NULL) { DBrec2.NU = pRec[i].rc_id; sprintf(DBrec2.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec2.Station = pRec[i].fac_id; DBrec2.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(DBrec2.ID, "%d", pRec[i].rc_id); DBrec2.ele = 1-pRec[i].run_state; DBrec2.sta = 1; if (pRec[i].nd1_no<0) DBrec2.Node1 = 0; else DBrec2.Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) DBrec2.Node2 = 0; else DBrec2.Node2 = pRec[i].nd2_no; DBrec2.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec2.Qmax=pRec[i].qnom; DBrec2.RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; LSI_AppendRec("visualpw.Sreact", &DBrec2); } else { memcpy(&DBrec2, pDBrec2, sizeof(DBrec2)); sprintf(DBrec2.Name, "%s%s", pSta!=NULL?pSta->Name:"", pRec[i].rc_name); DBrec2.Station = pRec[i].fac_id; DBrec2.ZoneNU=pSta!=NULL?pSta->zoneNU:0;//GetZoneNU(DBrec2.Station); sprintf(DBrec2.ID, "%d", pRec[i].rc_id); DBrec2.ele = 1-pRec[i].run_state; DBrec2.sta = 1; if (pRec[i].nd1_no<0) DBrec2.Node1 = 0; else DBrec2.Node1 = pRec[i].nd1_no; if (pRec[i].nd2_no<0) DBrec2.Node2 = 0; else DBrec2.Node2 = pRec[i].nd2_no; DBrec2.VL = g_DataBase.m_CommonVec.BinaryFindVoltageBase(pRec[i].vlty_id); DBrec2.Qmax=pRec[i].qnom; DBrec2.RVol=pRec[i].vnom; //DBrec2.CtrlType=pRec[i].q_status; g_DB.UpdateRecord("Sreact", m_szTmp.GetBuffer(0), &DBrec2, "visualpw"); } } } }*/ void DB_pwShuntSreact::RefreshRealTime(char *pData, int bufSize) { RC_DEVICE_Real *pRec = (RC_DEVICE_Real*)pData; PositionShunt *pPos1; PositionSreact *pPos2; visualpw_Shunt *pDBrec1; visualpw_Sreact *pDBrec2; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Real); i++) { if (pRec[i].rc_type == RC_SHUNT || pRec[i].rc_type == RC_SERIESSHUNT) //电容 { m_nRet = BinaryFindShuntByNu(pRec[i].rc_id); if(m_nRet != -1) { pPos1 = &m_VecShunt.at(m_nRet); pDBrec1 = &m_VecShunt.at(m_nRet).rec; if (fabs(pDBrec1->Q - pRec[i].q_value)>0.01) { LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "Q", (void*)&pRec[i].q_value); pDBrec1->Q = pRec[i].q_value; } BYTE Tsta=pDBrec1->Tsta; if(g_TimeFile.GetDay()!=pDBrec1->LogTime.GetDay()) //复位 Tsta=0; if(fabs((pDBrec1->Q - pRec[i].q_value)/pDBrec1->Qmax)>0.5) { if(g_firstrun==false) Tsta++; } if(Tsta!=pDBrec1->Tsta) //变位计数 { //g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "Tsta", (void*)&Tsta); LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "Tsta", (void*)&Tsta); pDBrec1->Tsta = Tsta; } BYTE sta=0; if(fabs(pDBrec1->Q)>0.1||fabs(pDBrec1->I)>0.1) sta=1; if (pDBrec1->sta != sta) { LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "sta", (void*)&sta); pDBrec1->sta = sta; } if (pDBrec1->LogTime != g_TimeFile) { LSI_PutColVal(m_nTableID_Shunt, pPos1->nPos, "LogTime", (void*)&g_TimeFile); pDBrec1->LogTime = g_TimeFile; } } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { m_nRet = BinaryFindSreactByNu(pRec[i].rc_id); if (m_nRet == -1) { pPos2 = &m_VecSreact.at(m_nRet); pDBrec2 = &m_VecSreact.at(m_nRet).rec; if (fabs(pDBrec2->Zx - pRec[i].q_value)>0.01) { LSI_PutColVal(m_nTableID_Sreact, pPos2->nPos, "Zx", (void*)&pRec[i].q_value); pDBrec2->Zx = pRec[i].q_value; } BYTE sta=0; if(fabs(pDBrec2->Zx)>0.1||fabs(pDBrec2->I)>0.1) sta=1; if (sta != pDBrec2->sta) { LSI_PutColVal(m_nTableID_Sreact, pPos2->nPos, "sta", (void*)&sta); pDBrec2->sta = sta; } if (pDBrec2->LogTime != g_TimeFile) { LSI_PutColVal(m_nTableID_Sreact, pPos2->nPos, "LogTime", (void*)&g_TimeFile); pDBrec2->LogTime = g_TimeFile; } } } } } /* void DB_pwShuntSreact::RefreshRealTime(char *pData, int bufSize) { // InitParam(); RC_DEVICE_Real *pRec = (RC_DEVICE_Real*)pData; visualpw_Shunt *pDBrec1; visualpw_Sreact *pDBrec2; for (int i=0; i<bufSize/sizeof(RC_DEVICE_Real); i++) { if (pRec[i].rc_type == RC_SHUNT || pRec[i].rc_type == RC_SERIESSHUNT) //电容 { m_szTmp.Format("TABLE(visualpw.Shunt),WHERE(NU=%d)", pRec[i].rc_id); pDBrec1 = (visualpw_Shunt*)g_DB.QueryRecord("Shunt",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec1 != NULL) { if (fabs(pDBrec1->Q - pRec[i].q_value)>0.01) g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "Q", (void*)&pRec[i].q_value); BYTE Tsta=pDBrec1->Tsta; if(g_TimeFile.GetDay()!=pDBrec1->LogTime.GetDay()) //复位 Tsta=0; if(fabs((pDBrec1->Q - pRec[i].q_value)/pDBrec1->Qmax)>0.5) { if(g_firstrun==false) Tsta++; } if(Tsta!=pDBrec1->Tsta) //变位计数 g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "Tsta", (void*)&Tsta); BYTE sta=0; if(fabs(pDBrec1->Q)>0.1||fabs(pDBrec1->I)>0.1) sta=1; g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "sta", (void*)&sta); g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "LogTime", (void*)&g_TimeFile); } } else if (pRec[i].rc_type == 2 || //电抗 pRec[i].rc_type == 4 || pRec[i].rc_type == 5) { m_szTmp.Format("TABLE(visualpw.Sreact),WHERE(NU=%d)", pRec[i].rc_id); pDBrec2 = (visualpw_Sreact*)g_DB.QueryRecord("Sreact",m_szTmp.GetBuffer(0),m_recn,"visualpw"); if(pDBrec2 != NULL) { if (fabs(pDBrec2->Zx - pRec[i].q_value)>0.01) g_DB.ModifyRecord(m_nTableID_Sreact, m_szTmp.GetBuffer(0), "Zx", (void*)&pRec[i].q_value); BYTE sta=0; if(fabs(pDBrec2->Zx)>0.1||fabs(pDBrec2->I)>0.1) sta=1; g_DB.ModifyRecord(m_nTableID_Sreact, m_szTmp.GetBuffer(0), "sta", (void*)&sta); g_DB.ModifyRecord(m_nTableID_Shunt, m_szTmp.GetBuffer(0), "LogTime", (void*)&g_TimeFile); } } } if(g_firstrun==true) g_firstrun=false; }*/
[ "wangdi190@qq.com" ]
wangdi190@qq.com
0baa26ae1375782d04f64c5f14aaa7de8a70bb98
64895fff118ac407357a050861297a395fa2fbc6
/CodeChef/Snackdown 17/coup.cpp
4dc8f8bea06e6363ad820c7e81aaf7998892d453
[]
no_license
whiz-Tuhin/Competitve
38df5475ba8f9e4ecfa96071e1a0b639bb2ab41e
f5fd063e31f0e5b6addc26c83e007eeb5ae7b89f
refs/heads/master
2020-04-06T03:46:19.820666
2017-08-01T08:02:00
2017-08-01T08:02:00
68,317,364
4
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
#include <iostream> #include <string> #include <vector> #include <cmath> #include <utility> using namespace std; typedef unsigned long long int ulli; int main(){ ios_base::sync_with_stdio(false); int t; cin>>t; while(t--){ int n; cin>>n; vector<string> grid(2); int count_s = 0; for(int i = 0; i < 2;i++){ string s; cin>>s; grid.push_back(s); } int h = 0,v = 0; for(int i = 0;i < n;i++){ if(grid[0][i] == '*' && grid[1][i] == '*'){ h++; break; } } for(int i = 0;i < n-1;i++){ if((grid[0][i] == '*' && grid[0][i+1] == '*') || (grid[1][i] == '*' && grid[1][i+1] == '*') || (grid[0][i] == '*' && grid[1][i+1] == '*') || (grid[1][i] == '*' && grid[0][i+1] == '*')){ v++; } } cout<<(h+v)<<endl; } return 0; }
[ "tuhinkhare3@gmail.com" ]
tuhinkhare3@gmail.com
bf6b0d51ae6dbd61c103eef05b8194c5ae05a5ac
ca32936825c3cbae13e4db108ad97d670e0a9264
/src/adapter.cc
ddcab60ffb5ccc1f0b2fc7996019a037e0a72975
[]
no_license
zqqiang/node-cad
7b783fb758dcacb5b1e1b8276c73dfe0942adfbb
739ff348b4d2c77b275c3a0fe87682c14ffd8181
refs/heads/master
2021-01-14T08:03:53.991041
2016-12-23T19:07:33
2016-12-23T19:07:33
46,592,925
5
0
null
null
null
null
UTF-8
C++
false
false
339
cc
#include <iostream> #include "adapter.h" #include "core.h" using namespace std; Adapter::Adapter() { } Adapter::~Adapter() { } void Adapter::Execute(int edge, int faceA, int faceB) { cout << " Adapter::Execute edge => " << edge << " faceA => " << faceA << " faceB => " << faceB << endl; Core *core = new Core(); core->Compute(); }
[ "qiangzhaoqing@gmail.com" ]
qiangzhaoqing@gmail.com
71ec932a3dcc2177d58750dac9ce17f49b5c9d78
2153c572a578bd13aec501a34ebcbef9d31aa187
/Launch/LeLaunch.cpp
bc51c4996a5e5386e6d78f60b241682c6d7af069
[]
no_license
ZcHuer/LMPlayer
e579f0718e61789cc15d77b4976379276813085c
da2fe595a8121b3d3c2feec91c461a38d9909bca
refs/heads/master
2022-04-09T22:07:15.900773
2020-03-17T08:10:19
2020-03-17T08:10:19
null
0
0
null
null
null
null
GB18030
C++
false
false
10,600
cpp
// LMPlayer.cpp : 定义应用程序的入口点。 // #include "stdafx.h" #include <ShlObj.h> #include <shellapi.h> #include <TlHelp32.h> #include <ImageHlp.h> #include <string> #include "../SDK/FLog/FileLog.h" #include "../Include/LeReport.h" #include "../Include/Data_RealTime.h" using namespace std; #define LMPLAYER_MUTEX_STRING L"{A974FD90-34FE-4B69-A509-75E43255FE49}" #define LEUPDATE_MUTEX_STRING L"{95209F0E-6D08-48BE-B660-5161524B371F}" // 杀掉进程 BOOL KillProcess(LPCTSTR lpProcessName) { HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 pe; pe.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hSnapShot, &pe)) { return FALSE; } CString strProcessName = lpProcessName; strProcessName.MakeLower(); while (Process32Next(hSnapShot, &pe)) { CString scTmp = pe.szExeFile; scTmp.MakeLower(); if (!scTmp.Compare(strProcessName)) { DWORD dwProcessID = pe.th32ProcessID; HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessID); ::TerminateProcess(hProcess, 0); CloseHandle(hProcess); } scTmp.ReleaseBuffer(); } strProcessName.ReleaseBuffer(); return TRUE; } typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); /** * Don't use the function IsWow64Process as a static function, * you should load it by function GetProcAddress, because * it is not available on all version of Windows. */ LPFN_ISWOW64PROCESS fnIsWow64Process = NULL; /** * This function tells if your application is a x64 program. */ BOOL Isx64Application() { return (sizeof(LPFN_ISWOW64PROCESS) == 8) ? TRUE : FALSE; } /** * This function tells if you're under Windows x64. */ BOOL IsWow64() { BOOL bIsWow64 = FALSE; if (!fnIsWow64Process) fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if (fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) return FALSE; } return bIsWow64; } static BOOL MakeDirExist(LPCWSTR lpwsDir) { if (NULL == lpwsDir) return FALSE; int nLen = lstrlen(lpwsDir); if (nLen <= 0) return FALSE; LPWSTR pwsBuf = new WCHAR[MAX_PATH];; memset(pwsBuf, 0, MAX_PATH); memcpy_s(pwsBuf, MAX_PATH, lpwsDir, nLen*2); BOOL bRtn = PathFileExists(lpwsDir); if (!bRtn) { PathRemoveFileSpec(pwsBuf); if (MakeDirExist(pwsBuf)) { bRtn = CreateDirectory(lpwsDir, NULL); } } delete[] pwsBuf; return bRtn; } #ifndef SAFE_DELETE #define SAFE_DELETE(ptr) do{ if(ptr) {delete ptr; ptr=NULL;} }while(0) #endif #ifndef SAFE_CREATELP #define SAFE_CREATELP(a,b,c) a *b = new a[c + 1]; memset(b,0,sizeof(a) * (c + 1)) #endif #ifndef DELETE_LP_NULL #define DELETE_LP_NULL(x) if(x){delete [] x;x = NULL;} #endif #ifndef SAFE_CREATEARRAY #define SAFE_CREATEARRAY(a,b,c) a b[c]; memset(b,0,sizeof(a) * c); #endif #ifndef SAFE_INITLP #define SAFE_INITLP(a,b,c)b = new a[c+1]; memset(b,0,sizeof(a) * (c+1)); #endif #ifndef SAFE_lP #define SAFE_lP(a,b) a * b = NULL; #endif string ws2s(wstring str) { string s = ""; if (!str.empty()) { int nStrLen = str.length(); SAFE_CREATELP(char, lpBuff, nStrLen * 2); WideCharToMultiByte(CP_ACP, 0, str.c_str(), nStrLen, lpBuff, nStrLen * 2, 0, 0); s = lpBuff; SAFE_DELETE(lpBuff); } return s; } wstring s2ws(string str) { wstring ws = L""; if (!str.empty()) { int nStrLen = str.length(); SAFE_CREATELP(WCHAR, lpBuff, nStrLen); MultiByteToWideChar(CP_ACP, 0, str.c_str(), nStrLen, lpBuff, nStrLen); ws = lpBuff; SAFE_DELETE(lpBuff); } return ws; } // 杀掉进程-lmplayer等,杀n次 void Killlmplayer(int n) { FLOG(_T("Killlmplayer begin")); int i = n; bool bKillLePlayer = false; while (i-- > 0) { CHandle hLePlayerMutex; hLePlayerMutex.Attach(::CreateMutexW(NULL, TRUE, LMPLAYER_MUTEX_STRING)); if (GetLastError() == ERROR_ALREADY_EXISTS) { KillProcess(L"lmp.exe"); } else bKillLePlayer = true; if (bKillLePlayer) break; Sleep(1000); } FLOG(_T("Killlmplayer end")); return; } // 获取一系列变量 void GetVerAndExePath(HINSTANCE hInstance, wstring& wstrCfg, wstring& wstrCurVer, wstring& wstrNewVer, wstring& wstrRun, wstring& wstrVer, wstring& wstrRunExe, wstring& wstrVersionExe) { // 获取当前配置文件路径 WCHAR wcPath_Cfg[MAX_PATH] = { 0 }; ::GetModuleFileName(hInstance, wcPath_Cfg, MAX_PATH); PathRemoveFileSpecW(wcPath_Cfg); PathAppendW(wcPath_Cfg, L"\\Config.ini"); wstrCfg = wcPath_Cfg; // 获取当前版本号 WCHAR wcCurVer[MAX_PATH] = { 0 }; ::GetPrivateProfileStringW(L"Update", L"CurVer", L"", wcCurVer, MAX_PATH, wcPath_Cfg); wstrCurVer = wcCurVer; // 获取新版本号 WCHAR wcNewVer[MAX_PATH] = { 0 }; ::GetPrivateProfileStringW(L"Update", L"NewVer", L"", wcNewVer, MAX_PATH, wcPath_Cfg); wstrNewVer = wcNewVer; WCHAR wcPath_Run[MAX_PATH] = { 0 }; ::GetModuleFileNameW(hInstance, wcPath_Run, MAX_PATH); PathRemoveFileSpecW(wcPath_Run); wstrRun = wcPath_Run; wstrRun += L"\\run"; wstrVer = wcPath_Run; wstrVer += L"\\"; wstrVer += wcNewVer; wstrVersionExe = wstrVer; wstrVersionExe += L"\\lmp.exe"; wstrRunExe = wcPath_Run; wstrRunExe += L"\\run\\lmp.exe"; return; } // 删除run文件夹,并改名新版本文件夹为run BOOL RemoveRunAndRename(wstring wstrRun, wstring wstrVer) { FLOG(_T("RemoveRunAndRename begin")); // 删除run文件夹 SHFILEOPSTRUCTW fop; ZeroMemory(&fop, sizeof(SHFILEOPSTRUCT)); fop.wFunc = FO_DELETE; TCHAR tchTmp[MAX_PATH + 1]; ZeroMemory(tchTmp, (MAX_PATH + 1) * sizeof(TCHAR)); _tcscpy(tchTmp, wstrRun.c_str()); tchTmp[wstrRun.length()] = _T('\0'); tchTmp[wstrRun.length() + 1] = _T('\0'); fop.pFrom = tchTmp; fop.pTo = NULL; fop.fFlags |= FOF_SILENT; /*不显示进度*/ fop.fFlags |= FOF_NOERRORUI; /*不报告错误信息*/ fop.fFlags |= FOF_NOCONFIRMATION;/*不进行确认*/ fop.fFlags &= ~FOF_ALLOWUNDO; fop.hNameMappings = NULL; fop.hwnd = NULL; fop.lpszProgressTitle = NULL; int n = SHFileOperationW(&fop); for (int i = 0; i < 5; i++)// 防止异步操作改不了名字 { //文件夹不存在 if (!PathFileExistsW(wstrRun.c_str())) { // 把版本号更名为run ZeroMemory(&fop, sizeof(fop)); fop.wFunc = FO_RENAME; TCHAR tchTmp_From[MAX_PATH + 1]; ZeroMemory(tchTmp_From, (MAX_PATH + 1) * sizeof(TCHAR)); _tcscpy(tchTmp_From, wstrVer.c_str()); tchTmp_From[wstrVer.length()] = _T('\0'); tchTmp_From[wstrVer.length() + 1] = _T('\0'); fop.pFrom = tchTmp_From; TCHAR tchTmp_To[MAX_PATH + 1]; ZeroMemory(tchTmp_To, (MAX_PATH + 1) * sizeof(TCHAR)); _tcscpy(tchTmp_To, wstrRun.c_str()); tchTmp_To[wstrRun.length()] = _T('\0'); tchTmp_To[wstrRun.length() + 1] = _T('\0'); fop.pTo = tchTmp_To; fop.fFlags |= FOF_SILENT; /*不显示进度*/ fop.fFlags |= FOF_NOERRORUI; /*不报告错误信息*/ fop.fFlags |= FOF_NOCONFIRMATION;/*不进行确认*/ fop.fFlags &= ~FOF_ALLOWUNDO; fop.hNameMappings = NULL; fop.hwnd = NULL; fop.lpszProgressTitle = NULL; int n = SHFileOperationW(&fop); if (0 == n) { FLOG(_T("Rename true")); return TRUE; } else { FLOG(_T("Rename false")); return FALSE; } } Sleep(300); FLOG(_T("Sleep(300)")); } FLOG(_T("RemoveRunAndRename end")); return FALSE; } // 运行lmplayer(是否需要更新版本,是否切换成功,配置文件路径,新版本路径,旧版本exe路径,新版本exe路径,命令行) void Runlmplayer(BOOL bNeedUpdate, BOOL bSwitchOk, wstring wstrCfg, wstring wstrNewVer, wstring wstrRunExe, wstring wstrVersionExe, CString cstrCommand) { FLOG(_T("RunLeplayer begin")); if (bNeedUpdate) { FLOG(_T("bNeedUpdate 1")); if (bSwitchOk) { FLOG(_T("bSwitchOk 1")); WritePrivateProfileStringW(L"Update", L"CurVer", wstrNewVer.c_str(), wstrCfg.c_str()); if (PathFileExistsW(wstrRunExe.c_str())) ::ShellExecuteW(NULL, L"open", wstrRunExe.c_str(), cstrCommand.GetString(), NULL, SW_SHOW); else ::MessageBox(NULL, L"本地文件错误, 请重新下载安装!https://sta.vgs.lenovo.com.cn/leplayer.html", L"提示", MB_OK); // 这里报数:替换成功 CLeReport::GetInstance()->SendRTD_Eeventsync(RTD_UPDATE, "1", "4replace"); } else { FLOG(_T("bSwitchOk 0")); if (PathFileExistsW(wstrVersionExe.c_str())) ::ShellExecuteW(NULL, L"open", wstrVersionExe.c_str(), cstrCommand.GetString(), NULL, SW_SHOW); else ::MessageBox(NULL, L"本地文件错误, 请重新下载安装!https://sta.vgs.lenovo.com.cn/leplayer.html", L"提示", MB_OK); // 这里报数:替换失败 CLeReport::GetInstance()->SendRTD_Eeventsync(RTD_UPDATE, "1", "4replacefail"); } } else { FLOG(_T("bNeedUpdate 0")); if (PathFileExistsW(wstrRunExe.c_str())) ::ShellExecuteW(NULL, L"open", wstrRunExe.c_str(), cstrCommand.GetString(), NULL, SW_SHOW); else ::MessageBox(NULL, L"本地文件错误, 请重新下载安装!https://sta.vgs.lenovo.com.cn/leplayer.html", L"提示", MB_OK); } FLOG(_T("Runlmplayer end")); return; } int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { //初始化日志路径 TCHAR buff_log[MAX_PATH] = { 0 }; GetModuleFileName(NULL, buff_log, sizeof(buff_log)); wstring wslog = buff_log; wslog.append(L".log"); LOGINIT(wslog.c_str()); FLOG(_T("wWinMain begin")); FLOG(L">>>启动,命令行:%s", lpCmdLine); UNREFERENCED_PARAMETER(lpCmdLine); CString cstrCommand = lpCmdLine; // 命令行-启动新版本 if (cstrCommand.Find(L"runnew") != -1) Killlmplayer(3); wstring wstrCfg; // 配置文件路径 wstring wstrCurVer; // 当前版本号 wstring wstrNewVer; // 新版本号 wstring wstrRun; // run路径 wstring wstrVer; // 新版本路径 wstring wstrRunExe; // run下exe路径 wstring wstrVersionExe; // 新版本下exe路径 GetVerAndExePath(hInstance, wstrCfg, wstrCurVer, wstrNewVer, wstrRun, wstrVer, wstrRunExe, wstrVersionExe); BOOL bNeedUpdate = FALSE; BOOL bSwitchOk = FALSE; // 如果两个版本不一样 if (0 != StrCmpW(wstrCurVer.c_str(), wstrNewVer.c_str()) && wstrNewVer.length() != 0 && PathFileExistsW(wstrVersionExe.c_str())) { bNeedUpdate = TRUE; Killlmplayer(1); bSwitchOk = RemoveRunAndRename(wstrRun, wstrVer); } // 运行lmplayer(是否需要更新版本,是否切换成功,配置文件路径,新版本路径,旧版本exe路径,新版本exe路径,命令行) Runlmplayer(bNeedUpdate, bSwitchOk, wstrCfg, wstrNewVer, wstrRunExe, wstrVersionExe, cstrCommand); FLOG(_T("wWinMain end")); return 0; }
[ "liuhs10@lenovo.com" ]
liuhs10@lenovo.com
171b46953de5381bd23df20c0b07220ae393ea4e
9a4b3c039dbe14d357fc6051136214f07851dd4c
/user/MIT_Controller/FSM_States/ControlFSM.cpp
801d888b219d1c212e94daba81d7713e0b171a6c
[ "MIT" ]
permissive
YisongCai666/Cheetah-Software
34cd716a6dac9bd7eab1042d991a121db22a14b3
2b99a85c5307a182a8fb719a6a6f0690e38c0367
refs/heads/master
2020-09-04T08:17:18.683458
2019-10-25T17:07:18
2019-10-25T17:07:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,558
cpp
/*============================ Control FSM ============================*/ /** * The Finite State Machine that manages the robot's controls. Handles * calls to the FSM State functions and manages transitions between all * of the states. */ #include "ControlFSM.h" /** * Constructor for the Control FSM. Passes in all of the necessary * data and stores it in a struct. Initializes the FSM with a starting * state and operating mode. * * @param _quadruped the quadruped information * @param _stateEstimator contains the estimated states * @param _legController interface to the leg controllers * @param _gaitScheduler controls scheduled foot contact modes * @param _desiredStateCommand gets the desired COM state trajectories * @param controlParameters passes in the control parameters from the GUI */ template <typename T> ControlFSM<T>::ControlFSM(Quadruped<T>* _quadruped, StateEstimatorContainer<T>* _stateEstimator, LegController<T>* _legController, GaitScheduler<T>* _gaitScheduler, DesiredStateCommand<T>* _desiredStateCommand, RobotControlParameters* controlParameters, VisualizationData* visualizationData, MIT_UserParameters* userParameters) { // Add the pointers to the ControlFSMData struct data._quadruped = _quadruped; data._stateEstimator = _stateEstimator; data._legController = _legController; data._gaitScheduler = _gaitScheduler; data._desiredStateCommand = _desiredStateCommand; data.controlParameters = controlParameters; data.visualizationData = visualizationData; data.userParameters = userParameters; // Initialize and add all of the FSM States to the state list statesList.invalid = nullptr; statesList.passive = new FSM_State_Passive<T>(&data); statesList.jointPD = new FSM_State_JointPD<T>(&data); statesList.impedanceControl = new FSM_State_ImpedanceControl<T>(&data); statesList.standUp = new FSM_State_StandUp<T>(&data); statesList.balanceStand = new FSM_State_BalanceStand<T>(&data); statesList.locomotion = new FSM_State_Locomotion<T>(&data); safetyChecker = new SafetyChecker<T>(&data); // Initialize the FSM with the Passive FSM State initialize(); } /** * Initialize the Control FSM with the default settings. SHould be set to * Passive state and Normal operation mode. */ template <typename T> void ControlFSM<T>::initialize() { // Initialize a new FSM State with the control data currentState = statesList.passive; // Enter the new current state cleanly currentState->onEnter(); // Initialize to not be in transition nextState = currentState; // Initialize FSM mode to normal operation operatingMode = FSM_OperatingMode::NORMAL; } /** * Called each control loop iteration. Decides if the robot is safe to * run controls and checks the current state for any transitions. Runs * the regular state behavior if all is normal. */ template <typename T> void ControlFSM<T>::runFSM() { // Check the robot state for safe operation operatingMode = safetyPreCheck(); // Run the robot control code if operating mode is not unsafe if (operatingMode != FSM_OperatingMode::ESTOP) { // Run normal controls if no transition is detected if (operatingMode == FSM_OperatingMode::NORMAL) { // Check the current state for any transition nextStateName = currentState->checkTransition(); // Detect a commanded transition if (nextStateName != currentState->stateName) { // Set the FSM operating mode to transitioning operatingMode = FSM_OperatingMode::TRANSITIONING; // Get the next FSM State by name nextState = getNextState(nextStateName); // Print transition initialized info printInfo(1); } else { // Run the iteration for the current state normally currentState->run(); } } // Run the transition code while transition is occuring if (operatingMode == FSM_OperatingMode::TRANSITIONING) { transitionData = currentState->transition(); // Check the robot state for safe operation safetyPostCheck(); // Run the state transition if (transitionData.done) { // Exit the current state cleanly currentState->onExit(); // Print finalizing transition info printInfo(2); // Complete the transition currentState = nextState; // Enter the new current state cleanly currentState->onEnter(); // Return the FSM to normal operation mode operatingMode = FSM_OperatingMode::NORMAL; } } else { // Check the robot state for safe operation safetyPostCheck(); } } else { currentState = statesList.passive; currentState->onEnter(); nextStateName = currentState->stateName; } // Print the current state of the FSM printInfo(0); } /** * Checks the robot state for safe operation conditions. If it is in * an unsafe state, it will not run the normal control code until it * is safe to operate again. * * @return the appropriate operating mode */ template <typename T> FSM_OperatingMode ControlFSM<T>::safetyPreCheck() { // Check for safe orientation if the current state requires it if (currentState->checkSafeOrientation) { if (!safetyChecker->checkSafeOrientation()) { operatingMode = FSM_OperatingMode::ESTOP; std::cout << "broken" << std::endl; } } // Default is to return the current operating mode return operatingMode; } /** * Checks the robot state for safe operation commands after calculating the * control iteration. Prints out which command is unsafe. Each state has * the option to enable checks for commands that it cares about. * * Should this EDamp / EStop or just continue? * Should break each separate check into its own function for clarity * * @return the appropriate operating mode */ template <typename T> FSM_OperatingMode ControlFSM<T>::safetyPostCheck() { // Check for safe desired foot positions if (currentState->checkPDesFoot) { safetyChecker->checkPDesFoot(); } // Check for safe desired feedforward forces if (currentState->checkForceFeedForward) { safetyChecker->checkForceFeedForward(); } // Default is to return the current operating mode return operatingMode; } /** * Returns the approptiate next FSM State when commanded. * * @param next commanded enumerated state name * @return next FSM state */ template <typename T> FSM_State<T>* ControlFSM<T>::getNextState(FSM_StateName stateName) { // Choose the correct FSM State by enumerated state name switch (stateName) { case FSM_StateName::INVALID: return statesList.invalid; case FSM_StateName::PASSIVE: return statesList.passive; case FSM_StateName::JOINT_PD: return statesList.jointPD; case FSM_StateName::IMPEDANCE_CONTROL: return statesList.impedanceControl; case FSM_StateName::STAND_UP: return statesList.standUp; case FSM_StateName::BALANCE_STAND: return statesList.balanceStand; case FSM_StateName::LOCOMOTION: return statesList.locomotion; default: return statesList.invalid; } } /** * Prints Control FSM info at regular intervals and on important events * such as transition initializations and finalizations. Separate function * to not clutter the actual code. * * @param printing mode option for regular or an event */ template <typename T> void ControlFSM<T>::printInfo(int opt) { switch (opt) { case 0: // Normal printing case at regular intervals // Increment printing iteration printIter++; // Print at commanded frequency if (printIter == printNum) { std::cout << "[CONTROL FSM] Printing FSM Info...\n"; std::cout << "---------------------------------------------------------\n"; if (operatingMode == FSM_OperatingMode::NORMAL) { std::cout << "Operating Mode: NORMAL in " << currentState->stateString << "\n"; } else if (operatingMode == FSM_OperatingMode::TRANSITIONING) { std::cout << "Operating Mode: TRANSITIONING from " << currentState->stateString << " to " << nextState->stateString << "\n"; } else if (operatingMode == FSM_OperatingMode::ESTOP) { std::cout << "Operating Mode: ESTOP\n"; } std::cout << "Gait Type: " << data._gaitScheduler->gaitData.gaitName << "\n"; std::cout << std::endl; // Reset iteration counter printIter = 0; } // Print robot info about the robot's status // data._gaitScheduler->printGaitInfo(); // data._desiredStateCommand->printStateCommandInfo(); break; case 1: // Initializing FSM State transition std::cout << "[CONTROL FSM] Transition initialized from " << currentState->stateString << " to " << nextState->stateString << "\n" << std::endl; break; case 2: // Finalizing FSM State transition std::cout << "[CONTROL FSM] Transition finalizing from " << currentState->stateString << " to " << nextState->stateString << "\n" << std::endl; break; } } // template class ControlFSM<double>; This should be fixed... need to make // RobotRunner a template template class ControlFSM<float>;
[ "humanoid@mit.edu" ]
humanoid@mit.edu
5131d9e514f573a78e56346e8783217d69471721
b709bee6ad4d10b99d6ea442050b1d9b264786dc
/AOJ/alds1_12_b_single_source_shortest_path_II.cpp
b27370376a2b000d353b01ca2a333eab69dcbd54
[ "Apache-2.0" ]
permissive
konnase/algorithm
87addb227221ff36bbc6561d5fb3e085925c025a
628ebc03e211da76165349bb03758e991ee8fe18
refs/heads/master
2020-04-04T08:57:35.279553
2019-09-04T13:37:37
2019-09-04T13:37:37
155,801,089
0
0
null
2019-03-17T08:29:38
2018-11-02T02:05:48
C++
UTF-8
C++
false
false
2,818
cpp
// // Created by 李青坪 on 2018/11/8. // /* * 定义结构体Node表示结点编号和某结点到该结点的权重 * 由于优先级队列默认优先取最大值,所以要自定义Compare类,priority_queue<Node, vector<Node>, cmp> V_S; * 需要visited数组来记录结点是否被访问过 */ #include <cstdio> #include <algorithm> #include <queue> #include <vector> #define INFINITY 1<<21 #define NIL -1 #define MAXN 10000 using namespace std; struct Node{ int id; int weight; }; struct cmp{ bool operator ()(Node &a, Node &b){ return a.weight > b.weight; } }; bool comp(Node a, Node b){ return a.weight > b.weight; } vector<Node> graph[MAXN]; priority_queue<Node, vector<Node>, cmp> V_S; int n; int d[MAXN]; bool visited[MAXN]; void init(){ fill(d, d+MAXN, INFINITY); d[0] = 0; fill(visited, visited+MAXN, false); Node node; node.id = 0; node.weight = 0; V_S.push(node); } void updateMinWeight(Node u){ vector<Node>::iterator it; for (it = graph[u.id].begin(); it != graph[u.id].end(); ++it){ //遍历与u相连的所有结点,看有没有结点到S的距离减小了 if (visited[(*it).id]) continue; //与u相连的结点如果已经在S中了,就跳过 if (d[(*it).id] > d[u.id] + (*it).weight){ d[(*it).id] = d[u.id] + (*it).weight; Node node; node.id = (*it).id; node.weight = d[(*it).id]; V_S.push(node); } } } void dijkstra(){ while (!V_S.empty()){ Node u = V_S.top(); V_S.pop(); visited[u.id] = true; updateMinWeight(u); } } int main(){ scanf("%d", &n); int u, k; for (int i = 0; i < n; ++i) { scanf("%d %d", &u, &k); int v, w; Node node; for (int j = 0; j < k; ++j) { scanf("%d %d", &v, &w); node.id = v; node.weight = w; graph[u].push_back(node); } } init(); dijkstra(); for (int l = 0; l < n; ++l) { printf("%d %d\n", l, d[l]); } // Node node1, node2; // node1.id = 0; node1.weight = 5; // node2.id = 1; node2.weight = 3; // cmp cmp1; // printf("%d", cmp1.operator()(node1, node2)); // 测试升序优先级队列 // Node l[6]; // l[0].id = 0; l[0].weight = 3; // l[1].id = 1; l[1].weight = 2; // l[2].id = 2; l[2].weight = 5; // l[3].id = 3; l[3].weight = 3; // l[4].id = 4; l[4].weight = 4; // l[5].id = 5; l[5].weight = 2; // for (int i = 0; i < 6; ++i) { // V_S.push(l[i]); // } // for (int j = 0; j < 6; ++j) { // printf("id: %d weight: %d\n", V_S.top().id, V_S.top().weight); // V_S.pop(); // } } /* 5 0 3 2 3 3 1 1 2 1 2 0 2 3 4 2 3 0 3 3 1 4 1 3 4 2 1 0 1 1 4 4 3 4 2 2 1 3 3 */
[ "lqp19940918@163.com" ]
lqp19940918@163.com
f2d025c21ae40821d3c105e4e95e378398f3d77f
d5f9d7a79053303de0511565132bddf80dfee6f0
/QMultiWindowProject/mainwindow.h
45800811784d6aaaac2ae9cb8c2644e27838bd68
[]
no_license
metaliuyong/QtProjects
4f666fa2714a53fda61abf5f5a782804701721c2
49ca33edbbfbeb7d7e31a8db99450c10edf1dd4a
refs/heads/master
2022-12-29T05:39:13.213834
2020-10-15T22:49:55
2020-10-15T22:49:55
304,539,316
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPaintEvent> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; protected: }; #endif // MAINWINDOW_H
[ "metaliuyong@gmail.com" ]
metaliuyong@gmail.com
d7b136f76d1e00af355ac8776cbc6c9d245ec792
2543612ab825ee3e0b11cfc31c149492488a7ba2
/squirrel/squirrel/sqobject.h
31d26a02a86c9bcd3434944d14ffe3c3959aa73f
[ "MIT" ]
permissive
albertodemichelis/visualsquirrel
6e29941228d9f238aa2f3224e60023aafc49861f
357a2a826ee45325615cc2da72bc8e795a4b2653
refs/heads/master
2020-04-05T20:55:22.687865
2018-11-12T10:28:04
2018-11-12T10:28:04
157,200,205
3
0
MIT
2018-11-12T11:01:58
2018-11-12T11:01:57
null
UTF-8
C++
false
false
9,847
h
/* see copyright notice in squirrel.h */ #ifndef _SQOBJECT_H_ #define _SQOBJECT_H_ #include "squtils.h" #ifdef _SQ64 #define UINT_MINUS_ONE (0xFFFFFFFFFFFFFFFF) #else #define UINT_MINUS_ONE (0xFFFFFFFF) #endif #define SQ_CLOSURESTREAM_HEAD (('S'<<24)|('Q'<<16)|('I'<<8)|('R')) #define SQ_CLOSURESTREAM_PART (('P'<<24)|('A'<<16)|('R'<<8)|('T')) #define SQ_CLOSURESTREAM_TAIL (('T'<<24)|('A'<<16)|('I'<<8)|('L')) struct SQSharedState; enum SQMetaMethod{ MT_ADD=0, MT_SUB=1, MT_MUL=2, MT_DIV=3, MT_UNM=4, MT_MODULO=5, MT_SET=6, MT_GET=7, MT_TYPEOF=8, MT_NEXTI=9, MT_CMP=10, MT_CALL=11, MT_CLONED=12, MT_NEWSLOT=13, MT_DELSLOT=14, MT_TOSTRING=15, MT_NEWMEMBER=16, MT_INHERITED=17, MT_LAST = 18 }; #define MM_ADD _SC("_add") #define MM_SUB _SC("_sub") #define MM_MUL _SC("_mul") #define MM_DIV _SC("_div") #define MM_UNM _SC("_unm") #define MM_MODULO _SC("_modulo") #define MM_SET _SC("_set") #define MM_GET _SC("_get") #define MM_TYPEOF _SC("_typeof") #define MM_NEXTI _SC("_nexti") #define MM_CMP _SC("_cmp") #define MM_CALL _SC("_call") #define MM_CLONED _SC("_cloned") #define MM_NEWSLOT _SC("_newslot") #define MM_DELSLOT _SC("_delslot") #define MM_TOSTRING _SC("_tostring") #define MM_NEWMEMBER _SC("_newmember") #define MM_INHERITED _SC("_inherited") #define _CONSTRUCT_VECTOR(type,size,ptr) { \ for(SQInteger n = 0; n < ((SQInteger)size); n++) { \ new (&ptr[n]) type(); \ } \ } #define _DESTRUCT_VECTOR(type,size,ptr) { \ for(SQInteger nl = 0; nl < ((SQInteger)size); nl++) { \ ptr[nl].~type(); \ } \ } #define _COPY_VECTOR(dest,src,size) { \ for(SQInteger _n_ = 0; _n_ < ((SQInteger)size); _n_++) { \ dest[_n_] = src[_n_]; \ } \ } #define _NULL_SQOBJECT_VECTOR(vec,size) { \ for(SQInteger _n_ = 0; _n_ < ((SQInteger)size); _n_++) { \ vec[_n_].Null(); \ } \ } #define MINPOWER2 4 struct SQRefCounted { SQUnsignedInteger _uiRef; struct SQWeakRef *_weakref; SQRefCounted() { _uiRef = 0; _weakref = NULL; } virtual ~SQRefCounted(); SQWeakRef *GetWeakRef(SQObjectType type); virtual void Release()=0; }; struct SQWeakRef : SQRefCounted { void Release(); SQObject _obj; }; #define _realval(o) (type((o)) != OT_WEAKREF?(SQObject)o:_weakref(o)->_obj) struct SQObjectPtr; #define __AddRef(type,unval) if(ISREFCOUNTED(type)) \ { \ unval.pRefCounted->_uiRef++; \ } #define __Release(type,unval) if(ISREFCOUNTED(type) && ((--unval.pRefCounted->_uiRef)==0)) \ { \ unval.pRefCounted->Release(); \ } #define __ObjRelease(obj) { \ if((obj)) { \ (obj)->_uiRef--; \ if((obj)->_uiRef == 0) \ (obj)->Release(); \ (obj) = NULL; \ } \ } #define __ObjAddRef(obj) { \ (obj)->_uiRef++; \ } #define type(obj) ((obj)._type) #define is_delegable(t) (type(t)&SQOBJECT_DELEGABLE) #define raw_type(obj) _RAW_TYPE((obj)._type) #define _integer(obj) ((obj)._unVal.nInteger) #define _float(obj) ((obj)._unVal.fFloat) #define _string(obj) ((obj)._unVal.pString) #define _table(obj) ((obj)._unVal.pTable) #define _array(obj) ((obj)._unVal.pArray) #define _closure(obj) ((obj)._unVal.pClosure) #define _generator(obj) ((obj)._unVal.pGenerator) #define _nativeclosure(obj) ((obj)._unVal.pNativeClosure) #define _userdata(obj) ((obj)._unVal.pUserData) #define _userpointer(obj) ((obj)._unVal.pUserPointer) #define _thread(obj) ((obj)._unVal.pThread) #define _funcproto(obj) ((obj)._unVal.pFunctionProto) #define _class(obj) ((obj)._unVal.pClass) #define _instance(obj) ((obj)._unVal.pInstance) #define _delegable(obj) ((SQDelegable *)(obj)._unVal.pDelegable) #define _weakref(obj) ((obj)._unVal.pWeakRef) #define _outer(obj) ((obj)._unVal.pOuter) #define _refcounted(obj) ((obj)._unVal.pRefCounted) #define _rawval(obj) ((obj)._unVal.raw) #define _stringval(obj) (obj)._unVal.pString->_val #define _userdataval(obj) ((SQUserPointer)sq_aligning((obj)._unVal.pUserData + 1)) #define tofloat(num) ((type(num)==OT_INTEGER)?(SQFloat)_integer(num):_float(num)) #define tointeger(num) ((type(num)==OT_FLOAT)?(SQInteger)_float(num):_integer(num)) ///////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////// #if defined(SQUSEDOUBLE) && !defined(_SQ64) || !defined(SQUSEDOUBLE) && defined(_SQ64) #define SQ_REFOBJECT_INIT() SQ_OBJECT_RAWINIT() #else #define SQ_REFOBJECT_INIT() #endif #define _REF_TYPE_DECL(type,_class,sym) \ SQObjectPtr(_class * x) \ { \ SQ_OBJECT_RAWINIT() \ _type=type; \ _unVal.sym = x; \ assert(_unVal.pTable); \ _unVal.pRefCounted->_uiRef++; \ } \ inline SQObjectPtr& operator=(_class *x) \ { \ SQObjectType tOldType; \ SQObjectValue unOldVal; \ tOldType=_type; \ unOldVal=_unVal; \ _type = type; \ SQ_REFOBJECT_INIT() \ _unVal.sym = x; \ _unVal.pRefCounted->_uiRef++; \ __Release(tOldType,unOldVal); \ return *this; \ } #define _SCALAR_TYPE_DECL(type,_class,sym) \ SQObjectPtr(_class x) \ { \ SQ_OBJECT_RAWINIT() \ _type=type; \ _unVal.sym = x; \ } \ inline SQObjectPtr& operator=(_class x) \ { \ __Release(_type,_unVal); \ _type = type; \ SQ_OBJECT_RAWINIT() \ _unVal.sym = x; \ return *this; \ } struct SQObjectPtr : public SQObject { SQObjectPtr() { SQ_OBJECT_RAWINIT() _type=OT_NULL; _unVal.pUserPointer=NULL; } SQObjectPtr(const SQObjectPtr &o) { _type = o._type; _unVal = o._unVal; __AddRef(_type,_unVal); } SQObjectPtr(const SQObject &o) { _type = o._type; _unVal = o._unVal; __AddRef(_type,_unVal); } _REF_TYPE_DECL(OT_TABLE,SQTable,pTable) _REF_TYPE_DECL(OT_CLASS,SQClass,pClass) _REF_TYPE_DECL(OT_INSTANCE,SQInstance,pInstance) _REF_TYPE_DECL(OT_ARRAY,SQArray,pArray) _REF_TYPE_DECL(OT_CLOSURE,SQClosure,pClosure) _REF_TYPE_DECL(OT_NATIVECLOSURE,SQNativeClosure,pNativeClosure) _REF_TYPE_DECL(OT_OUTER,SQOuter,pOuter) _REF_TYPE_DECL(OT_GENERATOR,SQGenerator,pGenerator) _REF_TYPE_DECL(OT_STRING,SQString,pString) _REF_TYPE_DECL(OT_USERDATA,SQUserData,pUserData) _REF_TYPE_DECL(OT_WEAKREF,SQWeakRef,pWeakRef) _REF_TYPE_DECL(OT_THREAD,SQVM,pThread) _REF_TYPE_DECL(OT_FUNCPROTO,SQFunctionProto,pFunctionProto) _SCALAR_TYPE_DECL(OT_INTEGER,SQInteger,nInteger) _SCALAR_TYPE_DECL(OT_FLOAT,SQFloat,fFloat) _SCALAR_TYPE_DECL(OT_USERPOINTER,SQUserPointer,pUserPointer) SQObjectPtr(bool bBool) { SQ_OBJECT_RAWINIT() _type = OT_BOOL; _unVal.nInteger = bBool?1:0; } inline SQObjectPtr& operator=(bool b) { __Release(_type,_unVal); SQ_OBJECT_RAWINIT() _type = OT_BOOL; _unVal.nInteger = b?1:0; return *this; } ~SQObjectPtr() { __Release(_type,_unVal); } inline SQObjectPtr& operator=(const SQObjectPtr& obj) { SQObjectType tOldType; SQObjectValue unOldVal; tOldType=_type; unOldVal=_unVal; _unVal = obj._unVal; _type = obj._type; __AddRef(_type,_unVal); __Release(tOldType,unOldVal); return *this; } inline SQObjectPtr& operator=(const SQObject& obj) { SQObjectType tOldType; SQObjectValue unOldVal; tOldType=_type; unOldVal=_unVal; _unVal = obj._unVal; _type = obj._type; __AddRef(_type,_unVal); __Release(tOldType,unOldVal); return *this; } inline void Null() { SQObjectType tOldType = _type; SQObjectValue unOldVal = _unVal; _type = OT_NULL; _unVal.raw = (SQRawObjectVal)NULL; __Release(tOldType ,unOldVal); } private: SQObjectPtr(const SQChar *){} //safety }; inline void _Swap(SQObject &a,SQObject &b) { SQObjectType tOldType = a._type; SQObjectValue unOldVal = a._unVal; a._type = b._type; a._unVal = b._unVal; b._type = tOldType; b._unVal = unOldVal; } ///////////////////////////////////////////////////////////////////////////////////// #ifndef NO_GARBAGE_COLLECTOR #define MARK_FLAG 0x80000000 struct SQCollectable : public SQRefCounted { SQCollectable *_next; SQCollectable *_prev; SQSharedState *_sharedstate; virtual SQObjectType GetType()=0; virtual void Release()=0; virtual void Mark(SQCollectable **chain)=0; void UnMark(); virtual void Finalize()=0; static void AddToChain(SQCollectable **chain,SQCollectable *c); static void RemoveFromChain(SQCollectable **chain,SQCollectable *c); }; #define ADD_TO_CHAIN(chain,obj) AddToChain(chain,obj) #define REMOVE_FROM_CHAIN(chain,obj) {if(!(_uiRef&MARK_FLAG))RemoveFromChain(chain,obj);} #define CHAINABLE_OBJ SQCollectable #define INIT_CHAIN() {_next=NULL;_prev=NULL;_sharedstate=ss;} #else #define ADD_TO_CHAIN(chain,obj) ((void)0) #define REMOVE_FROM_CHAIN(chain,obj) ((void)0) #define CHAINABLE_OBJ SQRefCounted #define INIT_CHAIN() ((void)0) #endif struct SQDelegable : public CHAINABLE_OBJ { bool SetDelegate(SQTable *m); virtual bool GetMetaMethod(SQVM *v,SQMetaMethod mm,SQObjectPtr &res); SQTable *_delegate; }; SQUnsignedInteger TranslateIndex(const SQObjectPtr &idx); typedef sqvector<SQObjectPtr> SQObjectPtrVec; typedef sqvector<SQInteger> SQIntVec; const SQChar *GetTypeName(const SQObjectPtr &obj1); const SQChar *IdType2Name(SQObjectType type); #endif //_SQOBJECT_H_
[ "david@qnsoftware.com" ]
david@qnsoftware.com
a2e35a62b0bcc374e5e3bb8f22889e8830ab51df
7b177b9c7e66d3812a8605f593349038350c1a42
/c++/16.3_recursiveSubstrings.cpp
04d989d2bba322a0181c244a14ccd07a70d4826c
[]
no_license
enola3011/HacktoberFest2k21
bac1cff6c62fa2ac5d10f3fad643d5dd4c57ca00
bea0f643b878772acb9c7e72168b0a9081e05070
refs/heads/main
2023-09-01T06:18:17.031940
2021-10-25T18:10:08
2021-10-25T18:10:08
421,132,416
1
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include <bits/stdc++.h> using namespace std; void subString(string s, string ans) { if (s.length() == 0) { cout << ans << endl; return; } char ch = s[0]; string ros = s.substr(1); subString(ros, ans); subString(ros, ans + ch); } int main() { subString("ABC", " "); cout << endl; return 0; }
[ "vandanadewangan1999@gmail.com" ]
vandanadewangan1999@gmail.com
3944a8ffb68706b8baf7fe597cf6135fbb785792
e7ef7af13648aac13fc39c8f065c53ac7d387505
/libyara.NET/GCHandleWrapper.h
87d54abbbf9bac4f32afa47b22616b2dd334086a
[]
permissive
microsoft/libyara.NET
a09e4f6a42694fefacf7188934c1aa9d253efb96
e5c3524ab82689640c93ce8486d4f386f5751589
refs/heads/master
2023-06-22T06:20:11.322873
2023-06-19T21:37:39
2023-06-19T21:37:39
61,913,596
31
17
BSD-3-Clause
2023-06-19T21:37:41
2016-06-24T21:34:18
C++
UTF-8
C++
false
false
985
h
#pragma once #include <stdexcept> using namespace System; using namespace System::Runtime::InteropServices; namespace libyaraNET { /// <summary> /// RAII wrapper for a GCHandle that frees the handle on scope exit. /// </summary> ref class GCHandleWrapper { GCHandle handle; public: /// <summary> /// Create a GCHandle that points to the specified object. /// </summary> GCHandleWrapper(Object^ value) { handle = GCHandle::Alloc(value); } ~GCHandleWrapper() { handle.Free(); } /// <summary> /// Get the underlying GCHandle /// </summary> GCHandle^ GetHandle() { return handle; } /// <summary> /// Get the underlying GCHandle as a void* /// </summary> void* GetPointer() { return GCHandle::ToIntPtr(handle).ToPointer(); } }; }
[ "kylereed@microsoft.com" ]
kylereed@microsoft.com
87c3a393d2b68de573da304c5ceec39158dc8672
f0de6c3ffc999616a0a9580a8a3678aef283cdf5
/chromeos/components/tether/disconnect_tethering_request_sender_impl.cc
a25b705621f5d75fb0d4519b168a1b6327433d8b
[ "BSD-3-Clause" ]
permissive
r00tk1ts/chromium
db18e3940667da7aa76baff69c229788baa5d706
a3cef2a9d2ba64068c1fe7de81500d9d33cf4f87
refs/heads/master
2023-02-23T04:57:23.997581
2018-03-28T10:54:29
2018-03-28T10:54:29
127,127,996
1
0
null
2018-03-28T11:07:29
2018-03-28T11:07:28
null
UTF-8
C++
false
false
5,140
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 "chromeos/components/tether/disconnect_tethering_request_sender_impl.h" #include <memory> #include "base/memory/ptr_util.h" #include "chromeos/components/tether/ble_connection_manager.h" #include "chromeos/components/tether/tether_host_fetcher.h" #include "components/proximity_auth/logging/logging.h" namespace chromeos { namespace tether { // static DisconnectTetheringRequestSenderImpl::Factory* DisconnectTetheringRequestSenderImpl::Factory::factory_instance_ = nullptr; // static std::unique_ptr<DisconnectTetheringRequestSender> DisconnectTetheringRequestSenderImpl::Factory::NewInstance( BleConnectionManager* ble_connection_manager, TetherHostFetcher* tether_host_fetcher) { if (!factory_instance_) factory_instance_ = new Factory(); return factory_instance_->BuildInstance(ble_connection_manager, tether_host_fetcher); } // static void DisconnectTetheringRequestSenderImpl::Factory::SetInstanceForTesting( Factory* factory) { factory_instance_ = factory; } std::unique_ptr<DisconnectTetheringRequestSender> DisconnectTetheringRequestSenderImpl::Factory::BuildInstance( BleConnectionManager* ble_connection_manager, TetherHostFetcher* tether_host_fetcher) { return base::WrapUnique(new DisconnectTetheringRequestSenderImpl( ble_connection_manager, tether_host_fetcher)); } DisconnectTetheringRequestSenderImpl::DisconnectTetheringRequestSenderImpl( BleConnectionManager* ble_connection_manager, TetherHostFetcher* tether_host_fetcher) : ble_connection_manager_(ble_connection_manager), tether_host_fetcher_(tether_host_fetcher), weak_ptr_factory_(this) {} DisconnectTetheringRequestSenderImpl::~DisconnectTetheringRequestSenderImpl() { for (auto const& entry : device_id_to_operation_map_) entry.second->RemoveObserver(this); } void DisconnectTetheringRequestSenderImpl::SendDisconnectRequestToDevice( const std::string& device_id) { if (base::ContainsKey(device_id_to_operation_map_, device_id)) return; num_pending_host_fetches_++; tether_host_fetcher_->FetchTetherHost( device_id, base::Bind(&DisconnectTetheringRequestSenderImpl::OnTetherHostFetched, weak_ptr_factory_.GetWeakPtr(), device_id)); } bool DisconnectTetheringRequestSenderImpl::HasPendingRequests() { return !device_id_to_operation_map_.empty() || num_pending_host_fetches_ > 0; } void DisconnectTetheringRequestSenderImpl::OnTetherHostFetched( const std::string& device_id, std::unique_ptr<cryptauth::RemoteDevice> tether_host) { num_pending_host_fetches_--; DCHECK(num_pending_host_fetches_ >= 0); if (!tether_host) { PA_LOG(ERROR) << "Could not fetch device with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id) << ". Unable to send DisconnectTetheringRequest."; return; } PA_LOG(INFO) << "Attempting to send DisconnectTetheringRequest to device " << "with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id); std::unique_ptr<DisconnectTetheringOperation> disconnect_tethering_operation = DisconnectTetheringOperation::Factory::NewInstance( *tether_host, ble_connection_manager_); // Add to the map. device_id_to_operation_map_.emplace( device_id, std::move(disconnect_tethering_operation)); // Start the operation; OnOperationFinished() will be called when finished. device_id_to_operation_map_.at(device_id)->AddObserver(this); device_id_to_operation_map_.at(device_id)->Initialize(); } void DisconnectTetheringRequestSenderImpl::OnOperationFinished( const std::string& device_id, bool success) { if (success) { PA_LOG(INFO) << "Successfully sent DisconnectTetheringRequest to device " << "with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id); } else { PA_LOG(ERROR) << "Failed to send DisconnectTetheringRequest to device " << "with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs( device_id); } bool had_pending_requests = HasPendingRequests(); if (base::ContainsKey(device_id_to_operation_map_, device_id)) { // Regardless of success/failure, unregister as a listener and delete the // operation. device_id_to_operation_map_.at(device_id)->RemoveObserver(this); device_id_to_operation_map_.erase(device_id); } else { PA_LOG(ERROR) << "Operation finished, but device with ID " << cryptauth::RemoteDevice::TruncateDeviceIdForLogs(device_id) << " was not being tracked by DisconnectTetheringRequestSender."; } // If there were pending reqests but now there are none, notify the Observers. if (had_pending_requests && !HasPendingRequests()) NotifyPendingDisconnectRequestsComplete(); } } // namespace tether } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
8653926be38dd078d7012422cb4253d9e71392df
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/printscan/faxsrv/clientconsole/errordlg.h
39bc6034e1c0daa5f33ab9970e72aba766b5772d
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
2,056
h
#if !defined(AFX_ERRORDLG_H__E6A84A73_2471_4E02_848B_2263C157998A__INCLUDED_) #define AFX_ERRORDLG_H__E6A84A73_2471_4E02_848B_2263C157998A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ErrorDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CErrorDlg dialog class CErrorDlg : public CDialog { // Construction public: CErrorDlg( DWORD dwWin32ErrCode, DWORD dwFileId, int iLineNumber ); // Dialog Data //{{AFX_DATA(CErrorDlg) enum { IDD = IDD_ERROR }; CStatic m_staticSeperator; BOOL m_bDetails; CString m_cstrDetails; CString m_cstrErrorText; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CErrorDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CErrorDlg) afx_msg void OnDetails(); virtual void OnOK(); virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: void FillErrorText (); CRect m_rcBig; CRect m_rcSmall; DWORD m_dwWin32ErrCode; int m_iLineNumber; DWORD m_dwFileId; }; #define PopupError(err) { CMainFrame *pFrm = GetFrm(); \ if (pFrm) \ pFrm->PostMessage (WM_POPUP_ERROR, \ WPARAM(err), \ MAKELPARAM(__LINE__, __FILE_ID__)); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ERRORDLG_H__E6A84A73_2471_4E02_848B_2263C157998A__INCLUDED_)
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
5b12307122e47bcf65c58be7e47c42cb975ed72a
8a4c011199dc4f3250da99f84f0353b2fef1d2ea
/ColorsBase.h
3e9ca0ec30cbc7602a3d83160ed76c6ed04c3960
[ "Apache-2.0" ]
permissive
yuanyuanxiang/3DCode
87bd35b6a48338fc643b9d7f43187d02959b87eb
8d4c14ea67a3a7ed263074595bd67bc384d8e783
refs/heads/master
2020-06-11T19:56:26.102972
2020-01-02T12:52:33
2020-01-02T12:52:33
75,626,401
12
9
null
null
null
null
GB18030
C++
false
false
3,239
h
/** * @file ColorsBase.h * @brief 彩色二维码彩色编码解码基类 * @date 2016/10/15 */ #pragma once #include "DataTypes.h" #include <vector> using namespace std; #ifndef MAX_MODULESIZE #define MAX_MODULESIZE 177 /**< QR码最大尺寸 */ #endif /** * @enum EncodeModule * @brief 彩色编码模块 * @details 1 - 在白色模块编码;0 - 在黑色模块编码 */ enum EncodeModule { BlackModule = 0, /**< 在前景色编码(黑色) */ WhiteModule = 1, /**< 在背景色编码(白色) */ }; /// 掩码操作 const static int HEADER_MASK[90] = { // 16 x 3 前48位为 Color Infomation 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, // 14 x 3 后42位为 Logo & Version 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1}; /// 采用新版 #define NEW_VERSION 1 /** * @class ColorsBase * @brief 彩色二维码编码解码基类 */ class ColorsBase { protected: BYTE* m_pBitMatrix[MAX_MODULESIZE]; /**< 原二维码 */ int m_nSymbolSize; /**< 二维码尺寸 */ vector<CPixelPoint> m_HeaderIndex; /**< 数据头索引 */ CLogoRect m_LogoRect; /**< 二维码LOGO */ private: EncodeModule m_EncodeModule;/**< 彩色编码模块(1,默认为白色) */ vector<CPixelPoint> m_vColorsModuleIndex; /**< 彩色模块索引 */ public: /** * @brief 创建一个彩色编码解码基类对象 * @param[in] bMatrix 二维码数据 * @param[in] nSymbolSize 二维码尺寸 */ ColorsBase(qrMat bMatrix[MAX_MODULESIZE], int nSymbolSize) { /// 采用for循环,将bMatrix的每行拷贝给m_pBitMatrix /// @note 只能采用循环,不能使用memcpy for (int i = 0; i < nSymbolSize; ++i) { m_pBitMatrix[i] = bMatrix[i]; } /// 构造的对象默认无LOGO m_LogoRect = 0; /// 默认在白色模块编码色彩 m_EncodeModule = WhiteModule; m_nSymbolSize = nSymbolSize; } /// 默认的析构函数 ~ColorsBase() { } /// 设置编码模块 inline void SetEncodeModule(EncodeModule Module) { m_EncodeModule = Module; } /// 获取编码模块 inline EncodeModule GetEncodeModule() const { return m_EncodeModule; } /// 设置二维码LOGO inline void SetLogoRect(CMyRect logo) { m_LogoRect = logo; } /// 获取二维码LOGO inline CMyRect GetLogoRect() const { return m_LogoRect; } /// 获取模块总数 inline int GetModulesCount() const { return m_nSymbolSize * m_nSymbolSize - m_LogoRect.Width() * m_LogoRect.Height(); } // 获取编码模块总数 int GetColorsMoudlesCount() const { return m_vColorsModuleIndex.size(); } /// 获取编码模块的索引 const vector<CPixelPoint>& GetColorsModuleIndex() const { return m_vColorsModuleIndex; } /// 获取彩色编码起始位置 int GetColorsStartIndex() const { return m_EncodeModule ? 0 : 90; } // 初始化编码模块的索引 void InitColorsModuleIndex(BOOL bFore = TRUE); // (row, col)非数据头索引 BOOL NotHeaderIndex(int row, int col) const; // 获取彩色数据头的索引 virtual void GetDataHeaderIndex() = 0; };
[ "962914132@qq.com" ]
962914132@qq.com
c6291f540bcfc75251249df6bbfd25dc5077420c
f85fdd8b8e779ec564abb52876b82ebea9337bcf
/hw7-1/sorted_array_main.cc
ff3e66e0c13a0bae7d8094a8ce76a892b8f99c9a
[ "MIT" ]
permissive
revsic/HYU-ITE1015
0a02b5ee014d9cec8b83fed6ef55a5515afea17f
b2d2d210f4b936be0fd94bd258e15b6c16c432fe
refs/heads/master
2020-04-06T09:11:54.463873
2019-03-07T08:36:00
2019-03-07T08:36:00
157,332,436
1
0
null
null
null
null
UTF-8
C++
false
false
1,051
cc
#include "sorted_array.h" #include <iostream> #include <sstream> int main() { std::string given; SortedArray sorted_array; while (true) { std::cin >> given; if (given == "ascend") { for (int i : sorted_array.GetSortedAscending()) { std::cout << i << ' '; } std::cout << std::endl; } else if (given == "descend") { for (int i : sorted_array.GetSortedDescending()) { std::cout << i << ' '; } std::cout << std::endl; } else if (given == "max") { std::cout << sorted_array.GetMax() << std::endl; } else if (given == "min") { std::cout << sorted_array.GetMin() << std::endl; } else if (given == "quit") { break; } else { std::stringstream sstream(given); int num = 0; sstream >> num; sorted_array.AddNumber(num); } } return 0; }
[ "revsic99@gmail.com" ]
revsic99@gmail.com
d9f5e53ad443bd5d09cb49e5fb0c1eca5f47682c
8d9a1ef810a2369e0285b4ee30188c8b7ba201a2
/containers/R/rclipper_serve/src/r_models.cpp
9a0bef6e1da45e53f20774e039a8cb9c8b4e78ac
[ "Apache-2.0" ]
permissive
RehanSD/clipper
7da926005b0d6774958ee77e655dda4b329b9c2c
90cde6c87d804f595a56f1614942ed620bb85ff0
refs/heads/develop
2020-03-19T23:00:14.113566
2019-03-12T17:20:04
2019-03-12T17:20:04
136,989,102
1
2
Apache-2.0
2018-07-09T19:47:32
2018-06-11T22:48:34
C++
UTF-8
C++
false
false
3,536
cpp
#include <iostream> #include "r_models.hpp" #include <Rcpp.h> #include "datatypes.hpp" namespace container { RNumericVectorModel::RNumericVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RNumericVectorModel::predict(const std::vector<DoubleVector> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::NumericVector> numeric_inputs; for(auto const& input : inputs) { Rcpp::NumericVector numeric_input(input.get_data(), input.get_data() + input.get_length()); numeric_inputs.push_back(std::move(numeric_input)); } Rcpp::List list = function_(Rcpp::wrap(numeric_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RIntegerVectorModel::RIntegerVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RIntegerVectorModel::predict(const std::vector<IntVector> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::IntegerVector> integer_inputs; for(auto const& input : inputs) { Rcpp::IntegerVector integer_input(input.get_data(), input.get_data() + input.get_length()); integer_inputs.push_back(std::move(integer_input)); } Rcpp::List list = function_(Rcpp::wrap(integer_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RRawVectorModel::RRawVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RRawVectorModel::predict(const std::vector<ByteVector> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::RawVector> raw_inputs; for(auto const& input : inputs) { Rcpp::RawVector raw_input(input.get_data(), input.get_data() + input.get_length()); raw_inputs.push_back(std::move(raw_input)); } Rcpp::List list = function_(Rcpp::wrap(raw_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RCharacterVectorModel::RCharacterVectorModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RCharacterVectorModel::predict(const std::vector<SerializableString> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::RawVector> raw_inputs; for(auto const& input : inputs) { Rcpp::RawVector raw_input(input.get_data(), input.get_data() + input.get_length()); raw_inputs.push_back(std::move(raw_input)); } Rcpp::List list = function_(Rcpp::wrap(raw_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } RSerializedInputModel::RSerializedInputModel(const Rcpp::Function function) : function_(function) { } std::vector<std::string> RSerializedInputModel::predict(const std::vector<SerializableString> inputs) const { std::vector<std::string> outputs; std::vector<Rcpp::RawVector> serialized_inputs; for(auto const& input : inputs) { Rcpp::RawVector serialized_input(input.get_data(), input.get_data() + input.get_length()); serialized_inputs.push_back(std::move(serialized_input)); } Rcpp::List list = function_(Rcpp::wrap(serialized_inputs)); for(Rcpp::List::iterator it = list.begin(); it != list.end(); ++it) { outputs.push_back(Rcpp::as<std::string>(*it)); } return outputs; } } // namespace container
[ "dscrankshaw@gmail.com" ]
dscrankshaw@gmail.com
9def4216287ac715010445c417f8aff0f5daa7ff
8c8820fb84dea70d31c1e31dd57d295bd08dd644
/Experimental/Chaos/Public/Chaos/TrackedGeometryManager.h
ec2168cb41318f62081abcec84ab2f040958fca1
[]
no_license
redisread/UE-Runtime
e1a56df95a4591e12c0fd0e884ac6e54f69d0a57
48b9e72b1ad04458039c6ddeb7578e4fc68a7bac
refs/heads/master
2022-11-15T08:30:24.570998
2020-06-20T06:37:55
2020-06-20T06:37:55
274,085,558
3
0
null
null
null
null
UTF-8
C++
false
false
2,065
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once namespace Chaos { class FImplicitObject; class CHAOS_API FTrackedGeometryManager { public: static FTrackedGeometryManager& Get() { static FTrackedGeometryManager Singleton; return Singleton; } void DumpMemoryUsage(FOutputDevice* Ar) const { struct FMemInfo { uint32 NumBytes; FString DebugInfo; FString ToString; bool operator<(const FMemInfo& Other) const { return NumBytes < Other.NumBytes; } }; TArray<FMemInfo> MemEntries; uint32 TotalBytes = 0; for (const auto& Itr : SharedGeometry) { FMemInfo Info; Info.DebugInfo = Itr.Value; TArray<uint8> Data; FMemoryWriter MemAr(Data); FChaosArchive ChaosAr(MemAr); FImplicitObject* NonConst = const_cast<FImplicitObject*>(Itr.Key.Get()); //only doing this to write out, serialize is non const for read in NonConst->Serialize(ChaosAr); Info.ToString = NonConst->ToString(); Info.NumBytes = Data.Num(); MemEntries.Add(Info); TotalBytes += Info.NumBytes; } MemEntries.Sort(); Ar->Logf(TEXT("")); Ar->Logf(TEXT("Chaos Tracked Geometry:")); Ar->Logf(TEXT("")); for (const FMemInfo& Info : MemEntries) { Ar->Logf(TEXT("%-10d %s ToString:%s"), Info.NumBytes, *Info.DebugInfo, *Info.ToString); } Ar->Logf(TEXT("%-10d Total"), TotalBytes); } private: TMap<TSerializablePtr<FImplicitObject>, FString> SharedGeometry; FCriticalSection CriticalSection; friend FImplicitObject; //These are private because of various threading considerations. ImplicitObject does the cleanup because it needs extra information void AddGeometry(TSerializablePtr<FImplicitObject> Geometry, const FString& DebugInfo) { FScopeLock Lock(&CriticalSection); SharedGeometry.Add(Geometry, DebugInfo); } void RemoveGeometry(const FImplicitObject* Geometry) { FScopeLock Lock(&CriticalSection); TSerializablePtr<FImplicitObject> Dummy; Dummy.SetFromRawLowLevel(Geometry); SharedGeometry.Remove(Dummy); } }; }
[ "wujiahong19981022@outlook.com" ]
wujiahong19981022@outlook.com
7bdcabd191590e83c10f09b372428447b2184da8
e50b5f066628ef65fd7f79078b4b1088f9d11e87
/llvm/tools/clang/test/PCH/cxx-char-literal.cpp
d540720307dd7723342b3fc1c460d2c390120df8
[ "NCSA" ]
permissive
uzleo/coast
1471e03b2a1ffc9883392bf80711e6159917dca1
04bd688ac9a18d2327c59ea0c90f72e9b49df0f4
refs/heads/master
2020-05-16T11:46:24.870750
2019-04-23T13:57:53
2019-04-23T13:57:53
183,025,687
0
0
null
2019-04-23T13:52:28
2019-04-23T13:52:27
null
UTF-8
C++
false
false
409
cpp
// RUN: %clang_cc1 -emit-pch -std=c++1z -o %t %s // RUN: %clang_cc1 -std=c++1z -x ast -ast-print %t | FileCheck %s // Ensure that character literals are properly surfaced through PCH. char a = '0'; // CHECK: char a = '0'; char b = L'1'; // CHECK: char b = L'1'; char c = u8'2'; // CHECK: char c = u8'2'; char d = U'3'; // CHECK: char d = U'3'; char e = u'4'; // CHECK: char e = u'4';
[ "jeffrey.goeders@gmail.com" ]
jeffrey.goeders@gmail.com
5f6583e42da0bc327d71f953a19ada985498edc8
795535d17e9da8afe6d103dcf8f3dea8d435201f
/src/GameObjects/ObjectThemer.cpp
28b1e701344b82582806941bfb00e2dc7352e4f2
[]
no_license
LiudmilaMashkina/Runner
4696033ac36a677d3a9001b913e11285721bcccf
abdcd83098bc3bac58ea315cdb563e3899426e11
refs/heads/master
2021-05-12T03:01:00.709510
2018-02-27T00:47:30
2018-02-27T00:47:30
117,604,929
0
0
null
null
null
null
UTF-8
C++
false
false
441
cpp
#pragma warning(push, 0) #pragma warning(pop) #include "ObjectThemer.h" #include "Utils/Environment.h" ObjectThemer::ObjectThemer() {} ObjectThemer::ThemeId ObjectThemer::getTheme() { int start = static_cast<int>(ObjectThemer::ThemeId::EnumStart) + 1; int end = static_cast<int>(ObjectThemer::ThemeId::EnumEnd) - 1; return static_cast<ObjectThemer::ThemeId>(Environment::generateIntRand(start, end)); }
[ "liudmilamashkina@gmail.com" ]
liudmilamashkina@gmail.com
d3f389ce64e2952fa0d2b731adc18d44f3113945
15bb0920fecafb9c6fe37e6b30e90f8277c9a710
/devel/include/sar_localization/Csi.h
7cf8da9502c54d3225e7a612711cb213b60d3f64
[]
no_license
ClarenceZSK/Root-catkin_ws
673a20c560958197bc7b783873ff71fbc39623f2
6a1886e6fee42a1d4209595765294191c0440709
refs/heads/master
2020-12-30T10:50:06.238611
2015-09-03T12:59:12
2015-09-03T12:59:12
31,320,005
0
0
null
null
null
null
UTF-8
C++
false
false
6,074
h
// Generated by gencpp from file sar_localization/Csi.msg // DO NOT EDIT! #ifndef SAR_LOCALIZATION_MESSAGE_CSI_H #define SAR_LOCALIZATION_MESSAGE_CSI_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> #include <std_msgs/Float64.h> namespace sar_localization { template <class ContainerAllocator> struct Csi_ { typedef Csi_<ContainerAllocator> Type; Csi_() : header() , cos_value() { } Csi_(const ContainerAllocator& _alloc) : header(_alloc) , cos_value(_alloc) { } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::std_msgs::Float64_<ContainerAllocator> _cos_value_type; _cos_value_type cos_value; typedef boost::shared_ptr< ::sar_localization::Csi_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::sar_localization::Csi_<ContainerAllocator> const> ConstPtr; }; // struct Csi_ typedef ::sar_localization::Csi_<std::allocator<void> > Csi; typedef boost::shared_ptr< ::sar_localization::Csi > CsiPtr; typedef boost::shared_ptr< ::sar_localization::Csi const> CsiConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::sar_localization::Csi_<ContainerAllocator> & v) { ros::message_operations::Printer< ::sar_localization::Csi_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace sar_localization namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'sar_localization': ['/home/clarence/catkin_ws/src/sar_localization/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::sar_localization::Csi_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::sar_localization::Csi_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::sar_localization::Csi_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::sar_localization::Csi_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sar_localization::Csi_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::sar_localization::Csi_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::sar_localization::Csi_<ContainerAllocator> > { static const char* value() { return "243b6b66f6697b18c3d1b19c55371a5a"; } static const char* value(const ::sar_localization::Csi_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x243b6b66f6697b18ULL; static const uint64_t static_value2 = 0xc3d1b19c55371a5aULL; }; template<class ContainerAllocator> struct DataType< ::sar_localization::Csi_<ContainerAllocator> > { static const char* value() { return "sar_localization/Csi"; } static const char* value(const ::sar_localization::Csi_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::sar_localization::Csi_<ContainerAllocator> > { static const char* value() { return "Header header\n\ std_msgs/Float64 cos_value\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: std_msgs/Float64\n\ float64 data\n\ "; } static const char* value(const ::sar_localization::Csi_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::sar_localization::Csi_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.cos_value); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct Csi_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::sar_localization::Csi_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::sar_localization::Csi_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "cos_value: "; s << std::endl; Printer< ::std_msgs::Float64_<ContainerAllocator> >::stream(s, indent + " ", v.cos_value); } }; } // namespace message_operations } // namespace ros #endif // SAR_LOCALIZATION_MESSAGE_CSI_H
[ "shengkai.zhang@gmail.com" ]
shengkai.zhang@gmail.com
ff497c137921789684bd803496fd6c4c26c3b8f8
016dcc77cade4d5df23387dea4a4038c7ed2e683
/src/pluginmanager.h
1ec51037b8672ee9c0fce80ea06c2d8206c74547
[]
no_license
wyrover/akview
aeeb971e14a3065378a3b9d05fa5eb8607375d64
c10e6f92ec57260e6bc7fc5e1d9d9e0f3bbe37e6
refs/heads/master
2021-01-15T09:53:15.401278
2015-01-04T11:02:54
2015-01-04T11:02:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
#ifndef PLUGINMANAGER_H #define PLUGINMANAGER_H #include "actionthread.h" #include "plugin.h" #include "progressbardialog.h" namespace mv { class PluginManager : public QObject { Q_OBJECT public: PluginManager(); bool loadPlugin(const QString& folderPath); void loadPlugins(const QString& folderPath); PluginVector plugins() const; void execAction(const QString& actionName, const QStringList& filePaths); private: PluginVector plugins_; QString afterPackageInstallationAction_; QStringList afterPackageInstallationFilePaths_; QScriptEngine* scriptEngine_; QStringList replaceVariables(const QStringList& command); QObject* jsConsole_; QObject* jsImaging_; QObject* jsSystem_; ActionThread* actionThread_; bool canceling_; public slots: void packageManager_installationDone(); void actionThread_finished(); void mainWindow_cancelButtonClicked(); }; } #endif // PLUGINMANAGER_H
[ "laurent@pogopixels.com" ]
laurent@pogopixels.com
94352804703f0f7be19cff404381dec5ba7ab566
719ca866888053c63c4f76207f3792b0a46b5c8a
/Libraries/FiringRateSim/PacemakerNeuron.h
da27a8c42be746e490a18e4d21c57b03529469f9
[]
no_license
silicondosa/AnimatLabPublicSource
08e71f28c221881bf8527bb95df8cf530c455ca0
c5b23f8898513582afb7891eb994a7bd40a89f08
refs/heads/master
2023-03-20T02:16:00.390767
2016-10-04T18:17:59
2016-10-04T18:17:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,789
h
/** \file PacemakerNeuron.h \brief Declares the pacemaker neuron class. **/ #pragma once namespace FiringRateSim { namespace Neurons { class FAST_NET_PORT PacemakerNeuron : public Neuron { protected: /// The hyperpolarizing current that brings the membrane potential back down after it has been firing. float m_fltIl; /// The slope of the linear function that is used to calculate the length of time that Il current remains active. float m_fltIh; /// A lower steady state threshold. If the steady state voltage of the neuron goes below this value then the Il current is locked on until that voltage rises above this threshold. float m_fltVssm; /// The slope of the linear function that is used to calculate the length of time that Il current remains active. float m_fltMtl; /// The intercept of the linear function that is used to calculate the length of time that Il current remains active. float m_fltBtl; /// This is the length of time that the Ih current remains active. float m_fltTh; /// Time that the current intrinsic current mode is active. float m_fltITime; /// The interburst interval float m_fltInterburstInterval; /// The steady state voltage float m_fltVss; /// Type of the intrinsic current that is active. (HI or LOW) unsigned char m_iIntrinsicType; void HighCurrentOn(); void LowCurrentOn(float fltVss); virtual float CalculateIntrinsicCurrent(FiringRateModule *lpModule, float fltInputCurrent); public: PacemakerNeuron(); virtual ~PacemakerNeuron(); float Il(); void Il(float fltVal); float Ih(); void Ih(float fltVal); float Vssm(); void Vssm(float fltVal); float Mtl(); void Mtl(float fltVal); float Btl(); void Btl(float fltVal); float Th(); void Th(float fltVal); float ITime(); void ITime(float fltVal); unsigned char IntrinsicType(); void IntrinsicType(unsigned char iVal); virtual unsigned char NeuronType(); virtual void Copy(CStdSerialize *lpSource); virtual void ResetSimulation(); virtual void StepSimulation(); virtual float *GetDataPointer(const std::string &strDataType); virtual bool SetData(const std::string &strDataType, const std::string &strValue, bool bThrowError = true); virtual void QueryProperties(CStdPtrArray<TypeProperty> &aryProperties); #pragma region SnapshotMethods virtual long CalculateSnapshotByteSize(); virtual void SaveKeyFrameSnapshot(byte *aryBytes, long &lIndex); virtual void LoadKeyFrameSnapshot(byte *aryBytes, long &lIndex); #pragma endregion virtual void Load(CStdXml &oXml); }; } //Neurons } //FiringRateSim
[ "dcofer@NeuroRoboticTech.com" ]
dcofer@NeuroRoboticTech.com
fb3fa2d5257395499d9453dbdb0595eeb7db1edb
75d6d834a098b58c944f216b6d2e8533b9eadf60
/Lineseg_Cylinder_3D (inefficient)/Lineseg_Cylinder_3D/main.cpp
2f65a916d6922872eee615990104dbbd3a240a37
[]
no_license
IGME-RIT/physics-lineSeg-Cylinder3D
98e78e92de8e083a6fc05b0d81de42ddf1655a58
023e19c8e3a3fff001f12843ff2fef614d2e0d37
refs/heads/master
2020-12-25T09:38:14.356166
2016-06-03T16:33:12
2016-06-03T16:33:12
60,354,588
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
29,230
cpp
/* Title: Line Segment - Cylinder 3D collision Detection File Name: main.cpp Copyright © 2015 Original authors: Srinivasan Thiagarajan Written under the supervision of David I. Schwartz, Ph.D., and supported by a professional development seed grant from the B. Thomas Golisano College of Computing & Information Sciences (https://www.rit.edu/gccis) at the Rochester Institute of Technology. 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 3 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, see <http://www.gnu.org/licenses/>. Description: This is a example to detect collision between a linesegnt and a cylinder. It finds the closest points on the two lines and finds if the distance between them is less than radius. Ifso, the ncollision is detected. This is a inefficient test because it has a lot of edge cases, but its easier to understand and implement. References: Real time collision Detection by Ericson AABB-2D by Brockton Roth */ #include "GLIncludes.h" // We change this variable upon detecting collision float blue = 0.0f; float threshold = 0.001f; glm::vec3* currentlySelected; short int pointChange = 1; short int lineChange = 1; glm::mat4 MVP1, MVP2; glm::vec3 aaa, bbb; //This struct consists of the basic stuff needed for getting the shape on the screen. struct stuff_for_drawing{ //This stores the address the buffer/memory in the GPU. It acts as a handle to access the buffer memory in GPU. GLuint vbo; //This will be used to tell the GPU, how many vertices will be needed to draw during drawcall. int numberOfVertices; //This function gets the number of vertices and all the vertex values and stores them in the buffer. void initBuffer(int numVertices, VertexFormat* vertices) { numberOfVertices = numVertices; // This generates buffer object names // The first parameter is the number of buffer objects, and the second parameter is a pointer to an array of buffer objects (yes, before this call, vbo was an empty variable) glGenBuffers(1, &vbo); //// Binds a named buffer object to the specified buffer binding point. Give it a target (GL_ARRAY_BUFFER) to determine where to bind the buffer. //// There are several different target parameters, GL_ARRAY_BUFFER is for vertex attributes, feel free to Google the others to find out what else there is. //// The second paramter is the buffer object reference. If no buffer object with the given name exists, it will create one. //// Buffer object names are unsigned integers (like vbo). Zero is a reserved value, and there is no default buffer for each target (targets, like GL_ARRAY_BUFFER). //// Passing in zero as the buffer name (second parameter) will result in unbinding any buffer bound to that target, and frees up the memory. glBindBuffer(GL_ARRAY_BUFFER, vbo); //// Creates and initializes a buffer object's data. //// First parameter is the target, second parameter is the size of the buffer, third parameter is a pointer to the data that will copied into the buffer, and fourth parameter is the //// expected usage pattern of the data. Possible usage patterns: GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, //// GL_DYNAMIC_READ, or GL_DYNAMIC_COPY //// Stream means that the data will be modified once, and used only a few times at most. Static means that the data will be modified once, and used a lot. Dynamic means that the data //// will be modified repeatedly, and used a lot. Draw means that the data is modified by the application, and used as a source for GL drawing. Read means the data is modified by //// reading data from GL, and used to return that data when queried by the application. Copy means that the data is modified by reading from the GL, and used as a source for drawing. glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * numVertices, vertices, GL_STATIC_DRAW); //// By default, all client-side capabilities are disabled, including all generic vertex attribute arrays. //// When enabled, the values in a generic vertex attribute array will be accessed and used for rendering when calls are made to vertex array commands (like glDrawArrays/glDrawElements) //// A GL_INVALID_VALUE will be generated if the index parameter is greater than or equal to GL_MAX_VERTEX_ATTRIBS glEnableVertexAttribArray(0); //// Defines an array of generic vertex attribute data. Takes an index, a size specifying the number of components (in this case, floats)(has a max of 4) //// The third parameter, type, can be GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_FIXED, or GL_FLOAT //// The fourth parameter specifies whether to normalize fixed-point data values, the fifth parameter is the stride which is the offset (in bytes) between generic vertex attributes //// The fifth parameter is a pointer to the first component of the first generic vertex attribute in the array. If a named buffer object is bound to GL_ARRAY_BUFFER (and it is, in this case) //// then the pointer parameter is treated as a byte offset into the buffer object's data. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)16); //// You'll note sizeof(VertexFormat) is our stride, because each vertex contains data that adds up to that size. //// You'll also notice we offset this parameter by 16 bytes, this is because the vec3 position attribute is after the vec4 color attribute. A vec4 has 4 floats, each being 4 bytes //// so we offset by 4*4=16 to make sure that our first attribute is actually the position. The reason we put position after color in the struct has to do with padding. //// For more info on padding, Google it. //// This is our color attribute, so the offset is 0, and the size is 4 since there are 4 floats for color. glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0); } }; // The basic structure for a Circle. We need a center, a radius, and VBO and total number of vertices. struct Line{ glm::mat4 MVP; glm::vec3 point1; glm::vec3 point2; stuff_for_drawing base; }line; struct Cylinder{ glm::mat4 MVP; float radius; glm::vec3 point1; glm::vec3 point2; stuff_for_drawing base; }cylinder; // This function return the value between min and mx with the least distance value to x. This is called clamping. float clamp_on_range(float x, float min, float max) { if (x < min) return min; if (x > max) return max; return x; } //Convert the circle's position from world coordinate system to the box's model cordinate system. bool is_colliding(Line &l1, Cylinder &c1) { // We Change the line equation to parametric form. /* Assume that P1 and P2 are the closest points on line 1 and 2 respectively. So, P1 = L1(s) = point1 + (s* d1) P2 = L2(t) = point1 + (t* d2) for some constant s and t. the vector joining P1 and P2 is v. thus, v(s,t) = L1(s) + L2(t) So, since v is perpendicular to both L1 and L2. d1.v(s,t) = 0 d2.v(s,t) = 0 substituting the parametric equation for v(s,t) and expanding them gives us: (d1.d1)s - (d1.d2)t = -(d1.r) and (d2.d1)s - (d2.d2)t = -(d2.r) where r = l1.point1 - l2.point1 this can also be written as : |a -b| |s| = |-c| |b -c| |t| |-f| where; a =d1.d1 b= d1.d2 c = d1.r e = d2.d2 f = d2.r d = ae - b^2; solving this system of equation we get: s = (bf -ce)/d t = (af -bc)/d substituting these values in the quation gives us the closest point between two line segments. We can then check if these points lie on the line segment or outside. We then compute the distance between these points, and if the distance is less than a specified threshold then a collision is said to have occoured. If you want more detailed explanations, check the book Real-time Collision detection by Ericson, page 146. */ glm::vec3 d1, d2, r; d1 = l1.point2 - l1.point1; d2 = c1.point2 - c1.point1; r = l1.point1 - c1.point1; float a = glm::dot(d1, d1); float b = glm::dot(d1, d2); float c = glm::dot(d1, r); float e = glm::dot(d2, d2); float f = glm::dot(d2, r); float d = (a*e) - (b*b); float s = ((b*f) - (c*e)) / d; float t = ((a*f) - (b*c)) / d; //consider the equation of the line in parametric form: // P = Point1 + t * directionVector; // Where t is the constant, such that P lies on the on the plane /* since its a parametric representation, if the constants s and t are greater than 1, then the point lies along the vectorPQ but farther down the line i.e not on the line segment. And if the constants are less than 0, then the point lies along the vector -PQ, but after P, so not on the line segment PQ. Thus we can bail at this point knowing no collision occoured. collision detection between two Lines whcih extend infinitly will not have this check. */ glm::vec3 p1, p2; s = clamp_on_range(s, 0.0f, 1.0f); t = clamp_on_range(t, 0.0f, 1.0f); p1 = l1.point1 + (s * d1); p2 = c1.point1 + (t * d2); if (s == 0.0f || s == 1.0f) { //When the nearest point is between the two planes containing the the circles at the end of the cylinder, //We find the projection of that point on the line joining the centers of the cylinder. d = glm::dot(p1 - c1.point1, d2); t = d / glm::length(d2); t = clamp_on_range(t, 0.0f, 1.0f); p2 = c1.point1 + (t * d2); } aaa = p1; bbb = p2; if (t == 0.0f || t == 1.0f) { //If the closest point is near the end of the cylinder, we need to detect if the line intersects the the circle or not. glm::vec3 n = glm::normalize(glm::cross(d1, d2)); glm::vec3 RadiusVec = glm::normalize(glm::cross(n, d2)) * c1.radius; glm::vec3 pointA, pointB; pointA = p2 + RadiusVec; pointB = p2 - RadiusVec; glm::vec3 AR, BR; glm::vec3 diameter = pointB - pointA; AR = glm::normalize(glm::cross(pointA - l1.point1, diameter)); BR = glm::normalize(glm::cross(diameter, pointA - l1.point2)); //If both the end points of the line segment are on the same side of the circle,then the line segment is not intersecting the circle. if (glm::dot(AR, BR) < 0.0f) return false; // Early exit. The line and the cylinder are not colliding. // get the plane contating the two lines, and find the two points on the edge of tcylinder(diameter). //If the end points of the diameter are on the same side of the line l1, then the line intersects cylinder AR = glm::normalize(glm::cross(pointA - l1.point1,d1)); BR = glm::normalize(glm::cross(d1,pointB - l1.point1)); if (glm::dot(AR, BR) >= 0.0f) { aaa = pointA; bbb = pointB; return true; //early quit. the line intersects the cylinder } else return false; // Early quit. they do not intersect. } float dis = glm::distance(p1, p2); if (dis <= cylinder.radius) // If the closest point is closer than the distance of a radius, the objects are colliding. { return true; } else return false; } //This function sets up the two shapes we need for this example. void setup() { int NumberOfDivisions = 20; line.point1 = glm::vec3(-0.5f, 0.5f, 0.0f); line.point2 = glm::vec3(-0.5f, -0.5f, 0.0f); float radius = 0.25f; cylinder.radius = radius; cylinder.point1 = glm::vec3(0.0f, 0.5f, 0.0f); cylinder.point2 = glm::vec3(0.0f, -0.5f, 0.0f); VertexFormat center1(cylinder.point1, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); VertexFormat center2(cylinder.point2, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); std::vector<VertexFormat> vertices; float height = glm::distance(cylinder.point1, cylinder.point2); float theta = 360.0f / NumberOfDivisions; VertexFormat A, B, C, D; //Circle vertex generation //In this example we are not implementing the proper the code for indices. We are just going to produce redundant information in the buffer. //since we are only having a small number of objects on the screen currently, this redundancy should not matter. for (int i = 0; i < NumberOfDivisions; i++) { A = VertexFormat(glm::vec3(radius * cos(glm::radians(i*theta)),0.5f, radius * sin(glm::radians(i*theta))), glm::vec4(0.7f, 0.20f, 0.0f, 1.0f)); B = VertexFormat(glm::vec3(radius * cos(glm::radians((i + 1)*theta)), 0.5f, radius * sin(glm::radians((i + 1)*theta))), glm::vec4(0.7f, 0.20f, 0.0f, 1.0f)); C = VertexFormat(glm::vec3(radius * cos(glm::radians(i*theta)), -0.5f, radius * sin(glm::radians(i*theta))), glm::vec4(0.0f, 0.20f, 0.7f, 1.0f)); D = VertexFormat(glm::vec3(radius * cos(glm::radians((i + 1)*theta)), -0.5f, radius * sin(glm::radians((i + 1)*theta))), glm::vec4(0.0f, 0.20f, 0.7f, 1.0f)); //In every iteration, the center, the point at angle theta and at angle (theta+delta) are fed into the buffer. vertices.push_back(center1); vertices.push_back(A); vertices.push_back(B); vertices.push_back(center2); vertices.push_back(C); vertices.push_back(D); vertices.push_back(A); vertices.push_back(C); vertices.push_back(B); vertices.push_back(C); vertices.push_back(D); vertices.push_back(B); } cylinder.base.initBuffer(12 * NumberOfDivisions, &vertices[0]); } // Global data members #pragma region Global Data member // This is your reference to your shader program. // This will be assigned with glCreateProgram(). // This program will run on your GPU. GLuint program; // These are your references to your actual compiled shaders GLuint vertex_shader; GLuint fragment_shader; // This is a reference to your uniform MVP matrix in your vertex shader GLuint uniMVP; GLuint color; glm::mat4 view; glm::mat4 proj; glm::mat4 PV; glm::mat4 MVP; // Reference to the window object being created by GLFW. GLFWwindow* window; #pragma endregion // Functions called only once every time the program is executed. #pragma region Helper_functions std::string readShader(std::string fileName) { std::string shaderCode; std::string line; // We choose ifstream and std::ios::in because we are opening the file for input into our program. // If we were writing to the file, we would use ofstream and std::ios::out. std::ifstream file(fileName, std::ios::in); // This checks to make sure that we didn't encounter any errors when getting the file. if (!file.good()) { std::cout << "Can't read file: " << fileName.data() << std::endl; // Return so we don't error out. return ""; } // ifstream keeps an internal "get" position determining the location of the element to be read next // seekg allows you to modify this location, and tellg allows you to get this location // This location is stored as a streampos member type, and the parameters passed in must be of this type as well // seekg parameters are (offset, direction) or you can just use an absolute (position). // The offset parameter is of the type streamoff, and the direction is of the type seekdir (an enum which can be ios::beg, ios::cur, or ios::end referring to the beginning, // current position, or end of the stream). file.seekg(0, std::ios::end); // Moves the "get" position to the end of the file. shaderCode.resize((unsigned int)file.tellg()); // Resizes the shaderCode string to the size of the file being read, given that tellg will give the current "get" which is at the end of the file. file.seekg(0, std::ios::beg); // Moves the "get" position to the start of the file. // File streams contain two member functions for reading and writing binary data (read, write). The read function belongs to ifstream, and the write function belongs to ofstream. // The parameters are (memoryBlock, size) where memoryBlock is of type char* and represents the address of an array of bytes are to be read from/written to. // The size parameter is an integer that determines the number of characters to be read/written from/to the memory block. file.read(&shaderCode[0], shaderCode.size()); // Reads from the file (starting at the "get" position which is currently at the start of the file) and writes that data to the beginning // of the shaderCode variable, up until the full size of shaderCode. This is done with binary data, which is why we must ensure that the sizes are all correct. file.close(); // Now that we're done, close the file and return the shaderCode. return shaderCode; } // This method will consolidate some of the shader code we've written to return a GLuint to the compiled shader. // It only requires the shader source code and the shader type. GLuint createShader(std::string sourceCode, GLenum shaderType) { // glCreateShader, creates a shader given a type (such as GL_VERTEX_SHADER) and returns a GLuint reference to that shader. GLuint shader = glCreateShader(shaderType); const char *shader_code_ptr = sourceCode.c_str(); // We establish a pointer to our shader code string const int shader_code_size = sourceCode.size(); // And we get the size of that string. // glShaderSource replaces the source code in a shader object // It takes the reference to the shader (a GLuint), a count of the number of elements in the string array (in case you're passing in multiple strings), a pointer to the string array // that contains your source code, and a size variable determining the length of the array. glShaderSource(shader, 1, &shader_code_ptr, &shader_code_size); glCompileShader(shader); // This just compiles the shader, given the source code. GLint isCompiled = 0; // Check the compile status to see if the shader compiled correctly. glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled); if (isCompiled == GL_FALSE) { char infolog[1024]; glGetShaderInfoLog(shader, 1024, NULL, infolog); // Print the compile error. std::cout << "The shader failed to compile with the error:" << std::endl << infolog << std::endl; // Provide the infolog in whatever manor you deem best. // Exit with failure. glDeleteShader(shader); // Don't leak the shader. // NOTE: I almost always put a break point here, so that instead of the program continuing with a deleted/failed shader, it stops and gives me a chance to look at what may // have gone wrong. You can check the console output to see what the error was, and usually that will point you in the right direction. } return shader; } // Initialization code void init() { // Initializes the glew library glewInit(); // Enables the depth test, which you will want in most cases. You can disable this in the render loop if you need to. glEnable(GL_DEPTH_TEST); // Read in the shader code from a file. std::string vertShader = readShader("VertexShader.glsl"); std::string fragShader = readShader("FragmentShader.glsl"); // createShader consolidates all of the shader compilation code vertex_shader = createShader(vertShader, GL_VERTEX_SHADER); fragment_shader = createShader(fragShader, GL_FRAGMENT_SHADER); // A shader is a program that runs on your GPU instead of your CPU. In this sense, OpenGL refers to your groups of shaders as "programs". // Using glCreateProgram creates a shader program and returns a GLuint reference to it. program = glCreateProgram(); glAttachShader(program, vertex_shader); // This attaches our vertex shader to our program. glAttachShader(program, fragment_shader); // This attaches our fragment shader to our program. // This links the program, using the vertex and fragment shaders to create executables to run on the GPU. glLinkProgram(program); // End of shader and program creation // Creates the view matrix using glm::lookAt. // First parameter is camera position, second parameter is point to be centered on-screen, and the third paramter is the up axis. view = glm::lookAt(glm::vec3(0.0f, 0.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Creates a projection matrix using glm::perspective. // First parameter is the vertical FoV (Field of View), second paramter is the aspect ratio, 3rd parameter is the near clipping plane, 4th parameter is the far clipping plane. proj = glm::perspective(45.0f, 800.0f / 800.0f, 0.1f, 100.0f); //proj = glm::ortho(0.0f,800.0f, 0.0f, 800.0f,0.1f,100.0f); PV = proj * view; glm::mat4 translation = glm::translate(glm::vec3(0.0f, 0.0f, 0.0f)); MVP = PV* translation; MVP1 = MVP; view = glm::lookAt(glm::vec3(0.0f, 3.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)); //Create another position and perspective for camera, and compute the MVP matrix for that position. //Since we'll be just interchanging between two positions of the camera, there is no point in computing the MVP every frame. We will do that later while implementing camera controls. MVP2 = (proj * view) * translation; MVP2 = glm::mat4(1); // This gets us a reference to the uniform variable in the vertex shader, which is called "color". // We're using this variable to change color during runtime, without changing the buffer values. // Only 2 parameters required: A reference to the shader program and the name of the uniform variable within the shader code. uniMVP = glGetUniformLocation(program, "MVP"); color = glGetUniformLocation(program, "blue"); // This is not necessary, but I prefer to handle my vertices in the clockwise order. glFrontFace defines which face of the triangles you're drawing is the front. // Essentially, if you draw your vertices in counter-clockwise order, by default (in OpenGL) the front face will be facing you/the screen. If you draw them clockwise, the front face // will face away from you. By passing in GL_CW to this function, we are saying the opposite, and now the front face will face you if you draw in the clockwise order. // If you don't use this, just reverse the order of the vertices in your array when you define them so that you draw the points in a counter-clockwise order. glFrontFace(GL_CCW); // This is also not necessary, but more efficient and is generally good practice. By default, OpenGL will render both sides of a triangle that you draw. By enabling GL_CULL_FACE, // we are telling OpenGL to only render the front face. This means that if you rotated the triangle over the X-axis, you wouldn't see the other side of the triangle as it rotated. //glEnable(GL_CULL_FACE); //We are disabling hte cull face, because we wish to see both the front and back of the objects in wireframe mode for better understanding the depth. // Determines the interpretation of polygons for rasterization. The first parameter, face, determines which polygons the mode applies to. // The face can be either GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK // The mode determines how the polygons will be rasterized. GL_POINT will draw points at each vertex, GL_LINE will draw lines between the vertices, and // GL_FILL will fill the area inside those lines. //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } #pragma endregion // Functions called between every frame. game logic #pragma region util_functions // This runs once every physics timestep. void update() { // if the objects are colliding then change color, else recvet back to original color if (is_colliding(line, cylinder)) { blue = 1.0f; } else { blue = 0.0f; } // Get the cursor position with respect ot hte window. double x, y; glfwGetCursorPos(window, &x, &y); //Since the cursor posiiton is represented in pixel values, //dividing it by the window specs will reduce the position to 0-1 range. //multiplying it with 2 and then subtracting it with 1 wil bring the //mouse position to -1 ot 1. // Since the screen's origin is on the top, we need to negate the y values. x = x / 800.0f; y = y * (-1.0f) / 800.0f; x = (x * 2) - 1; y = (y * 2) + 1; //the Pointchange variable is used to interchange between the two points of the same line if (pointChange > 0) { currentlySelected = &(line.point1); line.point1.x = x; line.point1.y = y; } else { currentlySelected = &(line.point2); line.point2.x = x; line.point2.y = y; } } // This function runs every frame void renderScene() { // Clear the color buffer and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen to white glClearColor(1.0 -blue, 1.0-blue, 1.0-blue, 1.0); // Tell OpenGL to use the shader program you've created. glUseProgram(program); //since we are not removing the program currently in use, these primitive functions will also use the same shader. // Thus the MVP and color will be set in shader. Thus the lines will be in perspective projection // Set the uniform matrix in our shader to our MVP matrix for the line. glUniformMatrix4fv(uniMVP, 1, GL_FALSE, glm::value_ptr(MVP)); glLineWidth(2.5f); glUniform3f(color, 0.0f,0.0f,blue); glBegin(GL_LINES); glVertex3fv((float*)&line.point1); glVertex3fv((float*)&line.point2); glEnd(); //Drawing the cylinder glUniform3f(color, blue, blue, blue); glBindBuffer(GL_ARRAY_BUFFER ,cylinder.base.vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)16); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)0); glDrawArrays(GL_TRIANGLES, 0, cylinder.base.numberOfVertices); //drawing the x,yand z axis glLineWidth(0.7f); //x-axis (red Color) glUniform3f(color, 1.0f, 0.0f, 0.0f); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(100.0f, 0.0f, 0.0f); glEnd(); //y-axis (green color) glUniform3f(color, 0.0f, 1.0f, 0.0f); glBegin(GL_LINES); glVertex3f(0.0f, 100.0f,0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glEnd(); //z-axis (cyan color) glUniform3f(color, 0.0f, 1.0f, 1.0f); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 100.0f); glVertex3f(0.0f, 0.0f, 0.0f); glEnd(); } // This function is used to handle key inputs. // It is a callback funciton. i.e. glfw takes the pointer to this function (via function pointer) and calls this function every time a key is pressed in the during event polling. void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { float moverate = 0.25f; ////This set of controls are used to move one point (point1) of the line. if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) lineChange *= -1; if (key == GLFW_KEY_LEFT_SHIFT && action == GLFW_PRESS) pointChange *= -1; if (key == GLFW_KEY_W && action == GLFW_PRESS) currentlySelected->z -= 0.05f; if (key == GLFW_KEY_S && action == GLFW_PRESS) currentlySelected->z += 0.05f; //This changes the MVP (modelViewProjection Matrix) in current use, This results in change in camera if (key == GLFW_KEY_LEFT_CONTROL && action == GLFW_PRESS) { if (MVP == MVP1) MVP = MVP2; else MVP = MVP1; } } #pragma endregion void main() { glfwInit(); // Creates a window given (width, height, title, monitorPtr, windowPtr). // Don't worry about the last two, as they have to do with controlling which monitor to display on and having a reference to other windows. Leaving them as nullptr is fine. window = glfwCreateWindow(800, 800, "Line segment-Cylinder collision detection in 3D", nullptr, nullptr); std::cout << "\n This is a collision test between a cylinder and Line segment in 3D.\n\n\n\n\n"; std::cout << "Use Mouse to move in x-y plane, and \"w and s\" to move in z axis.\n"; std::cout << "Use left Shift to change the prespective of the camera between, perspective and orthagonal.\n"; std::cout << "Use \"left shift\" to change betweeen the vertices in contrl "; // Makes the OpenGL context current for the created window. glfwMakeContextCurrent(window); // Sets the number of screen updates to wait before swapping the buffers. // Setting this to zero will disable VSync, which allows us to actually get a read on our FPS. Otherwise we'd be consistently getting 60FPS or lower, // since it would match our FPS to the screen refresh rate. // Set to 1 to enable VSync. glfwSwapInterval(0); // Initializes most things needed before the main loop init(); // Sends the funtion as a funtion pointer along with the window to which it should be applied to. glfwSetKeyCallback(window, key_callback); setup(); // Enter the main loop. while (!glfwWindowShouldClose(window)) { // Call to update() which will update the gameobjects. update(); // Call the render function. renderScene(); // Swaps the back buffer to the front buffer // Remember, you're rendering to the back buffer, then once rendering is complete, you're moving the back buffer to the front so it can be displayed. glfwSwapBuffers(window); // Checks to see if any events are pending and then processes them. glfwPollEvents(); } // After the program is over, cleanup your data! glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(program); // Note: If at any point you stop using a "program" or shaders, you should free the data up then and there. // Frees up GLFW memory glfwTerminate(); }
[ "lunalovecraft@gmail.com" ]
lunalovecraft@gmail.com
750a38bce1f914031c9f1fce234c20854d33d47d
65ff0d6c1d995fbcc3402708fce77c6bf451998d
/calc_nPE/calc_nPE.cpp
e923c5aca83c2a6afc83707dae9011cbd1e078ce
[]
no_license
mabrow05/ParallelAnalyzer
de1b11d7718ab06bae579a5eebcc9bab3e890436
ad0855caae19ed61cd915ee66ef3b7b55976a6ab
refs/heads/master
2021-01-19T11:35:27.998125
2015-12-21T15:48:01
2015-12-21T15:48:01
34,797,061
0
0
null
null
null
null
UTF-8
C++
false
false
8,889
cpp
#include <iostream> #include <fstream> #include <cmath> #include <cstdlib> #include <sstream> // ROOT libraries #include "TRandom3.h" #include <TTree.h> #include <TFile.h> #include <TH1F.h> #include <TH2F.h> #include <TF1.h> #include <TH1D.h> #include "fullTreeVariables.h" #include "MWPCGeometry.h" #include "pedestals.h" #include "cuts.h" #include "basic_reconstruction.h" #include "replay_pass2.h" #include "replay_pass3.h" using namespace std; int main(int argc, char *argv[]) { //cout.setf(ios::fixed, ios::floatfield); //cout.precision(12); // Run number integer istringstream ss(argv[1]); int runNumber; ss >> runNumber; cout << "runNumber = " << runNumber << endl; // Read source list int nSources = 0; string sourceName[3]; char tempList[500]; sprintf(tempList, "%s/source_list_%s.dat",getenv("SOURCE_LIST"), argv[1]); //cout << tempList << endl; ifstream fileList(tempList); if (fileList.is_open()) fileList >> nSources; cout << " ... Number of sources: " << nSources << endl; for (int n=0; n<nSources; n++) { fileList >> sourceName[n]; cout << " " << sourceName[n] << endl; } //Adding in here that we are only using runs with Sn bool correctSource = false; bool useSource[3] = {false,false,false}; for (int n=0; n<nSources; n++) { if (sourceName[n]=="Sn") { correctSource = true; useSource[n]=true; continue; } } if (!correctSource) { cout << "Source run with no Sn\n"; exit(0); } // Open output ntuple char tempOut[500]; sprintf(tempOut, "%s/nPE_weights_%s.root",getenv("NPE_WEIGHTS"), argv[1]); TFile *fileOut = new TFile(tempOut,"RECREATE"); // Read source positions double xEast[3], yEast[3], sigmaEast[3]; double xWest[3], yWest[3], sigmaWest[3]; char tempPos[500]; sprintf(tempPos, "%s/source_positions_%s.dat",getenv("SOURCE_POSITIONS"), argv[1]); ifstream filePos(tempPos); cout << " ... Reading source positions" << endl; for (int n=0; n<nSources; n++) { filePos >> xEast[n] >> yEast[n] >> sigmaEast[n] >> xWest[n] >> yWest[n] >> sigmaWest[n]; cout << xEast[n] << " " << yEast[n] << " " << sigmaEast[n] << " " << xWest[n] << " " << yWest[n] << " " << sigmaWest[n] << endl; } // Output histograms int nBin = 400; TH1F *his[8]; his[0] = new TH1F("his1_E0", "", nBin,0.0,4000.0); his[1] = new TH1F("his1_E1", "", nBin,0.0,4000.0); his[2] = new TH1F("his1_E2", "", nBin,0.0,4000.0); his[3] = new TH1F("his1_E3", "", nBin,0.0,4000.0); his[4] = new TH1F("his1_W0", "", nBin,0.0,4000.0); his[5] = new TH1F("his1_W1", "", nBin,0.0,4000.0); his[6] = new TH1F("his1_W2", "", nBin,0.0,4000.0); his[7] = new TH1F("his1_W3", "", nBin,0.0,4000.0); /*his[1][0] = new TH1F("his2_E0", "", nBin,0.0,4000.0); his[1][1] = new TH1F("his2_E1", "", nBin,0.0,4000.0); his[1][2] = new TH1F("his2_E2", "", nBin,0.0,4000.0); his[1][3] = new TH1F("his2_E3", "", nBin,0.0,4000.0); his[1][4] = new TH1F("his2_W0", "", nBin,0.0,4000.0); his[1][5] = new TH1F("his2_W1", "", nBin,0.0,4000.0); his[1][6] = new TH1F("his2_W2", "", nBin,0.0,4000.0); his[1][7] = new TH1F("his2_W3", "", nBin,0.0,4000.0); his[2][0] = new TH1F("his3_E0", "", nBin,0.0,4000.0); his[2][1] = new TH1F("his3_E1", "", nBin,0.0,4000.0); his[2][2] = new TH1F("his3_E2", "", nBin,0.0,4000.0); his[2][3] = new TH1F("his3_E3", "", nBin,0.0,4000.0); his[2][4] = new TH1F("his3_W0", "", nBin,0.0,4000.0); his[2][5] = new TH1F("his3_W1", "", nBin,0.0,4000.0); his[2][6] = new TH1F("his3_W2", "", nBin,0.0,4000.0); his[2][7] = new TH1F("his3_W3", "", nBin,0.0,4000.0);*/ // Open input ntuple char tempIn[500]; sprintf(tempIn, "%s/replay_pass3_%s.root",getenv("REPLAY_PASS3"), argv[1]); TFile *fileIn = new TFile(tempIn, "READ"); TTree *Tin = (TTree*)(fileIn->Get("pass3")); // Variables Tin->SetBranchAddress("pmt0_pass3", &pmt_pass3[0]); Tin->SetBranchAddress("pmt1_pass3", &pmt_pass3[1]); Tin->SetBranchAddress("pmt2_pass3", &pmt_pass3[2]); Tin->SetBranchAddress("pmt3_pass3", &pmt_pass3[3]); Tin->SetBranchAddress("pmt4_pass3", &pmt_pass3[4]); Tin->SetBranchAddress("pmt5_pass3", &pmt_pass3[5]); Tin->SetBranchAddress("pmt6_pass3", &pmt_pass3[6]); Tin->SetBranchAddress("pmt7_pass3", &pmt_pass3[7]); Tin->SetBranchAddress("xE_pass3", &xE_pass3); Tin->SetBranchAddress("yE_pass3", &yE_pass3); Tin->SetBranchAddress("xW_pass3", &xW_pass3); Tin->SetBranchAddress("yW_pass3", &yW_pass3); Tin->SetBranchAddress("PID_pass3", &PID_pass3); Tin->SetBranchAddress("type_pass3", &type_pass3); Tin->SetBranchAddress("side_pass3", &side_pass3); Tin->SetBranchAddress("posError_pass3", &posError_pass3); int nEvents = Tin->GetEntries(); cout << "Processing " << argv[1] << " ... " << endl; cout << "... nEvents = " << nEvents << endl; // Loop over events for (int i=0; i<nEvents; i++) { Tin->GetEvent(i); // Use Type 0 events if (type_pass3 != 0) continue; // First source (x,y) if (useSource[0]) { if (side_pass3 == 0) { if ( (xE_pass3 - xEast[0])*(xE_pass3 - xEast[0]) + (yE_pass3 - yEast[0])*(yE_pass3 - yEast[0]) < (2.*sigmaEast[0])*(2.*sigmaEast[0]) ) { for (int p=0; p<4; p++) { his[p]->Fill(pmt_pass3[p]); } } } if (side_pass3 == 1) { if ( (xW_pass3 - xWest[0])*(xW_pass3 - xWest[0]) + (yW_pass3 - yWest[0])*(yW_pass3 - yWest[0]) < (2.*sigmaWest[0])*(2.*sigmaWest[0]) ) { for (int p=4; p<8; p++) { his[p]->Fill(pmt_pass3[p]); } } } } // Second source (x,y) if (nSources > 1 && useSource[1]) { if (side_pass3 == 0) { if ( (xE_pass3 - xEast[1])*(xE_pass3 - xEast[1]) + (yE_pass3 - yEast[1])*(yE_pass3 - yEast[1]) < (2.*sigmaEast[1])*(2.*sigmaEast[1]) ) { for (int p=0; p<4; p++) { his[p]->Fill(pmt_pass3[p]); } } } if (side_pass3 == 1) { if ( (xW_pass3 - xWest[1])*(xW_pass3 - xWest[1]) + (yW_pass3 - yWest[1])*(yW_pass3 - yWest[1]) < (2.*sigmaWest[1])*(2.*sigmaWest[1]) ) { for (int p=4; p<8; p++) { his[p]->Fill(pmt_pass3[p]); } } } } // Third source (x,y) if (nSources > 2 && useSource[2]) { if (side_pass3 == 0) { if ( (xE_pass3 - xEast[2])*(xE_pass3 - xEast[2]) + (yE_pass3 - yEast[2])*(yE_pass3 - yEast[2]) < (2.*sigmaEast[2])*(2.*sigmaEast[2]) ) { for (int p=0; p<4; p++) { his[p]->Fill(pmt_pass3[p]); } } } if (side_pass3 == 1) { if ( (xW_pass3 - xWest[2])*(xW_pass3 - xWest[2]) + (yW_pass3 - yWest[2])*(yW_pass3 - yWest[2]) < (2.*sigmaWest[2])*(2.*sigmaWest[2]) ) { for (int p=4; p<8; p++) { his[p]->Fill(pmt_pass3[p]); } } } } } // Find maximum bin double maxBin[8]; double maxCounts[8]; for (int j=0; j<8; j++) { maxCounts[j] = -1.0; } double binCenter[8]; double binCenterMax[8]; double binCounts[8]; for (int i=0; i<nBin; i++) { for (int j=0; j<8; j++) { binCenter[j] = his[j]->GetBinCenter(i+1); binCounts[j] = his[j]->GetBinContent(i+1); if (binCounts[j] > maxCounts[j]) { maxCounts[j] = binCounts[j]; maxBin[j] = i; binCenterMax[j] = binCenter[j]; } } } // Define histogram fit ranges double xLow[8], xHigh[8]; for (int j=0; j<8; j++) { for (int i=maxBin[j]; i<nBin; i++) { if (his[j]->GetBinContent(i+1) < 0.5*maxCounts[j]) { xHigh[j] = his[j]->GetBinCenter(i+1); break; } } for (int i=maxBin[j]; i>0; i--) { if (his[j]->GetBinContent(i+1) < 0.5*maxCounts[j]) { xLow[j] = his[j]->GetBinCenter(i+1); break; } } } // Fit histograms TF1 *gaussian_fit[8]; double fitMean[8], fitSigma[8], nPE[8], nPE_per_channel[8]; for (int j=0; j<8; j++) { char fitName[500]; sprintf(fitName, "gaussian_fit_%i", j); gaussian_fit[j] = new TF1(fitName, "gaus", xLow[j], xHigh[j]); gaussian_fit[j]->SetParameter(0,maxCounts[j]); gaussian_fit[j]->SetParameter(1,binCenterMax[j]); gaussian_fit[j]->SetParameter(2,100.0); gaussian_fit[j]->SetParLimits(1,xLow[j],xHigh[j]); his[j]->Fit(fitName, "LRQ"); fitMean[j] = gaussian_fit[j]->GetParameter(1); fitSigma[j] = gaussian_fit[j]->GetParameter(2); nPE[j] = (fitMean[j]*fitMean[j])/(fitSigma[j]*fitSigma[j]); nPE_per_channel[j] = nPE[j]/fitMean[j]; } // Write results to file char tempResults[500]; sprintf(tempResults, "%s/nPE_weights_%s.dat",getenv("NPE_WEIGHTS"), argv[1]); ofstream outResults(tempResults); for (int j=0; j<8; j++) { outResults << fitMean[j] << " " << fitSigma[j] << " " << nPE[j] << " " << nPE_per_channel[j] << endl; } // Write output ntuple fileOut->Write(); fileOut->Close(); return 0; }
[ "michael.brown1@uky.edu" ]
michael.brown1@uky.edu
223c34dbc43733d6d6060719f222b933a809b20e
5fd214ad737974f864ec2c055495e9696bbf24eb
/examples/mechanics/flexible_body/linear_external_ffr_spatial_beam/system.h
caff8a8c4ca89bd1f0242ec81d42ce51e2e5dcb0
[]
no_license
tsschindler/mbsim
28ede3f2035592532738b833fefe6a8755dfd59e
97fdb10cfe9e22fb962b7522a9b758d1cdc571ce
refs/heads/master
2021-01-15T10:18:44.245224
2015-06-05T11:37:17
2015-06-05T11:37:17
36,926,919
1
0
null
2015-06-05T11:37:18
2015-06-05T10:29:23
C++
UTF-8
C++
false
false
411
h
#ifndef _SYSTEM_H #define _SYSTEM_H #include "mbsim/dynamic_system_solver.h" #include "mbsimFlexibleBody/flexible_body/flexible_body_linear_external_ffr.h" #include "mbsim/rigid_body.h" #include <string> class System : public MBSim::DynamicSystemSolver { public: System(const std::string &projectName); private: MBSimFlexibleBody::FlexibleBodyLinearExternalFFR *test; }; #endif /* _SYSTEM_H */
[ "kgrundl@gmail.com@c123ba7f-e748-9643-39d5-9b7b2de17e7a" ]
kgrundl@gmail.com@c123ba7f-e748-9643-39d5-9b7b2de17e7a
ca8b6e51e5d3a3af26031114629f6229f6e48b99
0e9c066441c87fb9381b1d1f2084298a46fb4d33
/KeePass/WinGUI/Plugins/KpUtilitiesImpl.cpp
d452a21ba4cea12e8cd9b84053e406f80fd575e3
[ "MIT" ]
permissive
rrvt/KeePassLastPass
8c8207cc6cfb009a45220a404298a874c6317348
ea4b27a9e5e5fbd7220feb55aa2534cd3fe740be
refs/heads/main
2023-04-13T03:28:56.899812
2023-04-11T21:44:29
2023-04-11T21:44:29
422,981,282
0
1
null
null
null
null
UTF-8
C++
false
false
9,785
cpp
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2022 Dominik Reichl <dominik.reichl@t-online.de> 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "StdAfx.h" #include <tchar.h> #include <assert.h> #include "KpUtilitiesImpl.h" #include "../../KeePassLibCpp/PwManager.h" #include "../../KeePassLibCpp/Crypto/ARCFour.h" #include "../../KeePassLibCpp/Util/AppUtil.h" #include "../../KeePassLibCpp/Util/StrUtil.h" #include "../../KeePassLibCpp/Util/MemUtil.h" #include "../../KeePassLibCpp/Util/PwQualityEst.h" #include "../../KeePassLibCpp/Util/PwUtil.h" #include "../../KeePassLibCpp/Util/Base64.h" #include "../Util/WinUtil.h" #include "../Util/CmdLine/FullPathName.h" KP_IMPL_STDREFIMPL_NODELETE(CKpUtilitiesImpl) CKpUtilitiesImpl::CKpUtilitiesImpl() { KP_IMPL_CONSTRUCT; } CKpUtilitiesImpl& CKpUtilitiesImpl::Instance() { static CKpUtilitiesImpl singletonObject; return singletonObject; } STDMETHODIMP CKpUtilitiesImpl::QueryInterface(REFIID riid, void** ppvObject) { KP_REQ_OUT_PTR(ppvObject); KP_SUPPORT_INTERFACE(IID_IKpUnknown, IKpUnknown); KP_SUPPORT_INTERFACE(IID_IKpUtilities, IKpUtilities); *ppvObject = NULL; return E_NOINTERFACE; } STDMETHODIMP CKpUtilitiesImpl::ShowFileDialog(BOOL bOpenMode, LPCTSTR lpSuffix, LPTSTR lpStoreBuf, DWORD dwBufLen) { return ((WU_GetFileNameSz(bOpenMode, lpSuffix, lpStoreBuf, dwBufLen) == FALSE) ? E_ABORT : S_OK); } STDMETHODIMP_(char*) CKpUtilitiesImpl::UnicodeToMultiByte(const WCHAR* lpwString) { return _StringToAnsi(lpwString); } STDMETHODIMP_(WCHAR*) CKpUtilitiesImpl::MultiByteToUnicode(const char* lpString) { return _StringToUnicode(lpString); } STDMETHODIMP_(UTF8_BYTE*) CKpUtilitiesImpl::StringToUTF8(LPCTSTR lpSourceString) { return _StringToUTF8(lpSourceString); } STDMETHODIMP_(DWORD) CKpUtilitiesImpl::UTF8NumChars(const UTF8_BYTE* pUTF8String) { return _UTF8NumChars(pUTF8String); } STDMETHODIMP_(DWORD) CKpUtilitiesImpl::UTF8BytesNeeded(LPCTSTR lpString) { return _UTF8BytesNeeded(lpString); } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::UTF8ToString(const UTF8_BYTE* pUTF8String) { return _UTF8ToString(pUTF8String); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::IsUTF8String(const UTF8_BYTE* pUTF8String) { return _IsUTF8String(pUTF8String); } #pragma warning(push) #pragma warning(disable: 4996) // _tcscpy unsafe STDMETHODIMP CKpUtilitiesImpl::UuidToString(const BYTE* pUuid, LPTSTR lpOutBuf) { if((pUuid == NULL) || (lpOutBuf == NULL)) return E_POINTER; CString str; _UuidToString(pUuid, &str); _tcscpy(lpOutBuf, (LPCTSTR)str); return S_OK; } #pragma warning(pop) STDMETHODIMP CKpUtilitiesImpl::StringToUuid(LPCTSTR lpSource, BYTE* pUuid) { _StringToUuid(lpSource, pUuid); return S_OK; } STDMETHODIMP_(INT) CKpUtilitiesImpl::ShellOpenLocalFile(LPCTSTR lpFile, INT nMode) { return _OpenLocalFile(lpFile, nMode); } STDMETHODIMP CKpUtilitiesImpl::OpenUrl(LPCTSTR lpURL, HWND hParent) { if(lpURL == NULL) return E_POINTER; OpenUrlEx(lpURL, hParent); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::OpenAppHelp(LPCTSTR lpTopicFile) { return ((WU_OpenAppHelp(lpTopicFile, NULL) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP CKpUtilitiesImpl::Base64Encode(const BYTE* pbIn, DWORD cbInLen, BYTE* pbOut, DWORD* pcbOutLen) { if(pbIn == NULL) return E_POINTER; if(cbInLen == 0) return E_INVALIDARG; if((pbOut == NULL) || (pcbOutLen == NULL)) return E_POINTER; return (CBase64Codec::Encode(pbIn, cbInLen, pbOut, pcbOutLen) ? S_OK : E_FAIL); } STDMETHODIMP CKpUtilitiesImpl::Base64Decode(const BYTE* pbIn, DWORD cbInLen, BYTE* pbOut, DWORD* pcbOutLen) { if(pbIn == NULL) return E_POINTER; if(cbInLen == 0) return E_INVALIDARG; if((pbOut == NULL) || (pcbOutLen == NULL)) return E_POINTER; return (CBase64Codec::Decode(pbIn, cbInLen, pbOut, pcbOutLen) ? S_OK : E_FAIL); } STDMETHODIMP CKpUtilitiesImpl::GetApplicationDirectory(LPTSTR lpStoreBuf, DWORD dwBufLen, BOOL bFilterSpecial, BOOL bMakeURL) { if(lpStoreBuf == NULL) return E_POINTER; return ((AU_GetApplicationDirectory(lpStoreBuf, dwBufLen, bFilterSpecial, bMakeURL) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::MakeRelativePath(LPCTSTR lpBaseFile, LPCTSTR lpTargetFile) { if((lpBaseFile == NULL) || (lpTargetFile == NULL)) return NULL; CString str = MakeRelativePathEx(lpBaseFile, lpTargetFile); return _TcsSafeDupAlloc((LPCTSTR)str); } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::GetShortestAbsolutePath(LPCTSTR lpFilePath) { if(lpFilePath == NULL) return NULL; CString str = ::GetShortestAbsolutePath(lpFilePath); return _TcsSafeDupAlloc((LPCTSTR)str); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::IsAbsolutePath(LPCTSTR lpPath) { if(lpPath == NULL) return FALSE; return WU_IsAbsolutePath(lpPath); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::ValidatePath(LPCTSTR lpPath, DWORD dwOptions) { if(lpPath == NULL) return FALSE; std_string str = lpPath; const FullPathName fpn(str); if(fpn.getState() == FullPathName::INVALID_PATH) return FALSE; if((dwOptions & KPVPF_MUST_EXIST) != 0) { const DWORD dwAttrib = ::GetFileAttributes(lpPath); if(dwAttrib == INVALID_FILE_ATTRIBUTES) return FALSE; if(((dwOptions & KPVPF_TYPE_DIRECTORY) != 0) && ((dwAttrib & FILE_ATTRIBUTE_DIRECTORY) == 0)) return FALSE; if(((dwOptions & KPVPF_TYPE_FILE) != 0) && ((dwAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0)) return FALSE; } if((dwOptions & KPVPF_REGULAR_NAME) != 0) { LPCTSTR lpScan = lpPath; while(*lpScan != 0) { const TCHAR tch = *lpScan; if((tch == _T('<')) || (tch == _T('>')) || (tch == _T('\"')) || (tch == _T('/')) || (tch == _T('|')) || (tch == _T('?')) || (tch == _T('*'))) return FALSE; if((tch >= 0) && (tch <= 31)) return FALSE; ++lpScan; } } return TRUE; } STDMETHODIMP_(LPTSTR) CKpUtilitiesImpl::GetQuotedPath(LPCTSTR lpPath) { if(lpPath == NULL) return NULL; const std::basic_string<TCHAR> str = lpPath; const std::basic_string<TCHAR> strPath = SU_GetQuotedPath(str); return _TcsSafeDupAlloc(strPath.c_str()); } STDMETHODIMP CKpUtilitiesImpl::CreateDirectoryTree(LPCTSTR lpDirPath, DWORD dwOptions) { UNREFERENCED_PARAMETER(dwOptions); return WU_CreateDirectoryTree(lpDirPath); } STDMETHODIMP CKpUtilitiesImpl::FlushStorageBuffers(LPCTSTR lpFileOnStorage, BOOL bOnlyIfRemovable) { if(lpFileOnStorage == NULL) return E_POINTER; return ((WU_FlushStorageBuffersEx(lpFileOnStorage, bOnlyIfRemovable) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP CKpUtilitiesImpl::SecureDeleteFile(LPCTSTR lpFilePath) { if(lpFilePath == NULL) return E_POINTER; return ((AU_SecureDeleteFile(lpFilePath) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP CKpUtilitiesImpl::WriteFile(LPCTSTR lpFilePath, const BYTE* pData, DWORD dwDataSize) { if(lpFilePath == NULL) return E_POINTER; if(pData == NULL) return E_POINTER; const int nResult = AU_WriteBigFile(lpFilePath, pData, dwDataSize, FALSE); if(nResult == PWE_SUCCESS) return S_OK; if(nResult == PWE_NOFILEACCESS_WRITE) return E_ACCESSDENIED; return E_FAIL; } STDMETHODIMP_(INT) CKpUtilitiesImpl::CompareTimes(const PW_TIME* pTime1, const PW_TIME* pTime2) { if((pTime1 == NULL) || (pTime2 == NULL)) return 0; return _pwtimecmp(pTime1, pTime2); } STDMETHODIMP CKpUtilitiesImpl::HashFileSHA256(LPCTSTR lpFile, BYTE* pHashBuf) { if((lpFile == NULL) || (pHashBuf == NULL)) return E_POINTER; return ((SHA256_HashFile(lpFile, pHashBuf) == FALSE) ? E_FAIL : S_OK); } STDMETHODIMP_(DWORD) CKpUtilitiesImpl::EstimatePasswordBits(LPCTSTR lpPassword) { return CPwQualityEst::EstimatePasswordBits(lpPassword); } STDMETHODIMP_(BOOL) CKpUtilitiesImpl::IsTANEntry(const PW_ENTRY* pEntry) { return CPwUtil::IsTANEntry(pEntry); } STDMETHODIMP CKpUtilitiesImpl::SHA256CreateContext(void** pOutNewContext) { if(pOutNewContext == NULL) return E_POINTER; sha256_ctx* pContext = new sha256_ctx; sha256_begin(pContext); *pOutNewContext = pContext; return S_OK; } STDMETHODIMP CKpUtilitiesImpl::SHA256Init(void* pContext) { if(pContext == NULL) return E_POINTER; sha256_begin((sha256_ctx*)pContext); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::SHA256Hash(void* pContext, const BYTE* pData, DWORD dwDataLength) { if((pContext == NULL) || (pData == NULL)) return E_POINTER; sha256_hash(pData, dwDataLength, (sha256_ctx*)pContext); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::SHA256Final(void* pContext, BYTE* pOutHashBuf) { if((pContext == NULL) || (pOutHashBuf == NULL)) return E_POINTER; sha256_end(pOutHashBuf, (sha256_ctx*)pContext); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::EncryptMemory(BYTE* pbBuf, DWORD dwBufLen, const BYTE* pbKey, DWORD dwKeyLen) { if((pbBuf == NULL) || (pbKey == NULL)) return E_POINTER; ARCFourCrypt(pbBuf, dwBufLen, pbKey, dwKeyLen); return S_OK; } STDMETHODIMP CKpUtilitiesImpl::DecryptMemory(BYTE* pbBuf, DWORD dwBufLen, const BYTE* pbKey, DWORD dwKeyLen) { // ARCFour is self-inverse return CKpUtilitiesImpl::EncryptMemory(pbBuf, dwBufLen, pbKey, dwKeyLen); }
[ "rrvt@swde.com" ]
rrvt@swde.com
ef39a4f2774140b4d11cd79fdf8c8725981b50d5
2f685114f9dcf630673fc982380196ec0e4f8dd3
/ash/highlighter/highlighter_controller_unittest.cc
87368acad33cb182fa20c8d648cc35e127d7ceee
[ "BSD-3-Clause" ]
permissive
BitShekel/Tungsten
5ed9a6958f4d7147af42753ec6b85205394ce5fa
fd7caa325cbc10c6d88ce7e393d21c2e6941211c
refs/heads/master
2023-01-19T16:51:58.927691
2020-11-26T02:12:08
2020-11-26T02:12:08
133,874,738
0
0
null
null
null
null
UTF-8
C++
false
false
21,690
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 "ash/highlighter/highlighter_controller.h" #include <memory> #include "ash/components/fast_ink/fast_ink_points.h" #include "ash/highlighter/highlighter_controller_test_api.h" #include "ash/public/cpp/config.h" #include "ash/shell.h" #include "ash/system/palette/mock_palette_tool_delegate.h" #include "ash/system/palette/palette_tool.h" #include "ash/system/palette/tools/metalayer_mode.h" #include "ash/test/ash_test_base.h" #include "base/strings/stringprintf.h" #include "ui/aura/window_tree_host.h" #include "ui/compositor/test/draw_waiter_for_test.h" #include "ui/events/test/event_generator.h" namespace ash { namespace { class TestHighlighterObserver : public HighlighterController::Observer { public: TestHighlighterObserver() = default; ~TestHighlighterObserver() override = default; // HighlighterController::Observer: void OnHighlighterEnabledChanged(HighlighterEnabledState state) override { if (state == HighlighterEnabledState::kEnabled) { ++enabled_count_; } else if (state == HighlighterEnabledState::kDisabledByUser) { ++disabled_by_user_count_; } else { DCHECK_EQ(HighlighterEnabledState::kDisabledBySessionEnd, state); ++disabled_by_session_end_; } } int enabled_count_ = 0; int disabled_by_user_count_ = 0; int disabled_by_session_end_ = 0; private: DISALLOW_COPY_AND_ASSIGN(TestHighlighterObserver); }; class HighlighterControllerTest : public AshTestBase { public: HighlighterControllerTest() = default; ~HighlighterControllerTest() override = default; void SetUp() override { AshTestBase::SetUp(); controller_test_api_ = std::make_unique<HighlighterControllerTestApi>( Shell::Get()->highlighter_controller()); palette_tool_delegate_ = std::make_unique<MockPaletteToolDelegate>(); tool_ = std::make_unique<MetalayerMode>(palette_tool_delegate_.get()); } void TearDown() override { tool_.reset(); // This needs to be called first to reset the controller state before the // shell instance gets torn down. controller_test_api_.reset(); AshTestBase::TearDown(); } void UpdateDisplayAndWaitForCompositingEnded( const std::string& display_specs) { UpdateDisplay(display_specs); ui::DrawWaiterForTest::WaitForCompositingEnded( Shell::GetPrimaryRootWindow()->GetHost()->compositor()); } protected: void TraceRect(const gfx::Rect& rect) { GetEventGenerator().MoveTouch(gfx::Point(rect.x(), rect.y())); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(rect.right(), rect.y())); GetEventGenerator().MoveTouch(gfx::Point(rect.right(), rect.bottom())); GetEventGenerator().MoveTouch(gfx::Point(rect.x(), rect.bottom())); GetEventGenerator().MoveTouch(gfx::Point(rect.x(), rect.y())); GetEventGenerator().ReleaseTouch(); // The the events above will trigger a frame, so wait until a new // CompositorFrame is generated before terminating. ui::DrawWaiterForTest::WaitForCompositingEnded( Shell::GetPrimaryRootWindow()->GetHost()->compositor()); } std::unique_ptr<HighlighterControllerTestApi> controller_test_api_; std::unique_ptr<MockPaletteToolDelegate> palette_tool_delegate_; std::unique_ptr<PaletteTool> tool_; private: DISALLOW_COPY_AND_ASSIGN(HighlighterControllerTest); }; } // namespace // Test to ensure the class responsible for drawing the highlighter pointer // receives points from stylus movements as expected. TEST_F(HighlighterControllerTest, HighlighterRenderer) { // The highlighter pointer mode only works with stylus. GetEventGenerator().EnterPenPointerMode(); // When disabled the highlighter pointer should not be showing. GetEventGenerator().MoveTouch(gfx::Point(1, 1)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify that by enabling the mode, the highlighter pointer should still not // be showing. controller_test_api_->SetEnabled(true); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify moving the stylus 4 times will not display the highlighter pointer. GetEventGenerator().MoveTouch(gfx::Point(2, 2)); GetEventGenerator().MoveTouch(gfx::Point(3, 3)); GetEventGenerator().MoveTouch(gfx::Point(4, 4)); GetEventGenerator().MoveTouch(gfx::Point(5, 5)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify pressing the stylus will show the highlighter pointer and add a // point but will not activate fading out. GetEventGenerator().PressTouch(); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_FALSE(controller_test_api_->IsFadingAway()); EXPECT_EQ(1, controller_test_api_->points().GetNumberOfPoints()); // Verify dragging the stylus 2 times will add 2 more points. GetEventGenerator().MoveTouch(gfx::Point(6, 6)); GetEventGenerator().MoveTouch(gfx::Point(7, 7)); EXPECT_EQ(3, controller_test_api_->points().GetNumberOfPoints()); // Verify releasing the stylus still shows the highlighter pointer, which is // fading away. GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_TRUE(controller_test_api_->IsFadingAway()); // Verify that disabling the mode right after the gesture completion does not // hide the highlighter pointer immediately but lets it play out the // animation. controller_test_api_->SetEnabled(false); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_TRUE(controller_test_api_->IsFadingAway()); // Verify that disabling the mode mid-gesture hides the highlighter pointer // immediately. controller_test_api_->DestroyPointerView(); controller_test_api_->SetEnabled(true); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(6, 6)); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); controller_test_api_->SetEnabled(false); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify that the highlighter pointer does not add points while disabled. GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(8, 8)); GetEventGenerator().ReleaseTouch(); GetEventGenerator().MoveTouch(gfx::Point(9, 9)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); // Verify that the highlighter pointer does not get shown if points are not // coming from the stylus, even when enabled. GetEventGenerator().ExitPenPointerMode(); controller_test_api_->SetEnabled(true); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(10, 10)); GetEventGenerator().MoveTouch(gfx::Point(11, 11)); EXPECT_FALSE(controller_test_api_->IsShowingHighlighter()); GetEventGenerator().ReleaseTouch(); } // Test to ensure the class responsible for drawing the highlighter pointer // handles prediction as expected when it receives points from stylus movements. TEST_F(HighlighterControllerTest, HighlighterPrediction) { controller_test_api_->SetEnabled(true); // The highlighter pointer mode only works with stylus. GetEventGenerator().EnterPenPointerMode(); GetEventGenerator().PressTouch(); EXPECT_TRUE(controller_test_api_->IsShowingHighlighter()); EXPECT_EQ(1, controller_test_api_->points().GetNumberOfPoints()); // Initial press event shouldn't generate any predicted points as there's no // history to use for prediction. EXPECT_EQ(0, controller_test_api_->predicted_points().GetNumberOfPoints()); // Verify dragging the stylus 3 times will add some predicted points. GetEventGenerator().MoveTouch(gfx::Point(10, 10)); GetEventGenerator().MoveTouch(gfx::Point(20, 20)); GetEventGenerator().MoveTouch(gfx::Point(30, 30)); EXPECT_NE(0, controller_test_api_->predicted_points().GetNumberOfPoints()); // Verify predicted points are in the right direction. for (const auto& point : controller_test_api_->predicted_points().points()) { EXPECT_LT(30, point.location.x()); EXPECT_LT(30, point.location.y()); } } // Test that stylus gestures are correctly recognized by HighlighterController. TEST_F(HighlighterControllerTest, HighlighterGestures) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); // A non-horizontal stroke is not recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(200, 200)); GetEventGenerator().ReleaseTouch(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // An almost horizontal stroke is recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(300, 102)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); // Horizontal stroke selection rectangle should: // have the same horizontal center line as the stroke bounding box, // be 4dp wider than the stroke bounding box, // be exactly 14dp high. EXPECT_EQ("98,94 204x14", controller_test_api_->selection().ToString()); // An insufficiently closed C-like shape is not recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 0)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 0)); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().MoveTouch(gfx::Point(100, 100)); GetEventGenerator().ReleaseTouch(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // An almost closed G-like shape is recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(200, 0)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 0)); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().MoveTouch(gfx::Point(200, 100)); GetEventGenerator().MoveTouch(gfx::Point(200, 20)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("0,0 200x100", controller_test_api_->selection().ToString()); // A closed diamond shape is recognized controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(100, 50)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(200, 150)); GetEventGenerator().MoveTouch(gfx::Point(100, 250)); GetEventGenerator().MoveTouch(gfx::Point(0, 150)); GetEventGenerator().MoveTouch(gfx::Point(100, 50)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("0,50 200x200", controller_test_api_->selection().ToString()); } TEST_F(HighlighterControllerTest, HighlighterGesturesScaled) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); const gfx::Rect original_rect(200, 100, 400, 300); // Allow for rounding errors. gfx::Rect inflated(original_rect); inflated.Inset(-1, -1); constexpr float display_scales[] = {1.f, 1.5f, 2.0f}; constexpr float ui_scales[] = {0.5f, 0.67f, 1.0f, 1.25f, 1.33f, 1.5f, 1.67f, 2.0f}; for (size_t i = 0; i < sizeof(display_scales) / sizeof(float); ++i) { const float display_scale = display_scales[i]; for (size_t j = 0; j < sizeof(ui_scales) / sizeof(float); ++j) { const float ui_scale = ui_scales[j]; std::string display_spec = base::StringPrintf("1500x1000*%.2f@%.2f", display_scale, ui_scale); SCOPED_TRACE(display_spec); UpdateDisplayAndWaitForCompositingEnded(display_spec); controller_test_api_->ResetSelection(); TraceRect(original_rect); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); const gfx::Rect selection = controller_test_api_->selection(); EXPECT_TRUE(inflated.Contains(selection)); EXPECT_TRUE(selection.Contains(original_rect)); } } } // Test that stylus gesture recognition correctly handles display rotation TEST_F(HighlighterControllerTest, HighlighterGesturesRotated) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); const gfx::Rect trace(200, 100, 400, 300); // No rotation UpdateDisplayAndWaitForCompositingEnded("1500x1000"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("200,100 400x300", controller_test_api_->selection().ToString()); // Rotate to 90 degrees UpdateDisplayAndWaitForCompositingEnded("1500x1000/r"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("100,900 300x400", controller_test_api_->selection().ToString()); // Rotate to 180 degrees UpdateDisplayAndWaitForCompositingEnded("1500x1000/u"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("900,600 400x300", controller_test_api_->selection().ToString()); // Rotate to 270 degrees UpdateDisplayAndWaitForCompositingEnded("1500x1000/l"); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("600,200 300x400", controller_test_api_->selection().ToString()); } // Test that a stroke interrupted close to the screen edge is treated as // contiguous. TEST_F(HighlighterControllerTest, InterruptedStroke) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); UpdateDisplayAndWaitForCompositingEnded("1500x1000"); // An interrupted stroke close to the screen edge should be recognized as a // contiguous stroke. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(300, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); EXPECT_FALSE(controller_test_api_->IsFadingAway()); GetEventGenerator().MoveTouch(gfx::Point(0, 200)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(300, 200)); GetEventGenerator().ReleaseTouch(); EXPECT_FALSE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_EQ("0,100 300x100", controller_test_api_->selection().ToString()); // Repeat the same gesture, but simulate a timeout after the gap. This should // force the gesture completion. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(300, 100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(0, 100)); GetEventGenerator().ReleaseTouch(); EXPECT_TRUE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); EXPECT_FALSE(controller_test_api_->IsFadingAway()); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_FALSE(controller_test_api_->IsWaitingToResumeStroke()); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(controller_test_api_->IsFadingAway()); } // Test that the selection is never crossing the screen bounds. TEST_F(HighlighterControllerTest, SelectionInsideScreen) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); constexpr float display_scales[] = {1.f, 1.5f, 2.0f}; for (size_t i = 0; i < sizeof(display_scales) / sizeof(float); ++i) { std::string display_spec = base::StringPrintf("1000x1000*%.2f", display_scales[i]); SCOPED_TRACE(display_spec); UpdateDisplayAndWaitForCompositingEnded(display_spec); const gfx::Rect screen(0, 0, 1000, 1000); // Rectangle completely offscreen. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(-100, -100, 10, 10)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // Rectangle crossing the left edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(-100, 100, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Rectangle crossing the top edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(100, -100, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Rectangle crossing the right edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(900, 100, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Rectangle crossing the bottom edge. controller_test_api_->ResetSelection(); TraceRect(gfx::Rect(100, 900, 200, 200)); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Horizontal stroke completely offscreen. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(0, -100)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(1000, -100)); GetEventGenerator().ReleaseTouch(); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // Horizontal stroke along the top edge of the screen. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(0, 0)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(1000, 0)); GetEventGenerator().ReleaseTouch(); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); // Horizontal stroke along the bottom edge of the screen. controller_test_api_->ResetSelection(); GetEventGenerator().MoveTouch(gfx::Point(0, 999)); GetEventGenerator().PressTouch(); GetEventGenerator().MoveTouch(gfx::Point(1000, 999)); GetEventGenerator().ReleaseTouch(); controller_test_api_->SimulateInterruptedStrokeTimeout(); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); EXPECT_TRUE(screen.Contains(controller_test_api_->selection())); } } // Test that a detached client does not receive notifications. TEST_F(HighlighterControllerTest, DetachedClient) { controller_test_api_->SetEnabled(true); GetEventGenerator().EnterPenPointerMode(); UpdateDisplayAndWaitForCompositingEnded("1500x1000"); const gfx::Rect trace(200, 100, 400, 300); // Detach the client, no notifications should reach it. controller_test_api_->DetachClient(); controller_test_api_->ResetEnabledState(); controller_test_api_->SetEnabled(false); EXPECT_FALSE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->SetEnabled(true); EXPECT_FALSE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_FALSE(controller_test_api_->HandleSelectionCalled()); // Attach the client again, notifications should be delivered normally. controller_test_api_->AttachClient(); controller_test_api_->ResetEnabledState(); controller_test_api_->SetEnabled(false); EXPECT_TRUE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->SetEnabled(true); EXPECT_TRUE(controller_test_api_->HandleEnabledStateChangedCalled()); controller_test_api_->ResetSelection(); TraceRect(trace); EXPECT_TRUE(controller_test_api_->HandleSelectionCalled()); } // Test enabling/disabling metalayer mode by selecting/deselecting on palette // tool and calling UpdateEnabledState notify observers properly. TEST_F(HighlighterControllerTest, UpdateEnabledState) { HighlighterController* controller = Shell::Get()->highlighter_controller(); TestHighlighterObserver observer; controller->AddObserver(&observer); ASSERT_EQ(0, observer.enabled_count_); ASSERT_EQ(0, observer.disabled_by_user_count_); ASSERT_EQ(0, observer.disabled_by_session_end_); tool_->OnEnable(); EXPECT_EQ(1, observer.enabled_count_); EXPECT_EQ(0, observer.disabled_by_user_count_); EXPECT_EQ(0, observer.disabled_by_session_end_); tool_->OnDisable(); EXPECT_EQ(1, observer.enabled_count_); EXPECT_EQ(1, observer.disabled_by_user_count_); EXPECT_EQ(0, observer.disabled_by_session_end_); tool_->OnEnable(); EXPECT_EQ(2, observer.enabled_count_); EXPECT_EQ(1, observer.disabled_by_user_count_); EXPECT_EQ(0, observer.disabled_by_session_end_); controller->UpdateEnabledState( HighlighterEnabledState::kDisabledBySessionEnd); EXPECT_EQ(2, observer.enabled_count_); EXPECT_EQ(1, observer.disabled_by_user_count_); EXPECT_EQ(1, observer.disabled_by_session_end_); controller->RemoveObserver(&observer); } } // namespace ash
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a6b620657a6039399bd3a0225a7c6305d8d91ee9
966818603978f073d4f4ed85709ec1ad0c794be4
/INSIGHTV2_1_3/include/ACE_Wrappers/ace/OS_NS_arpa_inet.cpp
3d046c7bf28352c14246f4cb8bb11ff4a941b946
[]
no_license
lastvangogh/YANGZE
c337743e29dafadbfb1ed532f6c9ce35ce7f24df
870eb6066b360036a49ebe40bd9435cdd31ff5ac
refs/heads/master
2020-09-01T13:43:02.027589
2019-11-06T08:40:09
2019-11-06T08:40:09
218,970,441
0
0
null
null
null
null
UTF-8
C++
false
false
2,907
cpp
// -*- C++ -*- #include "ace/OS_NS_arpa_inet.h" #if !defined (ACE_HAS_INLINED_OSCALLS) # include "ace/OS_NS_arpa_inet.inl" #endif /* ACE_HAS_INLINED_OSCALLS */ #include "ace/Basic_Types.h" #include <cstdlib> ACE_BEGIN_VERSIONED_NAMESPACE_DECL int ACE_OS::inet_aton (const char *host_name, struct in_addr *addr) { #if defined (ACE_LACKS_INET_ATON) # if defined (ACE_WIN32) // Windows Server 2003 changed the behavior of a zero-length input // string to inet_addr(). It used to return 0 (INADDR_ANY) but now // returns -1 (INADDR_NONE). It will return INADDR_ANY for a 1-space // string, though, as do previous versions of Windows. if (host_name == 0 || host_name[0] == '\0') host_name = " "; # endif /* ACE_WIN32 */ # if defined (ACE_LACKS_INET_ADDR) if (!host_name) return 0; ACE_UINT32 ip = 0; int part = 0; for (const char *dot; *host_name; host_name = *dot ? dot + 1 : dot, ++part) { if (part > 3) return 0; dot = ACE_OS::strchr (host_name, '.'); if (!dot) dot = host_name + ACE_OS::strlen (host_name); char *last; const unsigned long n = std::strtoul (host_name, &last, 0); if (last != dot) return 0; if (!*dot) switch (part) { case 0: # if ACE_SIZEOF_LONG > 4 if (n > 0xffffffff) return 0; # endif ip = static_cast<ACE_UINT32> (n); continue; case 1: if (n > 0xffffff) return 0; ip <<= 24; ip |= n; continue; case 2: if (n > 0xffff) return 0; ip <<= 16; ip |= n; continue; } if (n > 0xff) return 0; ip <<= 8; ip |= n; } addr->s_addr = ACE_HTONL (ip); return 1; # else unsigned long ip_addr = ACE_OS::inet_addr (host_name); if (ip_addr == INADDR_NONE // Broadcast addresses are weird... && ACE_OS::strcmp (host_name, "255.255.255.255") != 0) return 0; else if (addr == 0) return 0; else { addr->s_addr = ip_addr; // Network byte ordered return 1; } # endif // ACE_LACKS_INET_ADDR #elif defined (ACE_VXWORKS) && (ACE_VXWORKS <= 0x690) // inet_aton() returns OK (0) on success and ERROR (-1) on failure. // Must reset errno first. Refer to WindRiver SPR# 34949, SPR# 36026 ::errnoSet(0); int result = ERROR; ACE_OSCALL (::inet_aton (const_cast <char*>(host_name), addr), int, ERROR, result); return (result == ERROR) ? 0 : 1; #else // inet_aton() returns 0 upon failure, not -1 since -1 is a valid // address (255.255.255.255). ACE_OSCALL_RETURN (::inet_aton (host_name, addr), int, 0); #endif /* ACE_LACKS_INET_ATON */ } ACE_END_VERSIONED_NAMESPACE_DECL
[ "zhangzhuo@yangzeinvest.com" ]
zhangzhuo@yangzeinvest.com
79bf5485d5fe4e7f7f47d4a8d2f20ae20505eb0b
4b99e2c54be595e3fa107e59c5da9a2bfa632531
/NativeLogic/src/GameLogic/MetalOrb.h
770df748e76b7b54f60aed6996a019c409d719f4
[]
no_license
SE346-H11-NT/Project
f0789a6896b47a5e358458eb430c67e15c1e6890
a1038d9f6104df5096a57e5a289233a603f3b7a7
refs/heads/master
2020-08-03T19:10:01.653852
2016-12-25T16:59:43
2016-12-25T16:59:43
73,538,873
0
0
null
null
null
null
UTF-8
C++
false
false
761
h
#ifndef MetalOrb_h__ #define MetalOrb_h__ #include "Mobs.h" #define METAL_ORB_BOUND_SIZE Size(16.0F, 16.0F) #define METAL_ORB_RESOURCE_LINK (tstring(_T("Resource//Bosses//ShadowEntrance//MetalOrb")) + EXTENSION_PICTURE) #define METAL_ORB_RESOURCE_ROWS 1 #define METAL_ORB_RESOURCE_COLUMNS 1 class MetalOrb : public Mobs { public: MetalOrb(){} MetalOrb(T6Vec3 position); virtual ~MetalOrb(); virtual unsigned int getScore(); virtual void waitUpdate(); virtual void activateUpdate(); virtual void deadUpdate(); virtual bool affect(Object* obj, DWORD key); virtual void setBasicProperties(); virtual void deadEffect(); void setPos(T6Vec3 newPos); virtual void draw(); }; #endif // MetalOrb_h__
[ "tranminhtuan11a1@gmail.com" ]
tranminhtuan11a1@gmail.com
4ba411b8aec7235aee157a1ab5700da8a96e0a80
6198a19968f36832cdeed2721f09bd9146e55d3f
/Linkit7697_RobotShieldV2_TANK_GO_MP3_V410/Linkit7697_RobotShieldV2_TANK_GO_MP3_V410.ino
52221a7b7899bde2903763983f611d2d5c3593cb
[]
no_license
GeorgeChiou/Robot-Shield-V2.0
3ba3b2612148353fa29968fd9a325db6dd1bc2eb
04549a8a0c7a9fec60240f8116baeb80a843eadd
refs/heads/master
2021-05-01T13:09:37.452676
2020-01-01T09:16:11
2020-01-01T09:16:11
121,072,400
16
5
null
null
null
null
UTF-8
C++
false
false
20,440
ino
// 最後編輯 2019-5-08 by ShinWei Chiou // 移除 搖桿 提供比賽 // 中文化 提供比賽 // 最後編輯 2019-5-06 by ShinWei Chiou // 移除 修復按鈕 提供比賽 // 最後編輯 2018-4-18 by ShinWei Chiou // 搖桿控制 LRemoteJoyStick // 最後編輯 2018-4-15 by ShinWei Chiou // 橫向控制 Change to Use RC_LANDSCAPE // 最後編輯 2018-4-02 by Mason // Add tank_name = "TANK"+ tank_address.substring(0,2) +tank_address.substring(3,5); // 最後編輯 2018-3-27 by ShinWei Chiou // DFPlayer mini mp3 module. // github as default source provider // https://github.com/DFRobot/DFPlayer-Mini-mp3 // For Linkit-7697 + Robot Shield V2.1 // Left Motor : P10 P12,Right Motor : P13 P17 // Servo : P5 // Buzzer : P14 // IR Test Button : P6 // IR Receiver : P9 // IR LED : P11 , P15 // DFplayer TX : P4 #include <Servo.h> #include <LRemote.h> #include <SoftwareSerial.h> #define Right_Wheel_A 12 #define Right_Wheel_B 10 #define Left_Wheel_A 17 #define Left_Wheel_B 13 #define Buzzer_Pin 14 #define Servo_Pin 5 #define IR_LED_Pin1 11 #define IR_LED_Pin2 15 #define IR_Button_Pin 6 #define IR_Receiver_Pin 9 // DFplayer #include <DFPlayer_Mini_Mp3.h> // On LinkIt 7697, the RX pin must be one of the EINT pins. // There are no limitations on TX pin. SoftwareSerial mp3Serial(2, 4); // RX, TX // Label LRemoteLabel Titlelabel; LRemoteLabel HPlabelT; LRemoteLabel HPlabelS; LRemoteLabel AMlabelT; LRemoteLabel AMlabelS; // JoyStick LRemoteJoyStick joystickDirection; // Button LRemoteButton forwardbutton; LRemoteButton backwardbutton; LRemoteButton turnleftbutton; LRemoteButton turnrightbutton; LRemoteButton firebutton; LRemoteButton reloadbutton; LRemoteButton repairsbutton; LRemoteSlider turretslider; LRemoteButton turretcenterbutton; LRemoteButton musicbutton1; LRemoteButton musicbutton2; LRemoteButton musicbutton3; LRemoteButton musicbutton4; LRemoteButton musicbutton5; LRemoteButton musicbutton6; LRemoteButton musicbutton7; LRemoteButton musicbutton8; LRemoteButton volmaxbutton; LRemoteButton volminbutton; LRemoteButton mutebutton; // Servo const int TurretTurnCenter = 90; const int TurretTurnMax = 160; const int TurretTurnMin = 10; int Turret_Turn_Value = TurretTurnCenter; // IR Battle System const int Damage_Value = 25; const int Tank_AM_MaxValue = 5; int Tank_HP_Value = 100; int Tank_AM_Value = Tank_AM_MaxValue; int IR_Value = 0; // Music const int VolumeMax = 30; const int VolumeMin = 5; int Volume_Value = 15; // Create Servo object Servo TurretServo; /*------------------------------------------------------------*/ // IR Send Code 38kHz void IR_Send_Code_1() { for (int i16t = 0; i16t < 16; i16t++) { for (int i37k = 0; i37k < 125; i37k++) { digitalWrite(IR_LED_Pin1, HIGH); delayMicroseconds(12); digitalWrite(IR_LED_Pin1, LOW); delayMicroseconds(12); } delay(2); } } void IR_Send_Code_2() { for (int i16t = 0; i16t < 16; i16t++) { for (int i37k = 0; i37k < 125; i37k++) { digitalWrite(IR_LED_Pin2, HIGH); delayMicroseconds(12); digitalWrite(IR_LED_Pin2, LOW); delayMicroseconds(12); } delay(2); } } /*------------------------------------------------------------*/ // Ray Gun Sound void Ray_Gun_Sound() { for (int i = 0; i < 300; i++) { digitalWrite(Buzzer_Pin, HIGH); delayMicroseconds(i); digitalWrite(Buzzer_Pin, LOW); delayMicroseconds(i); } } /*------------------------------------------------------------*/ void Move_Forward() { digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, HIGH); } void Move_Backward() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, LOW); } void Move_TurnRight() { digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, LOW); } void Move_TurnLeft() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, HIGH); } void Motor_Break() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(13, HIGH); delay(100); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, LOW); } void Move_Fire() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(13, LOW); delay(50); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, LOW); digitalWrite(13, HIGH); delay(50); digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, HIGH); } void Move_Damage() { digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, LOW); delay(100); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, HIGH); delay(100); digitalWrite(Right_Wheel_A, HIGH); digitalWrite(Right_Wheel_B, HIGH); digitalWrite(Left_Wheel_A, HIGH); digitalWrite(Left_Wheel_B, HIGH); delay(50); digitalWrite(Right_Wheel_A, LOW); digitalWrite(Right_Wheel_B, LOW); digitalWrite(Left_Wheel_A, LOW); digitalWrite(Left_Wheel_B, LOW); TurretServo.write(60); delay(300); TurretServo.write(120); delay(300); TurretServo.write(Turret_Turn_Value); delay(300); } /*------------------------------------------------------------*/ void SteerDirection(int x, int y) { const int x_termP = 50; const int x_termN = -50; const int y_termP = 10; const int y_termN = -10; if (y > y_termP ) { if (x >= x_termP) { Move_TurnRight(); } else if (x <= x_termN) { Move_TurnLeft(); } else { Move_Forward(); } } else if (y < y_termN) { if (x >= x_termP) { Move_TurnRight(); } else if (x <= x_termN) { Move_TurnLeft(); } else { Move_Backward(); } } else { if (x >= x_termP) { Move_TurnRight(); } else if (x <= x_termN) { Move_TurnLeft(); } else { Motor_Break(); } } } /*------------------------------------------------------------*/ void setup() { // Initialize serial communications at 9600 bps: Serial.begin(9600); // Set the data rate for the SoftwareSerial port mp3Serial.begin(9600); // Add for DFplayer mp3_set_serial (mp3Serial); // set Serial for DFPlayer-mini mp3 module // Motor PIN Set pinMode(10, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); pinMode(17, OUTPUT); // IR PIN Set pinMode(IR_Receiver_Pin, INPUT); pinMode(IR_Button_Pin, INPUT); pinMode(IR_LED_Pin1, OUTPUT); pinMode(IR_LED_Pin2, OUTPUT); // Initialize Servo TurretServo.attach(Servo_Pin); TurretServo.write(90); // Initialize BLE subsystem & get BLE address LBLE.begin(); while (!LBLE.ready()) { delay(100); } Serial.print("Device Address = ["); LBLEAddress ble_address; String tank_address; ble_address = LBLE.getDeviceAddress(); tank_address = ble_address.toString(); Serial.print(tank_address); Serial.println("]"); String tank_name; tank_name = "TANK" + tank_address.substring(0, 2) + tank_address.substring(3, 5); // Setup the Remote Control's Name LRemote.setName(tank_name); // Setup the Remote Control's UI canvas LRemote.setOrientation(RC_LANDSCAPE); LRemote.setGrid(16, 9); // Add a text Title label Titlelabel.setText("Infrared Battle Tank V4.1"); Titlelabel.setPos(2, 0); Titlelabel.setSize(14, 1); Titlelabel.setColor(RC_GREY); LRemote.addControl(Titlelabel); // Add a text HP label HPlabelT.setText("血量"); HPlabelT.setPos(0, 1); HPlabelT.setSize(2, 1); HPlabelT.setColor(RC_GREY); LRemote.addControl(HPlabelT); HPlabelS.setText("100%"); HPlabelS.setPos(0, 2); HPlabelS.setSize(2, 1); HPlabelS.setColor(RC_GREY); LRemote.addControl(HPlabelS); // Add a text AMMO label AMlabelT.setText("彈量"); AMlabelT.setPos(5, 1); AMlabelT.setSize(2, 1); AMlabelT.setColor(RC_GREY); LRemote.addControl(AMlabelT); AMlabelS.setText(String(Tank_AM_Value, 10)); AMlabelS.setPos(5, 2); AMlabelS.setSize(2, 1); AMlabelS.setColor(RC_GREY); LRemote.addControl(AMlabelS); // Add Joystick Direction //joystickDirection.setPos(0, 3); //joystickDirection.setSize(7, 6); //joystickDirection.setColor(RC_BLUE); //LRemote.addControl(joystickDirection); // Add a Forward button forwardbutton.setText("前進"); forwardbutton.setPos(2, 3); forwardbutton.setSize(3, 3); forwardbutton.setColor(RC_BLUE); LRemote.addControl(forwardbutton); // Add a Backward button backwardbutton.setText("後退"); backwardbutton.setPos(2, 6); backwardbutton.setSize(3, 3); backwardbutton.setColor(RC_BLUE); LRemote.addControl(backwardbutton); // Add a TurnLeft button turnleftbutton.setText("左轉"); turnleftbutton.setPos(0, 4); turnleftbutton.setSize(2, 4); turnleftbutton.setColor(RC_BLUE); LRemote.addControl(turnleftbutton); // Add a TurnRight button turnrightbutton.setText("右轉"); turnrightbutton.setPos(5, 4); turnrightbutton.setSize(2, 4); turnrightbutton.setColor(RC_BLUE); LRemote.addControl(turnrightbutton); // Add a Reload button reloadbutton.setText("塡彈"); reloadbutton.setPos(13, 1); reloadbutton.setSize(3, 2); reloadbutton.setColor(RC_GREEN); LRemote.addControl(reloadbutton); // Add a Fire button firebutton.setText("發射"); firebutton.setPos(13, 3); //firebutton.setSize(3, 4); firebutton.setSize(3, 6); firebutton.setColor(RC_PINK); LRemote.addControl(firebutton); // Add a Repairs button //repairsbutton.setText("REPAIRS"); //repairsbutton.setPos(13, 7); //repairsbutton.setSize(3, 2); //repairsbutton.setColor(RC_GREEN); //LRemote.addControl(repairsbutton); // Add a Turret center button turretcenterbutton.setText("砲塔回正"); turretcenterbutton.setPos(2, 1); turretcenterbutton.setSize(3, 2); turretcenterbutton.setColor(RC_ORANGE); LRemote.addControl(turretcenterbutton); // Add a Turret slider turretslider.setText("砲塔旋轉"); turretslider.setPos(7, 6); turretslider.setSize(6, 3); turretslider.setColor(RC_ORANGE); turretslider.setValueRange(TurretTurnMin, TurretTurnMax, TurretTurnCenter); LRemote.addControl(turretslider); // Add a Music button musicbutton1.setText("♫1"); musicbutton1.setPos(8, 1); musicbutton1.setSize(2, 1); musicbutton1.setColor(RC_GREY); LRemote.addControl(musicbutton1); musicbutton2.setText("♫2"); musicbutton2.setPos(8, 2); musicbutton2.setSize(2, 1); musicbutton2.setColor(RC_GREY); LRemote.addControl(musicbutton2); musicbutton3.setText("♫3"); musicbutton3.setPos(8, 3); musicbutton3.setSize(2, 1); musicbutton3.setColor(RC_GREY); LRemote.addControl(musicbutton3); musicbutton4.setText("♫4"); musicbutton4.setPos(8, 4); musicbutton4.setSize(2, 1); musicbutton4.setColor(RC_GREY); LRemote.addControl(musicbutton4); musicbutton5.setText("♫5"); musicbutton5.setPos(10, 1); musicbutton5.setSize(2, 1); musicbutton5.setColor(RC_GREY); LRemote.addControl(musicbutton5); musicbutton6.setText("♫6"); musicbutton6.setPos(10, 2); musicbutton6.setSize(2, 1); musicbutton6.setColor(RC_GREY); LRemote.addControl(musicbutton6); musicbutton7.setText("♫7"); musicbutton7.setPos(10, 3); musicbutton7.setSize(2, 1); musicbutton7.setColor(RC_GREY); LRemote.addControl(musicbutton7); musicbutton8.setText("♫8"); musicbutton8.setPos(10, 4); musicbutton8.setSize(2, 1); musicbutton8.setColor(RC_GREY); LRemote.addControl(musicbutton8); volmaxbutton.setText("大聲"); volmaxbutton.setPos(8, 5); volmaxbutton.setSize(2, 1); volmaxbutton.setColor(RC_GREY); LRemote.addControl(volmaxbutton); volminbutton.setText("小聲"); volminbutton.setPos(10, 5); volminbutton.setSize(2, 1); volminbutton.setColor(RC_GREY); LRemote.addControl(volminbutton); mutebutton.setText("靜音"); mutebutton.setPos(0, 0); mutebutton.setSize(2, 1); mutebutton.setColor(RC_GREY); LRemote.addControl(mutebutton); // Start broadcasting our remote contoller LRemote.begin(); Serial.println("LRemote begin ..."); } /*------------------------------------------------------------*/ void loop() { // BLE central device, e.g. an mobile app if (!LRemote.connected()) { Serial.println("Waiting for connection ..."); delay(10); } else { delay(10); } // Process the incoming BLE write request LRemote.process(); // Tank HP Limit if (Tank_HP_Value >= 1) { /*----------------------------------*/ // Move //if (joystickDirection.isValueChanged()) //{ // auto dir = joystickDirection.getValue(); // // Serial.println(dir); // // SteerDirection(dir.x, dir.y); //} if (forwardbutton.getValue()) { Move_Forward(); } else if (backwardbutton.getValue()) { Move_Backward(); } else if (turnleftbutton.getValue()) { Move_TurnLeft(); } else if (turnrightbutton.getValue()) { Move_TurnRight(); } else { Motor_Break(); } /*----------------------------------*/ // Turret if (turretcenterbutton.isValueChanged()) { if (turretcenterbutton.getValue() == 1) { Turret_Turn_Value = TurretTurnCenter; TurretServo.write(TurretTurnCenter); delay(100); } } if (turretslider.isValueChanged()) { Titlelabel.updateText("Tank Go!"); Turret_Turn_Value = 180 - turretslider.getValue(); TurretServo.write(Turret_Turn_Value); } /*----------------------------------*/ // Fire if (firebutton.isValueChanged()) { if (firebutton.getValue() == 1) { if ( Tank_AM_Value >= 1) { mp3_set_volume (Volume_Value); delay(10); mp3_play (1); Titlelabel.updateText("!!! FIRE !!!"); Tank_AM_Value--; IR_Send_Code_1(); IR_Send_Code_2(); Move_Fire(); delay (700); mp3_stop (); } if ( Tank_AM_Value <= 0) { Titlelabel.updateText("!!! Reload !!!"); } AMlabelS.updateText(String(Tank_AM_Value, 10)); Serial.print("Tank_AT_Value = "); Serial.println(Tank_AM_Value); } else { Motor_Break(); } } /*----------------------------------*/ // Reload if (reloadbutton.isValueChanged()) { if (reloadbutton.getValue() == 1) { if ( Tank_AM_Value < Tank_AM_MaxValue) { mp3_set_volume (Volume_Value); delay(10); mp3_play (3); Titlelabel.updateText("Please Wait ..."); for (int iAM = Tank_AM_Value; iAM <= Tank_AM_MaxValue; iAM++) { Tank_AM_Value = iAM; AMlabelS.updateText(String(Tank_AM_Value, 10)); delay(200); } Titlelabel.updateText("Completed !"); Serial.println("Reload Tank_AT_Value"); delay(100); mp3_stop (); } else { Titlelabel.updateText("Full Ammo !"); } } } } /*----------------------------------*/ // IR Test Button if (digitalRead(IR_Button_Pin) == HIGH) { IR_Send_Code_1(); Ray_Gun_Sound(); IR_Send_Code_2(); Serial.println("IR Send Test Code"); } /*----------------------------------*/ // IR Battle System if (digitalRead(IR_Receiver_Pin) == LOW) { IR_Value = pulseIn(IR_Receiver_Pin, LOW); if ( IR_Value >= 2700 && IR_Value <= 3400 ) { mp3_set_volume (Volume_Value); delay(10); mp3_play (2); delay (100); Titlelabel.updateText("Damage !"); if ( Tank_HP_Value >= 1) { Tank_HP_Value = Tank_HP_Value - Damage_Value; Move_Damage(); } if ( Tank_HP_Value <= Damage_Value) { Titlelabel.updateText("!!! Repairs !!!"); } HPlabelS.updateText(String(Tank_HP_Value, 10) + "%"); Serial.print("IR_Value = "); Serial.print(IR_Value); Serial.print(" , Tank_HP_Value = "); Serial.println(Tank_HP_Value); delay (100); mp3_stop (); } } /*----------------------------------*/ // Repairs if (repairsbutton.isValueChanged()) { if (repairsbutton.getValue() == 1) { if ( Tank_HP_Value < 100) { mp3_set_volume (Volume_Value); delay(10); mp3_play (4); Titlelabel.updateText("Please Wait ..."); for (int iHP = Tank_HP_Value; iHP <= 100; iHP++) { Tank_HP_Value = iHP; HPlabelS.updateText(String(Tank_HP_Value, 10) + "%"); delay(20); } Titlelabel.updateText("Completed !"); Serial.println("Repair Tank_HP_Value"); delay(100); mp3_stop (); } else { Titlelabel.updateText("No Damage !"); } } } /*----------------------------------*/ // Mute Music if (mutebutton.isValueChanged()) { if (mutebutton.getValue() == 1) { Titlelabel.updateText("!!! Mute !!!"); mp3_stop (); } } // Adjust Volume Music if (volmaxbutton.isValueChanged()) { if (volmaxbutton.getValue() == 1) { if (Volume_Value < 30) { Volume_Value = Volume_Value + 5; Titlelabel.updateText("Volume = " + String(Volume_Value, 10)); mp3_set_volume (Volume_Value); delay(10); } else { Titlelabel.updateText("Volume = Max"); } } } if (volminbutton.isValueChanged()) { if (volminbutton.getValue() == 1) { if (Volume_Value > 5) { Volume_Value = Volume_Value - 5; Titlelabel.updateText("Volume = " + String(Volume_Value, 10)); mp3_set_volume (Volume_Value); delay(10); } else { Titlelabel.updateText("Volume = Min"); } } } /*----------------------------------*/ // Play Music 1 if (musicbutton1.isValueChanged()) { if (musicbutton1.getValue() == 1) { Titlelabel.updateText("Katyusha"); mp3_set_volume (Volume_Value); delay(10); mp3_play (10); } } // Play Music 2 if (musicbutton2.isValueChanged()) { if (musicbutton2.getValue() == 1) { Titlelabel.updateText("Panzerlied"); mp3_set_volume (Volume_Value); delay(10); mp3_play (11); } } // Play Music 3 if (musicbutton3.isValueChanged()) { if (musicbutton3.getValue() == 1) { Titlelabel.updateText("Marching"); mp3_set_volume (Volume_Value); delay(10); mp3_play (12); } } // Play Music 4 if (musicbutton4.isValueChanged()) { if (musicbutton4.getValue() == 1) { Titlelabel.updateText("Engine Start !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (13); } } // Play Music 5 if (musicbutton5.isValueChanged()) { if (musicbutton5.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (14); } } // Play Music 6 if (musicbutton6.isValueChanged()) { if (musicbutton6.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (15); } } // Play Music 7 if (musicbutton7.isValueChanged()) { if (musicbutton7.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (16); } } // Play Music 8 if (musicbutton8.isValueChanged()) { if (musicbutton8.getValue() == 1) { Titlelabel.updateText("No File !"); mp3_set_volume (Volume_Value); delay(10); mp3_play (17); } } }
[ "shinwei@iMac-4072.local" ]
shinwei@iMac-4072.local
68044e1b9135c455a0053b9d059b8c6a8a65a193
65abf609c59993d49b12dfbaa8d1665f4cfc2208
/test/alpha_svr/phxrpc_alphasvr_tool.cpp
71c935596da5e6e3fdd1b665cf2879c0e3106d81
[]
no_license
brandongbyd/phxrpctest
4244bbd89c987bd29bdede01f5f921d5d909adca
feb0203382925a7aca51964edfd112ab7f615a6c
refs/heads/master
2020-07-17T22:12:40.810679
2019-09-03T16:23:43
2019-09-03T16:23:43
206,110,381
2
0
null
null
null
null
UTF-8
C++
false
false
745
cpp
/* phxrpc_alphasvr_tool.cpp Generated by phxrpc_pb2tool from alpha_svr.proto Please DO NOT edit unless you know exactly what you are doing. */ #include "phxrpc_alphasvr_tool.h" #include "phxrpc/file.h" #include "alphasvr_client.h" using namespace phxrpc; AlphaSvrTool::AlphaSvrTool() { } AlphaSvrTool::~AlphaSvrTool() { } int AlphaSvrTool::PHXEcho(phxrpc::OptMap &/* opt_map */) { printf("\n *** PHXEcho unimplement ***\n"); return -1; } int AlphaSvrTool::AddTwoDigits(phxrpc::OptMap &/* opt_map */) { printf("\n *** AddTwoDigits unimplement ***\n"); return -1; } int AlphaSvrTool::AddSomeDigits(phxrpc::OptMap &/* opt_map */) { printf("\n *** AddSomeDigits unimplement ***\n"); return -1; }
[ "brandong@foxmail.xom" ]
brandong@foxmail.xom
3db8a68b433891379fc8804f5949ef73a2268a34
1c4108ffbfe03be4d4b1914775192750af930e29
/src/texture_handler.cpp
a3323e5bcbdf00c83280893086d4b212796ccbf9
[]
no_license
tropuq/SFMLVisualizer
659f04d1bd6ea3cdd1c15ef6a2fd29a7cda0fc90
07dd3b844edc2c71ce62cee5f16a4b594c2a2132
refs/heads/master
2020-03-10T22:00:23.046059
2018-10-26T11:04:20
2018-10-26T11:04:20
129,608,059
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
#include "../include/texture_handler.h" #include <cassert> #include <iostream> using namespace sf; using namespace std; TextureHandler::TextureHandler(const string &dir) { icon_directory = dir; } Texture* TextureHandler::getTexture(const string &name) { if (mp.find(name) == mp.end()) assert(mp[name].loadFromFile(icon_directory + '/' + name)); return &mp[name]; }
[ "niciejewski98@gmail.com" ]
niciejewski98@gmail.com
fab97f754f579937b6d529b3b76feec16e064ca8
33c12d0d070363dec10a3c79d1fc85d41cd8939c
/BCIREBORN/L_Utilities/Stack16.h
823209487ca1ad990cbb4ebd12e5dcb5375c2250
[]
no_license
jwnicholas99/Brain-Computer-Interface-for-Detection-of-Emotions
ca0e4748a08b301f268a14fb03ec07819fed86ce
8efb4c116fa4d47f5fe73e15000d97492c747d2c
refs/heads/master
2020-04-18T15:13:21.289269
2019-01-28T04:39:33
2019-01-28T04:39:33
167,564,848
0
0
null
null
null
null
UTF-8
C++
false
false
2,660
h
/* File: Stack16.h Description: Stack class definition header file. This module contains the class definition and member function definitions for supporting dynamic list objects with 16 bit labels. */ #ifndef rStack16_H #define rStack16_H #include "ConstDef.h" class Stack16; typedef Stack16 * Stack16P; // Class definition class Stack16 { public: Stack16 (long inCount = 50, long growCount = 0); ~Stack16 (void); long MemoryUsage (void); void Clear (void); long Push (Ptr16 item); Ptr16 Pop (void); Ptr16 Get (long index); void Set (long index, Ptr16 item); void Insert (long index, Ptr16 item); Stack16 * Copy (Stack16 * inList = NULL); Ptr16 First (void) { return Get (0); } Ptr16 Last (void) { return Get (fCount - 1); } long GetLength (void) { return fCount; } long GetCount (void) { return fCount; } Ptr16 * GetStorage (void) { return fStorage; } private: long fCount; long fMaxCount; long fGrowCount; long fRange; Ptr16 * fStorage; }; /*=============================================================================== Public Functions Stack (long inCount, long growCount = 0) Constructor. Makes an instance of an Stack and returns it. The initial size of the list as well as the grow size (for expanding the list) are user-specifiable. ~Stack (void) Destructor MemoryUsage (void) Returns the memory used by the dynamic list. Clear (void) Clears the list for reuse by reseting it's count index to 0. Copy (Stack * inList = NULL) Returns a copy of the list. If the optional inList is provided, copies the list into inList, and returns it. Push (Ptr16 item) Pushes an item onto the end of the list. Allocates more memory if necessary using fGrowCount. Pop (void) Pops an item off the end of the list, and returns. The item will no longer be on the list. Get (long index) Returns the item at index. If index is beyond range, returns kNoItem. Set (long index, Ptr16 item) Places the item in the list at location provided by index. Insert (long index, Ptr16 item) Inserts an item in the list. Pushes other items down, allocating more memory if necessary. First (void) Returns the first item on the list. Last (void) Returns the last item on the list. Length (void) Returns the length of the list. Count (void) Same as Count (). ===============================================================================*/ #endif // rStack_H
[ "jwnicholas99@gmail.com" ]
jwnicholas99@gmail.com
9231be6a36383b9579e83435371c9f0e4b0e42ea
8559edef3b57407ac5d11cb23df68b50b07b7911
/Best_Online Judge solution/Code force online judge/Game.cpp
1522d16b86c4e4c13c1aecbbf5889b12725ec5b1
[]
no_license
mijanur-rahman-40/C-C-plus-plus-Online-Judge-Algorithms-Practise-Programming
2a031b0743356ba4c8670623aaa87b57f0b43f27
254924e4bd890e2f6d434abcc9ef52ef3e209211
refs/heads/master
2023-02-13T06:26:20.422678
2021-01-13T14:20:21
2021-01-13T14:20:21
329,330,528
1
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
#include<bits/stdc++.h> using namespace std; int main() { int num; scanf("%d",&num); int arr[num]; for(int i=0; i<num; i++){ scanf("%d",&arr[i]); } sort(arr,arr+num); cout<<arr[(num-1)/2]<<endl; }
[ "mijanurrahman31416@gmail.com" ]
mijanurrahman31416@gmail.com
70659e403193818370c9763e57277954fec8e5aa
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/位运算初步/P4310.cpp
0b58d89b62abb458ada97dd206dff6fcb1c9c616
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
#include<iostream> #define MAXN 100010 #define MAX 65 using namespace std; int f[MAXN][MAX],a[MAXN],n=0,ans=0; int main() { register int i=0,j=0,k=0; cin>>n; for(i=1;i<=n;++i) { cin>>a[i]; } for(i=1;i<=n;++i) { for(j=0;j<MAX;++j) { if(a[i]>>j&1) { for(k=0;k<MAX;++k) { if(a[i]>>k&1) { f[i][j]=max(f[i][j],f[i-1][k]); } } ++f[i][j]; } else { f[i][j]=f[i-1][j]; } } } for(i=0;i<MAX;++i) { ans=max(ans,f[n][i]); } cout<<ans<<endl; return 0; }
[ "3305049949@qq.com" ]
3305049949@qq.com
1574a77a78057e2c32b6bc1f241ad1d8568521d4
43a9f64427158c5bec8e9ce60233ba91b8c55f3e
/samples/DockContainer/src/Classes.cpp
eda206ed74a7a59f4167c3928e14a3f8b41d4919
[]
no_license
CCCCCCCCZ/Win32xx
7e8647b74eaca47ef80cadd76d68dc036dabe709
2ef27b55e05931ebabf931f133387bc046f888dc
refs/heads/master
2020-06-07T13:29:41.006512
2019-06-22T07:33:53
2019-06-22T07:33:53
193,032,614
0
1
null
null
null
null
UTF-8
C++
false
false
5,703
cpp
/////////////////////////////////////////////////// // Classes.cpp - Definitions for the CViewClasses, CContainClasses // and CDockClasses classes #include "stdafx.h" #include "Classes.h" #include "ContainerApp.h" #include "resource.h" /////////////////////////////////////////////// // CViewClasses functions CViewClasses::CViewClasses() { } CViewClasses::~CViewClasses() { if (IsWindow()) DeleteAllItems(); } HTREEITEM CViewClasses::AddItem(HTREEITEM hParent, LPCTSTR text, int image) { TVITEM tvi; ZeroMemory(&tvi, sizeof(TVITEM)); tvi.mask = TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE; tvi.iImage = image; tvi.iSelectedImage = image; tvi.pszText = const_cast<LPTSTR>(text); TVINSERTSTRUCT tvis; ZeroMemory(&tvis, sizeof(TVINSERTSTRUCT)); tvis.hParent = hParent; tvis.item = tvi; return InsertItem(tvis); } void CViewClasses::OnAttach() { //set the image lists m_normalImages.Create(16, 15, ILC_COLOR32 | ILC_MASK, 1, 0); CBitmap bm(IDB_CLASSVIEW); m_normalImages.Add( bm, RGB(255, 0, 0) ); SetImageList(m_normalImages, LVSIL_NORMAL); // Adjust style to show lines and [+] button DWORD dwStyle = GetStyle(); dwStyle |= TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT; SetStyle(dwStyle); DeleteAllItems(); // Add some tree-view items HTREEITEM htiRoot = AddItem(NULL, _T("TreeView"), 0); HTREEITEM htiCTreeViewApp = AddItem(htiRoot, _T("CTreeViewApp"), 1); AddItem(htiCTreeViewApp, _T("CTreeViewApp()"), 3); AddItem(htiCTreeViewApp, _T("GetMainFrame()"), 3); AddItem(htiCTreeViewApp, _T("InitInstance()"), 3); HTREEITEM htiMainFrame = AddItem(htiRoot, _T("CMainFrame"), 1); AddItem(htiMainFrame, _T("CMainFrame()"), 3); AddItem(htiMainFrame, _T("OnCommand()"), 4); AddItem(htiMainFrame, _T("OnInitialUpdate()"), 4); AddItem(htiMainFrame, _T("WndProc()"), 4); HTREEITEM htiView = AddItem(htiRoot, _T("CView"), 1); AddItem(htiView, _T("CView()"), 3); AddItem(htiView, _T("OnInitialUpdate()"), 4); AddItem(htiView, _T("WndProc()"), 4); // Expand some tree-view items Expand(htiRoot, TVE_EXPAND); Expand(htiCTreeViewApp, TVE_EXPAND); } void CViewClasses::OnDestroy() { SetImageList(NULL, LVSIL_SMALL); } LRESULT CViewClasses::OnMouseActivate(UINT msg, WPARAM wparam, LPARAM lparam) // Respond to a mouse click on the window { // Set window focus. The docker will now report this as active. SetFocus(); return FinalWindowProc(msg, wparam, lparam); } void CViewClasses::PreCreate(CREATESTRUCT& cs) { cs.style = TVS_NOTOOLTIPS|WS_CHILD; cs.lpszClass = WC_TREEVIEW; } LRESULT CViewClasses::WndProc(UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { case WM_MOUSEACTIVATE: return OnMouseActivate(msg, wparam, lparam); } return WndProcDefault(msg, wparam, lparam); } /////////////////////////////////////////////// // CContainClasses functions CContainClasses::CContainClasses() { SetTabText(_T("ClassView")); SetTabIcon(IDI_CLASSVIEW); SetDockCaption (_T("Class View - Docking container")); SetView(m_viewClasses); } void CContainClasses::AddCombo() { int nComboWidth = 120; CToolBar& tb = GetToolBar(); if (tb.CommandToIndex(IDM_FILE_SAVE) < 0) return; // Adjust button width and convert to separator tb.SetButtonStyle(IDM_FILE_SAVE, TBSTYLE_SEP); tb.SetButtonWidth(IDM_FILE_SAVE, nComboWidth); // Determine the size and position of the ComboBox int index = tb.CommandToIndex(IDM_FILE_SAVE); CRect rect = tb.GetItemRect(index); // Create the ComboboxEx window m_comboBoxEx.Create(tb); m_comboBoxEx.SetWindowPos(NULL, rect, SWP_NOACTIVATE); // Adjust the toolbar height to accomodate the ComboBoxEx control CRect rc = m_comboBoxEx.GetWindowRect(); tb.SetButtonSize( rc.Height(), rc.Height() ); // Add the ComboBox's items m_comboBoxEx.AddItems(); } BOOL CContainClasses::OnCommand(WPARAM wparam, LPARAM lparam) { UNREFERENCED_PARAMETER(lparam); // OnCommand responds to menu and and toolbar input UINT id = LOWORD(wparam); switch(id) { case IDM_FILE_NEW: return OnFileNew(); case IDM_HELP_ABOUT: return OnHelpAbout(); } return FALSE; } BOOL CContainClasses::OnFileNew() { TRACE("File New\n"); MessageBox(_T("File New"), _T("Button Pressed"), MB_OK); return TRUE; } BOOL CContainClasses::OnHelpAbout() { // Send a message to the frame requesting the help dialog GetContainerApp().GetMainFrame().SendMessage(WM_HELP); return TRUE; } void CContainClasses::SetupToolBar() { // Set the Bitmap resource for the toolbar SetToolBarImages(RGB(192,192,192), IDW_MAIN, 0, 0); // Set the Resource IDs for the toolbar buttons AddToolBarButton( IDM_FILE_NEW ); AddToolBarButton( IDM_FILE_OPEN, FALSE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_FILE_SAVE, FALSE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_EDIT_CUT ); AddToolBarButton( IDM_EDIT_COPY ); AddToolBarButton( IDM_EDIT_PASTE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_FILE_PRINT, FALSE ); AddToolBarButton( 0 ); // Separator AddToolBarButton( IDM_HELP_ABOUT ); // Add the ComboBarEx control to the toolbar AddCombo(); } ///////////////////////////////////////////////// // Definitions for the CDockClasses class CDockClasses::CDockClasses() { SetView(m_classes); // Set the width of the splitter bar SetBarWidth(8); }
[ "czx_1991@qq.com" ]
czx_1991@qq.com
061ebd52d14edc14fe1319db07ba47d2d7e115c5
80fd548163c024b42111d63fb0877e079e61cdda
/targetFeature.cpp
04ab5053a70dc4300a7d7eb4050e572351267c4e
[]
no_license
Cxx0822/NAO_GolfVision_ML_C
b5859322e71c68a94e2db1aa2d0c28aa64a2dd42
38dcae05da5c34b03c820417915ee15a394372d4
refs/heads/master
2020-07-14T08:16:12.700494
2019-08-30T02:13:28
2019-08-30T02:13:28
205,281,108
2
0
null
null
null
null
GB18030
C++
false
false
2,409
cpp
#include "targetFeature.h" /*颜色特征提取类定义*/ ColorFeature::ColorFeature() { } ColorFeature::ColorFeature(Mat img, int number) { this->_img = img; this->_number = number; } ColorFeature::~ColorFeature() { } /*分离区间*/ Mat ColorFeature::split_interval(Mat &img) { Mat_<Vec3b>::iterator it = img.begin<Vec3b>(); Mat_<Vec3b>::iterator itend = img.end<Vec3b>(); // 将每个像素划分到各自的区间 for (; it != itend; ++it) { (*it)[0] = (*it)[0] / this->_number; // 例像素值20,20/16=1,即区间数为1 (*it)[1] = (*it)[1] / this->_number; (*it)[2] = (*it)[2] / this->_number; } return img; } /*颜色特征提取*/ vector<float> ColorFeature::color_extract() { vector<Mat> channels; vector<int> temp_channel; splited_img = split_interval(_img); split(splited_img, channels); // 分离通道 // 遍历3个通道,分别统计个数,并计算概率 for (int i = 0; i < channels.size(); i++) { temp_channel = channels.at(i).reshape(1, 1); // 转为vector for (int j = 0; j < this->_number; j++) { result = int(count(temp_channel.begin(), temp_channel.end(), j)); // 统计出现的次数 color_vector.push_back(float(result) / temp_channel.size()); // 计算概率(0-1) } } // 总特征维度为48,即16*3,每个通道16个区间。 return color_vector; } /*HOG特征提取类定义*/ HogFeature::HogFeature() { } HogFeature::HogFeature(Mat img, Size windowSize) { _img = img; _windowSize = windowSize; } HogFeature::~HogFeature() { } /*HOG特征提取*/ vector<float> HogFeature::hog_extract() { Mat img_gray; // 窗口大小=块大小=步长,即只检测一次,即原图,这样方便统一特征维度 // 总特征数为 4 * 8 = 32, 4是因为块大小是元胞大小的4倍,8是因为bins=8 blockSize = this->_windowSize; // 块大小 cellSize = blockSize / 2; // 元胞大小 blockStrideSize = blockSize; // 步长 nbins = 8; // 直方图bin的数量 HOGDescriptor hog(this->_windowSize, blockSize, blockStrideSize, cellSize, nbins); // 实例化hog类 vector<float> hog_vector; // HOG描述子向量 cvtColor(this->_img, img_gray, CV_BGR2GRAY); // HOG需要灰度图 hog.compute(img_gray, hog_vector, Size(4, 4), Size(0, 0)); // 计算hog特征向量 return hog_vector; }
[ "1556464090@qq.com" ]
1556464090@qq.com
5652bf087213054cbcb8db5e486113b3597c3150
f1caf5e677329b4b3263f4638089253f56e6891d
/lib/handsfree_hw/include/handsfree_hw/transport_serial.h
4cc0b16ec4a9f6b77b8f32014aa42f83c86c0055
[]
no_license
SiChiTong/handsfree_gui
9a40361db664dab54a5cc369ff304aafb97698c6
2280ef79946419760f37d54363861de2e56d1877
refs/heads/master
2021-01-21T21:05:19.572620
2017-04-10T03:37:11
2017-04-10T03:37:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,196
h
/*********************************************************************************************************************** * Copyright (c) Hands Free Team. All rights reserved. * FileName: hf_link.cpp * Contact: QQ Exchange Group -- 521037187 * Version: V2.0 * * LICENSING TERMS: * The Hands Free is licensed generally under a permissive 3-clause BSD license. * Contributions are requiredto be made under the same license. * * History: * <author> <time> <version> <desc> * luke liao 2016.4.1 V1.0 creat this file * * Description: define handfree transport serial method ***********************************************************************************************************************/ #ifndef TRANSPORT_SERIAL_H_ #define TRANSPORT_SERIAL_H_ #include <handsfree_hw/transport.h> namespace handsfree_hw { class SerialParams { public: std::string serialPort; unsigned int baudRate; unsigned int flowControl; unsigned int parity; unsigned int stopBits; SerialParams() : serialPort(), baudRate(921600), flowControl(0), parity(0), stopBits(0) { } SerialParams( std::string _serialPort, unsigned int _baudRate, unsigned int _flowControl, unsigned int _parity, unsigned int _stopBits ) : serialPort(_serialPort), baudRate(_baudRate), flowControl(_flowControl), parity(_parity), stopBits(_stopBits) { } }; class TransportSerial : public Transport { public: TransportSerial (); TransportSerial (std::string url); virtual Buffer readBuffer(); virtual void writeBuffer(Buffer &data); virtual void setParam(const TransportParam &param) ; virtual void enable(bool enable) ; private: boost::shared_ptr<boost::asio::serial_port> port_; SerialParams params_; // for async read Buffer temp_read_buf_; bool enable_use ; boost::thread thread_; // locks boost::mutex port_mutex_; boost::mutex write_mutex_; boost::mutex read_mutex_; bool initializeSerial(); void mainRun(); void start_a_read(); void start_a_write(); void readHandler(const boost::system::error_code &ec, size_t bytesTransferred); void writeHandler(const boost::system::error_code &ec); }; } #endif /* TRANSPORT_SERIAL_H_ */
[ "cp_vin@126.com" ]
cp_vin@126.com
b36cba653ce9b7516c17855670d67210ceead005
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/TFunction_HArray1OfDataMapOfGUIDDriver.hxx
67792c1568c7e876cbff93975c3931bd2169bbae
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
3,078
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _TFunction_HArray1OfDataMapOfGUIDDriver_HeaderFile #define _TFunction_HArray1OfDataMapOfGUIDDriver_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_TFunction_HArray1OfDataMapOfGUIDDriver_HeaderFile #include <Handle_TFunction_HArray1OfDataMapOfGUIDDriver.hxx> #endif #ifndef _TFunction_Array1OfDataMapOfGUIDDriver_HeaderFile #include <TFunction_Array1OfDataMapOfGUIDDriver.hxx> #endif #ifndef _MMgt_TShared_HeaderFile #include <MMgt_TShared.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif class Standard_RangeError; class Standard_DimensionMismatch; class Standard_OutOfRange; class Standard_OutOfMemory; class TFunction_DataMapOfGUIDDriver; class TFunction_Array1OfDataMapOfGUIDDriver; class TFunction_HArray1OfDataMapOfGUIDDriver : public MMgt_TShared { public: TFunction_HArray1OfDataMapOfGUIDDriver(const Standard_Integer Low,const Standard_Integer Up); TFunction_HArray1OfDataMapOfGUIDDriver(const Standard_Integer Low,const Standard_Integer Up,const TFunction_DataMapOfGUIDDriver& V); void Init(const TFunction_DataMapOfGUIDDriver& V) ; Standard_Integer Length() const; Standard_Integer Lower() const; Standard_Integer Upper() const; void SetValue(const Standard_Integer Index,const TFunction_DataMapOfGUIDDriver& Value) ; const TFunction_DataMapOfGUIDDriver& Value(const Standard_Integer Index) const; TFunction_DataMapOfGUIDDriver& ChangeValue(const Standard_Integer Index) ; const TFunction_Array1OfDataMapOfGUIDDriver& Array1() const; TFunction_Array1OfDataMapOfGUIDDriver& ChangeArray1() ; DEFINE_STANDARD_RTTI(TFunction_HArray1OfDataMapOfGUIDDriver) protected: private: TFunction_Array1OfDataMapOfGUIDDriver myArray; }; #define ItemHArray1 TFunction_DataMapOfGUIDDriver #define ItemHArray1_hxx <TFunction_DataMapOfGUIDDriver.hxx> #define TheArray1 TFunction_Array1OfDataMapOfGUIDDriver #define TheArray1_hxx <TFunction_Array1OfDataMapOfGUIDDriver.hxx> #define TCollection_HArray1 TFunction_HArray1OfDataMapOfGUIDDriver #define TCollection_HArray1_hxx <TFunction_HArray1OfDataMapOfGUIDDriver.hxx> #define Handle_TCollection_HArray1 Handle_TFunction_HArray1OfDataMapOfGUIDDriver #define TCollection_HArray1_Type_() TFunction_HArray1OfDataMapOfGUIDDriver_Type_() #include <TCollection_HArray1.lxx> #undef ItemHArray1 #undef ItemHArray1_hxx #undef TheArray1 #undef TheArray1_hxx #undef TCollection_HArray1 #undef TCollection_HArray1_hxx #undef Handle_TCollection_HArray1 #undef TCollection_HArray1_Type_ // other Inline functions and methods (like "C++: function call" methods) #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
10e7deafcca80ee57b51efc6c1dabc28f7c3310b
6934288c026289e5317e2aeb467b0cb685cfc59d
/tpc2/src/VentanillaEntrada.h
bbb173453297756c9743bd4f0b2952821b5da715
[]
no_license
gcocce/tpc
6b491ae579e4bf7be43086a63c43a5bec49ba143
f3ab6a689b810c6d5f2d32f0ee61c1bbc393fee8
refs/heads/master
2020-04-06T03:41:06.363897
2012-12-05T17:16:55
2012-12-05T17:16:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
904
h
#ifndef VENTANILLAENTRADA_H_ #define VENTANILLAENTRADA_H_ #include "Semaforo.h" #include "BufferSincronizado.h" #include "Estacionamiento.h" #include "SignalHandler.h" #include "Message.h" #include "logger.h" #include "ConcPipe.h" #include "MsgF.h" class VentanillaEntrada : public EventHandler { private: bool abierta; int estacionamiento; char numeroVentanilla; Semaforo barrera; BufferSincronizado<message> canalEntrada; BufferSincronizado<message> canalSalida; //BufferSincronizado<MsgFString> canalEAdmin; BufferSincronizado<MsgFST> canalEAdmin; Logger* log; ConcPipe* cpipe; public: VentanillaEntrada(Logger* log, char *path, int est, char numeroVentanilla, ConcPipe* cp); ~VentanillaEntrada(); void crear(); void eliminar(); void abrir(); void cerrar(); void iniciar(); void finalizar(); virtual int handleSignal ( int signum ); }; #endif /* VENTANILLAENTRADA_H_ */
[ "gastoncocce@hotmail.com" ]
gastoncocce@hotmail.com
1716467f2a2282dc1dcaed1835841e3a67a2e3f0
e2d6129f991ec7a8c304aa9c045f486cc8901b7c
/src/pcrepp/test_pcre2pp.cc
ce5b0c58b637c90975be8d3f7216982ad322e235
[ "BSD-2-Clause" ]
permissive
tstack/lnav
f1f8769885d1e639fa969dbc8c304626bfcb7318
c796a662731b5bdb74196af0a4dfd0cbdf96e285
refs/heads/master
2023-09-05T19:04:14.646192
2023-09-05T05:51:07
2023-09-05T05:51:07
306,147
5,812
355
BSD-2-Clause
2023-08-05T19:12:34
2009-09-14T01:02:02
C++
UTF-8
C++
false
false
7,794
cc
/** * Copyright (c) 2022, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest/doctest.h" #include "pcre2pp.hh" TEST_CASE("bad pattern") { auto compile_res = lnav::pcre2pp::code::from(string_fragment::from_const("[abc")); CHECK(compile_res.isErr()); auto ce = compile_res.unwrapErr(); CHECK(ce.ce_offset == 4); } TEST_CASE("named captures") { auto compile_res = lnav::pcre2pp::code::from( string_fragment::from_const("(?<abc>a)(b)(?<def>c)")); CHECK(compile_res.isOk()); const std::vector<std::pair<size_t, string_fragment>> expected_caps = { {1, string_fragment::from_const("abc")}, {3, string_fragment::from_const("def")}, }; int caps_index = 0; auto co = compile_res.unwrap(); for (const auto cap : co.get_named_captures()) { const auto& expected_cap = expected_caps[caps_index]; CHECK(expected_cap.first == cap.get_index()); CHECK(expected_cap.second == cap.get_name()); caps_index += 1; } } TEST_CASE("match") { static const char INPUT[] = "key1=1234;key2=5678;"; auto co = lnav::pcre2pp::code::from_const(R"((?<key>\w+)=(?<value>[^;]+);)"); co.capture_from(string_fragment::from_const(INPUT)) .for_each([](lnav::pcre2pp::match_data& md) { printf("got '%s' %s = %s\n", md[0]->to_string().c_str(), md[1]->to_string().c_str(), md[2]->to_string().c_str()); }); } TEST_CASE("partial") { static const char INPUT[] = "key1=1234"; auto co = lnav::pcre2pp::code::from_const(R"([a-z]+=.*)"); auto matched = co.match_partial(string_fragment::from_const(INPUT)); CHECK(matched == 3); } TEST_CASE("capture_name") { auto co = lnav::pcre2pp::code::from_const("(?<abc>def)(ghi)"); CHECK(co.get_capture_count() == 2); CHECK(string_fragment::from_c_str(co.get_name_for_capture(1)) == "abc"); CHECK(co.get_name_for_capture(2) == nullptr); } TEST_CASE("get_capture_count") { auto co = lnav::pcre2pp::code::from_const("(DEFINE)"); CHECK(co.get_capture_count() == 1); } TEST_CASE("get_captures") { auto co = lnav::pcre2pp::code::from_const(R"((?<abc>\w+)-(def)-)"); CHECK(co.get_capture_count() == 2); const auto& caps = co.get_captures(); CHECK(caps.size() == 2); CHECK(caps[0].to_string() == R"((?<abc>\w+))"); CHECK(caps[1].to_string() == R"((def))"); } TEST_CASE("replace") { static const char INPUT[] = "test 1 2 3"; auto co = lnav::pcre2pp::code::from_const(R"(\w*)"); auto in = string_fragment::from_const(INPUT); auto res = co.replace(in, R"({\0})"); CHECK(res == "{test}{} {1}{} {2}{} {3}{}"); } TEST_CASE("replace-empty") { static const char INPUT[] = ""; auto co = lnav::pcre2pp::code::from_const(R"(\w*)"); auto in = string_fragment::from_const(INPUT); auto res = co.replace(in, R"({\0})"); CHECK(res == "{}"); } TEST_CASE("for_each-all") { static const char INPUT[] = "Hello, World!\n"; auto co = lnav::pcre2pp::code::from_const(R"(.*)"); auto in = string_fragment::from_const(INPUT); co.capture_from(in).for_each([](lnav::pcre2pp::match_data& md) { printf("range %d:%d\n", md[0]->sf_begin, md[0]->sf_end); }); } TEST_CASE("capture_count") { auto co = lnav::pcre2pp::code::from_const(R"(^(\w+)=([^;]+);)"); CHECK(co.get_capture_count() == 2); } TEST_CASE("no-caps") { const static std::string empty_cap_regexes[] = { "foo (?:bar)", "foo [(]", "foo \\Q(bar)\\E", "(?i)", }; for (auto re : empty_cap_regexes) { auto co = lnav::pcre2pp::code::from(re).unwrap(); CHECK(co.get_captures().empty()); } } TEST_CASE("ipmatcher") { auto co = lnav::pcre2pp::code::from_const( R"((?(DEFINE)(?<byte>2[0-4]\d|25[0-5]|1\d\d|[1-9]?\d))\b(?&byte)(\.(?&byte)){3}\b)"); auto inp = string_fragment::from_const("192.168.1.1"); auto find_res = co.find_in(inp).ignore_error(); CHECK(find_res.has_value()); CHECK(find_res->f_all.sf_begin == 0); } TEST_CASE("get_captures-nested") { auto re = lnav::pcre2pp::code::from_const("foo (bar (?:baz)?)"); CHECK(re.get_captures().size() == 1); CHECK(re.get_captures()[0].sf_begin == 4); CHECK(re.get_captures()[0].sf_end == 18); CHECK(re.get_captures()[0].length() == 14); } TEST_CASE("get_captures-basic") { auto re = lnav::pcre2pp::code::from_const("(a)(b)(c)"); assert(re.get_captures().size() == 3); assert(re.get_captures()[0].sf_begin == 0); assert(re.get_captures()[0].sf_end == 3); assert(re.get_captures()[1].sf_begin == 3); assert(re.get_captures()[1].sf_end == 6); assert(re.get_captures()[2].sf_begin == 6); assert(re.get_captures()[2].sf_end == 9); } TEST_CASE("get_captures-escape") { auto re = lnav::pcre2pp::code::from_const("\\(a\\)(b)"); assert(re.get_captures().size() == 1); assert(re.get_captures()[0].sf_begin == 5); assert(re.get_captures()[0].sf_end == 8); } TEST_CASE("get_captures-named") { auto re = lnav::pcre2pp::code::from_const("(?<named>b)"); assert(re.get_captures().size() == 1); assert(re.get_captures()[0].sf_begin == 0); assert(re.get_captures()[0].sf_end == 11); } TEST_CASE("get_captures-namedP") { auto re = lnav::pcre2pp::code::from_const("(?P<named>b)"); assert(re.get_captures().size() == 1); assert(re.get_captures()[0].sf_begin == 0); assert(re.get_captures()[0].sf_end == 12); } TEST_CASE("get_captures-namedq") { auto re = lnav::pcre2pp::code::from_const("(?'named'b)"); CHECK(re.get_captures().size() == 1); CHECK(re.get_captures()[0].sf_begin == 0); CHECK(re.get_captures()[0].sf_end == 11); } TEST_CASE("anchored") { auto re = lnav::pcre2pp::code::from_const( "abc", PCRE2_ANCHORED | PCRE2_ENDANCHORED); const auto sub1 = string_fragment::from_const("abc"); const auto sub2 = string_fragment::from_const("abcd"); const auto sub3 = string_fragment::from_const("0abc"); CHECK(re.find_in(sub1).ignore_error().has_value()); CHECK_FALSE(re.find_in(sub2).ignore_error().has_value()); CHECK_FALSE(re.find_in(sub3).ignore_error().has_value()); }
[ "timothyshanestack@gmail.com" ]
timothyshanestack@gmail.com
951565ab7fb305eb98042414db665c615da8f273
453e647779e0ff590092b12629e759e010ee1223
/libs/embree/include/renderer/api/render_device.h
31e8a02303079b3eeb8efebe4c5d5924313105d8
[]
no_license
xiajiaonly/ofxEmbree
300361fe83d0c9902c6597e7149c6b0387a83b64
2fd9e66cbaa27ecfffa625344a8b042ded739498
refs/heads/master
2020-03-13T19:58:45.879441
2013-08-12T13:05:59
2013-08-12T13:05:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,302
h
// ======================================================================== // // Copyright 2009-2012 Intel Corporation // // // // 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 __EMBREE_RENDER_DEVICE_H__ #define __EMBREE_RENDER_DEVICE_H__ #include "default.h" #include "api/device.h" #include "api/swapchain.h" #include "sys/sync/mutex.h" namespace embree { class RenderDevice : public Device { public: /*! construction */ RenderDevice(size_t numThreadsPerProcessor); /*! destruction */ ~RenderDevice(); /******************************************************************* creation of objects *******************************************************************/ RTCamera rtNewCamera(const char* type); RTData rtNewData(const char* type, size_t bytes, const void* data); RTData rtNewDataFromFile(const char* type, const char* file, size_t offset, size_t bytes); RTImage rtNewImage(const char* type, size_t width, size_t height, const void* data); RTImage rtNewImageFromFile(const char* file); RTTexture rtNewTexture(const char* type); RTMaterial rtNewMaterial(const char* type); RTShape rtNewShape(const char* type); RTLight rtNewLight(const char* type); RTPrimitive rtNewShapePrimitive(RTShape shape, RTMaterial material, const float* transform = NULL); RTPrimitive rtNewLightPrimitive(RTLight light, const float* transform = NULL); RTPrimitive rtTransformPrimitive(RTPrimitive prim, const float* transform); RTScene rtNewScene(const char* type, RTPrimitive* prims, size_t size); RTToneMapper rtNewToneMapper(const char* type); RTRenderer rtNewRenderer(const char* type); RTFrameBuffer rtNewFrameBuffer(const char* type, size_t width, size_t height, size_t buffers); void rtGetFrameBufferSize(RTFrameBuffer frameBuffer, size_t& width, size_t& height); void* rtMapFrameBuffer(RTFrameBuffer frameBuffer); void rtUnmapFrameBuffer(RTFrameBuffer frameBuffer); void rtSwapBuffers(RTFrameBuffer frameBuffer); void rtIncRef(RTHandle handle); void rtDecRef(RTHandle handle); /******************************************************************* setting of parameters *******************************************************************/ void rtSetBool1(RTHandle handle, const char* property, bool x); void rtSetBool2(RTHandle handle, const char* property, bool x, bool y); void rtSetBool3(RTHandle handle, const char* property, bool x, bool y, bool z); void rtSetBool4(RTHandle handle, const char* property, bool x, bool y, bool z, bool w); void rtSetInt1(RTHandle handle, const char* property, int x); void rtSetInt2(RTHandle handle, const char* property, int x, int y); void rtSetInt3(RTHandle handle, const char* property, int x, int y, int z); void rtSetInt4(RTHandle handle, const char* property, int x, int y, int z, int w); void rtSetFloat1(RTHandle handle, const char* property, float x); void rtSetFloat2(RTHandle handle, const char* property, float x, float y); void rtSetFloat3(RTHandle handle, const char* property, float x, float y, float z); void rtSetFloat4(RTHandle handle, const char* property, float x, float y, float z, float w); void rtSetArray(RTHandle handle, const char* property, const char* type, RTData data, size_t size, size_t stride, size_t ofs); void rtSetString(RTHandle handle, const char* property, const char* str); void rtSetImage(RTHandle handle, const char* property, RTImage img); void rtSetTexture(RTHandle handle, const char* property, RTTexture tex); void rtSetTransform(RTHandle handle, const char* property, const float* transform); void rtClear(RTHandle handle); void rtCommit(RTHandle handle); /******************************************************************* render calls *******************************************************************/ void rtRenderFrame(RTRenderer renderer, RTCamera camera, RTScene scene, RTToneMapper toneMapper, RTFrameBuffer frameBuffer, int accumulate); bool rtPick(RTCamera camera, float x, float y, RTScene scene, float& px, float& py, float& pz); private: MutexSys mutex; }; } #endif
[ "diagne.cyril@gmail.com" ]
diagne.cyril@gmail.com
8a796819e38fd99102c378112818a01e5280f5d9
4394331a19b099681b0738e02e7f0a2f0713e95d
/libmediainfo_0.7.82/ZenLib/Source/ZenLib/Format/Http/Http_Handler.h
1ea484d271650f3ec3091284c1cc036530c5e484
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
OLEG4120/MediaInfoCLI-android
b986f2a3a74d502ecfe8c106d0f026082411bca7
94cf4fd1edc9b7b9912d56976f1b4b025dfe6119
refs/heads/master
2021-01-10T16:00:28.266042
2016-01-28T06:44:05
2016-01-28T06:44:57
50,170,254
3
0
null
null
null
null
UTF-8
C++
false
false
2,865
h
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a zlib-style license that can * be found in the License.txt file in the root of the source tree. */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // A HTTP Request // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- #ifndef ZenLib_Format_Http_RequestH #define ZenLib_Format_Http_RequestH //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "ZenLib/Format/Http/Http_Cookies.h" #include <string> #include <ctime> #include <map> #include <vector> //--------------------------------------------------------------------------- namespace ZenLib { namespace Format { namespace Http { //*************************************************************************** /// @brief //*************************************************************************** class Handler { public: //Constructor/Destructor Handler(); //In std::string Path; //The path being requested by this request std::map<std::string, std::string> Request_Headers; //All the incoming HTTP headers from the client web browser. std::map<std::string, std::string> Request_Cookies; //The set of cookies that came from the client along with this request std::map<std::string, std::string> Request_Queries; //All the key/value pairs in the query string of this request std::string Foreign_IP; //The foreign ip address for this request std::string Local_IP; //The foreign port number for this request unsigned short Foreign_Port; //The IP of the local interface this request is coming in on unsigned short Local_Port; //The local port number this request is coming in on bool HeadersOnly; //The request requests only the header //Out size_t Response_HTTP_Code; //HTTP code to be sent std::map<std::string, std::string> Response_Headers; //Additional headers you wish to appear in the HTTP response to this request Cookies Response_Cookies; //New cookies to pass back to the client along with the result of this request std::string Response_Body; //To be displayed as the response to this request }; } //Namespace } //Namespace } //Namespace #endif
[ "oleg02007@gmail.com" ]
oleg02007@gmail.com
10b00f1d7deb884ddc3369c0e9da346139ac88a5
85bfbbc8ecff945026ca735fa70b6b07029efef3
/PA4/mycode/expression_validation.h
42a061fdfc69ac7f2b1105c78d9a59625be916d3
[]
no_license
dafidi/cs143
3febf7a4b6a50f38c79a13ca32f39d4f291e2111
7336deac87625f90f57d731bc8346d7e40c90481
refs/heads/master
2020-07-13T00:36:50.471457
2019-09-06T01:22:33
2019-09-06T01:22:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,698
h
#pragma once #include "cool-tree.h" #include "symtab.h" #include "typechecking.h" #include <stack> #include <algorithm> namespace mycode { bool object_in_ancestry_attribs(Symbol sym, const Symbol c, SymbolTable<Symbol, symbol_table_data>*& sym_tab); bool validate_exp_assign(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_static_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_cond(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_loop(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_typcase(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_block(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_let(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_plus(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_sub(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_mul(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_divide(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_neg(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_lt(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_eq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_leq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_comp(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_int_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_bool_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_string_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_new_(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_isvoid(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_no_expr(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_exp_object(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_case(Class_ in_class, Feature in_feature, Case e, SymbolTable<Symbol, symbol_table_data>* sym_tab); bool validate_expression(Class_ in_class, Feature in_feature, Expression& e, SymbolTable<Symbol, symbol_table_data>*& sym_tab) { bool expression_is_valid = true; switch (e->get_expr_type()) { case expr_type::EXP_ASSIGN: { assign_class* assign_exp = (assign_class*) e; expression_is_valid = validate_exp_assign(in_class, in_feature, assign_exp, sym_tab); break; } case expr_type::EXP_STATIC_DISPATCH: { static_dispatch_class* static_dispatch_exp = (static_dispatch_class*) e; expression_is_valid = validate_exp_static_dispatch(in_class, in_feature, static_dispatch_exp, sym_tab); break; } case expr_type::EXP_DISPATCH: { dispatch_class* dispatch_exp = (dispatch_class*) e; expression_is_valid = validate_exp_dispatch(in_class, in_feature, dispatch_exp, sym_tab); break; } case expr_type::EXP_COND: { cond_class* cond_exp = (cond_class*) e; expression_is_valid = validate_exp_cond(in_class, in_feature, cond_exp, sym_tab); break; } case expr_type::EXP_LOOP: { loop_class* loop_exp = (loop_class*) e; expression_is_valid = validate_exp_loop(in_class, in_feature, loop_exp, sym_tab); break; } case expr_type::EXP_TYPCASE: { typcase_class* typcase_exp = (typcase_class*) e; expression_is_valid = validate_exp_typcase(in_class, in_feature, typcase_exp, sym_tab); break; } case expr_type::EXP_BLOCK: { block_class* block_exp = (block_class*) e; expression_is_valid = validate_exp_block(in_class, in_feature, block_exp, sym_tab); break; } case expr_type::EXP_LET: { let_class* let_exp = (let_class*) e; expression_is_valid = validate_exp_let(in_class, in_feature, let_exp, sym_tab); break; } case expr_type::EXP_PLUS: { plus_class* plus_exp = (plus_class*) e; expression_is_valid = validate_exp_plus(in_class, in_feature, plus_exp, sym_tab); break; } case expr_type::EXP_SUB: { sub_class* sub_exp = (sub_class*) e; expression_is_valid = validate_exp_sub(in_class, in_feature, sub_exp, sym_tab); break; } case expr_type::EXP_MUL: { mul_class* mul_exp = (mul_class*) e; expression_is_valid = validate_exp_mul(in_class, in_feature, mul_exp, sym_tab); break; } case expr_type::EXP_DIVIDE: { divide_class* divide_exp = (divide_class*) e; expression_is_valid = validate_exp_divide(in_class, in_feature, divide_exp, sym_tab); break; } case expr_type::EXP_NEG: { neg_class* neg_exp = (neg_class*) e; expression_is_valid = validate_exp_comp(in_class, in_feature, neg_exp, sym_tab); break; } case expr_type::EXP_LT: { lt_class* lt_exp = (lt_class*) e; expression_is_valid = validate_exp_lt(in_class, in_feature, lt_exp, sym_tab); break; } case expr_type::EXP_EQ: { eq_class* eq_exp = (eq_class*) e; expression_is_valid = validate_exp_eq(in_class, in_feature, eq_exp, sym_tab); break; } case expr_type::EXP_LEQ: { leq_class* leq_exp = (leq_class*) e; expression_is_valid = validate_exp_leq(in_class, in_feature, leq_exp, sym_tab); break; } case expr_type::EXP_COMP: { comp_class* comp_exp = (comp_class*) e; expression_is_valid = validate_exp_neg(in_class, in_feature, comp_exp, sym_tab); break; } case expr_type::EXP_INT_CONST: { expression_is_valid = true; break; } case expr_type::EXP_BOOL_CONST: { expression_is_valid = true; break; } case expr_type::EXP_STRING_CONST: { expression_is_valid = true; break; } case expr_type::EXP_NEW_: { new__class* new__exp = (new__class*) e; expression_is_valid = validate_exp_new_(in_class, in_feature, new__exp, sym_tab); break; } case expr_type::EXP_ISVOID: { isvoid_class* isvoid_exp = (isvoid_class*) e; expression_is_valid = validate_exp_isvoid(in_class, in_feature, isvoid_exp, sym_tab); break; } case expr_type::EXP_NO_EXPR: { expression_is_valid = true; break; } case expr_type::EXP_OBJECT: { object_class* object_exp = (object_class*) e->copy_Expression(); expression_is_valid = validate_exp_object(in_class, in_feature, object_exp, sym_tab); break; } defualt: { expression_is_valid = false; } } if (Symbol expr_type = get_expression_type(in_class, e, sym_tab)) { e->set_type(idtable.add_string(expr_type->get_string())); } else { e->set_type(idtable.add_string(Object->get_string())); } if (!expression_is_valid) { DEBUG_ACTION(std::cout << "Expression class(#) " << (int) e->get_expr_type() << " was faulty." << std::endl); } return expression_is_valid; } bool validate_exp_assign(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { assign_class* assign_exp = (assign_class*) e; Symbol type; Symbol assignee_name = assign_exp->get_name(); Expression assign_rhs_expr = assign_exp->get_expr(); symbol_table_data* assignee_data = sym_tab->lookup(assignee_name); bool still_valid = true; // The assignee must either be in scope (case I) or an attribute inherited from one of in_class's ancestors (case II). if (assignee_data || object_in_ancestry_attribs(assignee_name, in_class->get_name(), sym_tab)) { // The expression being assigned to the assignee must be valid by itself within the current scope. still_valid = validate_expression(in_class, in_feature, assign_rhs_expr, sym_tab); // Case I if (assignee_data) { type = assignee_data->get_type(); // If the in-scope variable is declared as SELF_TYPE, substitute the class's name for it. if (type == SELF_TYPE) { type = in_class->get_name(); } // The expression may be the type exactly, or a subtype of it. return still_valid && (type == get_expression_type(in_class, assign_rhs_expr, sym_tab) || is_super_type_of(type, get_expression_type(in_class, assign_rhs_expr, sym_tab), sym_tab)); } // Case II else { type = find_type_of_attribute_in_class_or_ancestry(assignee_name, in_class->get_name(), sym_tab); // If it is declared as SELF_TYPE in the ancestor, substitute the class's name for it. if (type == SELF_TYPE) { type = in_class->get_name(); } // The expression may be the type exactly, or a subtype of it. return still_valid && (type == get_expression_type(in_class, assign_rhs_expr, sym_tab) || is_super_type_of(type, get_expression_type(in_class, assign_rhs_expr, sym_tab), sym_tab)); } } else { return false; } } bool validate_exp_static_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { static_dispatch_class* s_dispatch_exp = (static_dispatch_class*) e; Expression expr = s_dispatch_exp->get_expr(); Symbol func_name = s_dispatch_exp->get_name(); Symbol type_name = s_dispatch_exp->get_type_name(); Expressions args = s_dispatch_exp->get_args(); Symbol expr_type = get_expression_type(in_class, expr, sym_tab); bool still_valid = validate_expression(in_class, in_feature, expr, sym_tab); if (!is_super_type_of(type_name, expr_type, sym_tab)) { still_valid = false; } if (!find_type_of_method_in_class_or_ancestry(func_name, type_name, sym_tab)) { still_valid = false; } else { // The method has to be defined in the exact class named by type_name. method_class* desired_method = (method_class*) get_method_from_class_or_ancestry(func_name, type_name , sym_tab); if (desired_method) { // Number of arguments should be the same as number of parameters in function declaration. Formals desired_formals = desired_method->get_formals(); if (desired_formals->len() != args->len()) { still_valid = false; } // Finally, the types of the arguments must match the declared parameter types. for (int i = args->first(); args->more(i); i = args->next(i)) { Expression nth_exp = args->nth(i); still_valid = validate_expression(in_class, in_feature, nth_exp, sym_tab) \ && (desired_formals->nth(i)->get_type() == get_expression_type(in_class, args->nth(i), sym_tab) \ || is_super_type_of(desired_formals->nth(i)->get_type(), get_expression_type(in_class, args->nth(i), sym_tab), sym_tab)) \ && still_valid; } } else { still_valid = false; } } return still_valid; } bool validate_exp_dispatch(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { dispatch_class* dispatch_exp = (dispatch_class*) e; Expression expr = dispatch_exp->get_expr(); Symbol func_name = dispatch_exp->get_name(); Expressions args = dispatch_exp->get_args(); Symbol expr_type = get_expression_type(in_class, expr, sym_tab); bool still_valid = validate_expression(in_class, in_feature, expr, sym_tab); if (expr_type == SELF_TYPE) { expr_type = in_class->get_name(); } // If the method is not defined on the class or its ancestors, it's a bad expression. if (method_class* desired_method = (method_class*) get_method_from_class_or_ancestry(func_name, expr_type, sym_tab)) { Formals desired_formals = desired_method->get_formals(); //Ha! now it's formals vs arguments. if (desired_formals->len() != args->len()) { return false; } for (int i = args->first(); args->more(i); i = args->next(i)) { Expression nth_exp = args->nth(i); Symbol nth_exp_type = get_expression_type(in_class, args->nth(i), sym_tab); if (nth_exp_type == SELF_TYPE) {nth_exp_type = in_class->get_name();} bool okay = validate_expression(in_class, in_feature, nth_exp, sym_tab) \ && (desired_formals->nth(i)->get_type() == nth_exp_type || is_super_type_of(desired_formals->nth(i)->get_type(), nth_exp_type, sym_tab)); still_valid = okay && still_valid; } } else { still_valid = false; } return still_valid; } bool validate_exp_cond(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { cond_class* cond_exp = (cond_class*) e; Expression pred = cond_exp->get_pred(); Expression then_exp = cond_exp->get_then_exp(); Expression else_exp = cond_exp->get_else_exp(); bool still_valid = validate_expression(in_class, in_feature, pred, sym_tab) && \ validate_expression(in_class, in_feature, then_exp, sym_tab) && \ validate_expression(in_class, in_feature, else_exp, sym_tab); still_valid = still_valid && Bool == get_expression_type(in_class, pred, sym_tab); return still_valid; } bool validate_exp_loop(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { loop_class* loop_exp = (loop_class*) e; Expression pred = loop_exp->get_pred(); Expression body = loop_exp->get_body(); bool still_valid = validate_expression(in_class, in_feature, pred, sym_tab) && \ validate_expression(in_class, in_feature, body, sym_tab); /* May need to possibly add pred variables to scope for body. Maybe. */ still_valid = still_valid && Bool == get_expression_type(in_class, pred, sym_tab); return still_valid; } bool validate_exp_typcase(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { typcase_class* typcase_exp = (typcase_class*) e; Expression expr = typcase_exp->get_expr(); Cases cases = typcase_exp->get_cases(); bool still_valid = true; std::vector<Symbol> types_seen_so_far; still_valid = validate_expression(in_class, in_feature, expr, sym_tab); for (int i = cases->first(); cases->more(i); i = cases->next(i)) { branch_class* nth_branch = (branch_class*)cases->nth(i); Symbol nth_branch_decl_type = nth_branch->get_type_decl(); bool okay = validate_case(in_class, in_feature, nth_branch, sym_tab); if (std::find(types_seen_so_far.begin(), types_seen_so_far.end(), nth_branch_decl_type) == types_seen_so_far.end()) { types_seen_so_far.push_back(nth_branch_decl_type); } else { still_valid = false; } still_valid = okay && still_valid; } return still_valid; } bool validate_case(Class_ in_class, Feature in_feature, Case c, SymbolTable<Symbol, symbol_table_data>* sym_tab) { branch_class* case_branch = (branch_class*) c; Symbol branch_id = case_branch->get_name(); Symbol branch_type = case_branch->get_type_decl() == SELF_TYPE ? in_class->get_name() : case_branch->get_type_decl(); Expression branch_expression = case_branch->get_expr(); symbol_table_data* data = new symbol_table_data({NULL, NULL, branch_type, NULL}); bool still_valid = true; sym_tab->enterscope(); sym_tab->addid(branch_id, data); still_valid = validate_expression(in_class, in_feature, branch_expression, sym_tab); Symbol s = get_expression_type(in_class, branch_expression, sym_tab); still_valid = still_valid && is_super_type_of(branch_type, s, sym_tab); sym_tab->exitscope(); return still_valid; } bool validate_exp_block(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { block_class* block_exp = (block_class*) e; Expressions expressions = block_exp->get_expressions(); bool still_valid = true; for (int i = expressions->first(); expressions->more(i); i = expressions->next(i)) { Expression nth_exp = expressions->nth(i); bool okay = validate_expression(in_class, in_feature, nth_exp, sym_tab) && still_valid; still_valid = okay && still_valid; } // DEBUG_ACTION(std::cout << "Block just validated says: " << still_valid << std::endl); return still_valid; } bool validate_exp_let(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { let_class* let_exp = (let_class*) e; Symbol id = let_exp->get_identifier(); Symbol type_decl = let_exp->get_type_decl(); Expression init_expr = let_exp->get_init_expr(); Expression body = let_exp->get_body(); bool still_valid = sym_tab->lookup(type_decl) != NULL ? true : false; still_valid = id != self && still_valid; Symbol init_expr_type = get_expression_type(in_class, init_expr, sym_tab); still_valid = (init_expr_type == No_type || (type_decl == init_expr_type) || is_super_type_of(type_decl, init_expr_type, sym_tab)) && still_valid; symbol_table_data* data = new symbol_table_data({NULL, NULL, type_decl, NULL}); sym_tab->enterscope(); sym_tab->addid(id, data); still_valid = validate_expression(in_class, in_feature, init_expr, sym_tab) && still_valid; still_valid = validate_expression(in_class, in_feature, body, sym_tab) && still_valid; sym_tab->exitscope(); return still_valid; } bool validate_exp_plus(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { plus_class* plus_exp = (plus_class*) e; bool still_valid = validate_expression(in_class, in_feature, plus_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, plus_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, plus_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, plus_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_sub(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { sub_class* sub_exp = (sub_class*) e; bool still_valid = validate_expression(in_class, in_feature, sub_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, sub_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, sub_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, sub_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_mul(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { mul_class* mul_exp = (mul_class*) e; bool still_valid = validate_expression(in_class, in_feature, mul_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, mul_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, mul_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, mul_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_divide(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { divide_class* divide_exp = (divide_class*) e; bool still_valid = validate_expression(in_class, in_feature, divide_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, divide_exp->get_second_expression(), sym_tab); still_valid = still_valid && \ Int == get_expression_type(in_class, divide_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, divide_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_neg(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { neg_class* neg_exp = (neg_class*) e; bool still_valid = validate_expression(in_class, in_feature, neg_exp->get_expr(), sym_tab); still_valid = still_valid && Bool == get_expression_type(in_class, neg_exp->get_expr(), sym_tab); return still_valid; } bool validate_exp_lt(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { lt_class* lt_exp = (lt_class*) e; bool still_valid = validate_expression(in_class, in_feature, lt_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, lt_exp->get_second_expression(), sym_tab); still_valid = Int == get_expression_type(in_class, lt_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, lt_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_eq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { eq_class* eq_exp = (eq_class*) e; bool still_valid = validate_expression(in_class, in_feature, eq_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, eq_exp->get_second_expression(), sym_tab); Symbol type_1 = get_expression_type(in_class, eq_exp->get_first_expression(), sym_tab); Symbol type_2 = get_expression_type(in_class, eq_exp->get_second_expression(), sym_tab); if (type_1 != type_2) { still_valid = still_valid && type_1 != Bool && type_2 != Bool && type_1 != Int && type_2 != Int && type_1 != Str && type_2 != Str; } return still_valid; } bool validate_exp_leq(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { leq_class* leq_exp = (leq_class*) e; bool still_valid = validate_expression(in_class, in_feature, leq_exp->get_first_expression(), sym_tab) && \ validate_expression(in_class, in_feature, leq_exp->get_second_expression(), sym_tab); still_valid = Int == get_expression_type(in_class, leq_exp->get_first_expression(), sym_tab) && \ Int == get_expression_type(in_class, leq_exp->get_second_expression(), sym_tab); return still_valid; } bool validate_exp_comp(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { comp_class* comp_exp = (comp_class*) e; bool still_valid = validate_expression(in_class, in_feature, comp_exp->get_expression(), sym_tab); still_valid = still_valid && Int == get_expression_type(in_class, comp_exp->get_expression(), sym_tab); return still_valid; } bool validate_exp_int_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_bool_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_string_const(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_new_(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { new__class* new__exp = (new__class*)e; if (sym_tab->lookup(new__exp->get_type_name())) { return true; } return false; } bool validate_exp_isvoid(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { isvoid_class* isvoid_exp = (isvoid_class*) e; return validate_expression(in_class, in_feature, isvoid_exp->get_expr(), sym_tab); } bool validate_exp_no_expr(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { return true; } bool validate_exp_object(Class_ in_class, Feature in_feature, Expression e, SymbolTable<Symbol, symbol_table_data>* sym_tab) { bool still_valid = true; object_class* object_exp = (object_class*) e; if (sym_tab->lookup(object_exp->get_name())) { if (object_exp->get_name() == in_feature->get_name() && !object_in_ancestry_attribs(object_exp->get_name(), in_class->get_name(), sym_tab)) { still_valid = false; if (object_exp->get_name() == self) { still_valid = true; } } // still_valid = true; } else if (object_in_ancestry_attribs(object_exp->get_name(), in_class->get_name(), sym_tab)) { still_valid = true; } else { still_valid = false; } return still_valid; } /** * This function checks whether a symbol is a feature of any class in the * ancestry of that object. Of course, it needs the symbol table to do this. * * @param sym The symbol being checked for (maybe an attribute or a method.) * It must surely be an object identifier (attribute or method). * @param c The class whose ancestors are being checked. It must surely be a * type (class) identifier * @param sym_tab The symbol table (pointer to it). */ bool object_in_ancestry_attribs(Symbol sym, const Symbol c, SymbolTable<Symbol, symbol_table_data>*& sym_tab) { symbol_table_data* class_data = sym_tab->lookup(c); symbol_table_data* class_parent_data = sym_tab->lookup(class_data->parent); if (class_parent_data) { for (int i = class_parent_data->features->first(); class_parent_data->features->more(i); i = class_parent_data->features->next(i)) { if (sym == class_parent_data->features->nth(i)->get_name()) { return true; } } return object_in_ancestry_attribs(sym, class_data->parent, sym_tab); } return false; } }
[ "david.awogbemila@bison.howard.edu" ]
david.awogbemila@bison.howard.edu
88ea7b80f4d118f94da626108f911b82018fe9d5
a2edaed1232234b1b3227f989fc35aece8c26a50
/TerrificTrafficSimulator/GUI/SCN_SelectMap.h
ce1df35e953784d863bf7360726e39cf86c467ec
[]
no_license
mkay1375/TerrificTrafficSimulator
690519488c62ddc21ce12321eac4a8e8c820e81a
ade4483abb23712980c8eee17da3feead67d21cd
refs/heads/main
2023-03-27T01:11:06.164891
2021-04-04T16:03:41
2021-04-04T16:03:41
354,578,362
6
0
null
null
null
null
UTF-8
C++
false
false
118
h
#pragma once #include "Scene.h" class SCN_SelectMap : public Scene { public: SCN_SelectMap(); ~SCN_SelectMap(); };
[ "mkay1375@gmail.com" ]
mkay1375@gmail.com
767e0b76c17293827c1edb301c5aa6f36672ef1d
65099cadbfbcaa34324864230bbfa7162a36fdad
/ENIGMAsystem/SHELL/Graphics_Systems/Direct3D9/DX9draw.cpp
244ccfb05076b18c7e3384f484e0d5f3e7f20a2b
[]
no_license
Rexhunter99/enigma-dev
cb7cc3e4fa2e5fe2b66bf827d0c8b84a37c71fd2
1b5af2c09284c16dd91905d3847554f26da9c1df
refs/heads/master
2021-01-17T14:15:42.919564
2013-10-20T11:48:43
2013-10-20T11:48:43
13,639,130
1
1
null
null
null
null
UTF-8
C++
false
false
6,270
cpp
/** Copyright (C) 2013 Robert B. Colton *** *** This file is a part of the ENIGMA Development Environment. *** *** ENIGMA 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, version 3 of the license or any later version. *** *** This application and its source code is distributed AS-IS, 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 code. If not, see <http://www.gnu.org/licenses/> **/ #include <math.h> #include "Direct3D9Headers.h" #include "Graphics_Systems/General/GSstdraw.h" #include "DX9binding.h" #include <stdio.h> #include "Universal_System/roomsystem.h" #define __GETR(x) ((x & 0x0000FF)) #define __GETG(x) ((x & 0x00FF00) >> 8) #define __GETB(x) ((x & 0xFF0000) >> 16) #include <vector> using std::vector; namespace enigma { float circleprecision=24; extern unsigned char currentcolor[4]; } namespace enigma_user { int draw_get_msaa_maxlevel() { } bool draw_get_msaa_supported() { } void draw_set_msaa_enabled(bool enable) { } void draw_enable_alphablend(bool enable) { d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, enable); } bool draw_get_alpha_test() { DWORD* enabled; d3ddev->GetRenderState(D3DRS_ALPHATESTENABLE, enabled); return *enabled; } unsigned draw_get_alpha_test_ref_value() { DWORD* val; d3ddev->GetRenderState(D3DRS_ALPHAREF, val); return *val; } void draw_set_alpha_test(bool enable) { d3ddev->SetRenderState(D3DRS_ALPHATESTENABLE, enable); } void draw_set_alpha_test_ref_value(unsigned val) { d3ddev->SetRenderState(D3DRS_ALPHAREF, val); } void draw_set_line_pattern(unsigned short pattern, int scale) { } void draw_point(gs_scalar x, gs_scalar y) { } void draw_point_color(gs_scalar x, gs_scalar y, int col) { } void draw_line(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2) { } void draw_line_width(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float width) { } void draw_line_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, int c1, int c2) { } void draw_line_width_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float width, int c1, int c2) { } void draw_rectangle(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, bool outline) { } void draw_rectangle_angle(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float angle, bool outline) { } void draw_rectangle_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, int c1, int c2, int c3, int c4, bool outline) { } void draw_set_circle_precision(float pr) { enigma::circleprecision = pr<3 ? 3 : pr; } float draw_get_circle_precision() { return enigma::circleprecision; } struct D3DTLVERTEX { float fX; float fY; float fZ; }; void draw_circle(gs_scalar x, gs_scalar y, float rad, bool outline) { double pr = 2 * M_PI / enigma::circleprecision; vector<float> Circle; d3ddev->SetFVF(D3DFVF_XYZ); if(outline) { for (double i = 0; i <= 2*M_PI; i += pr) { double xc1=cos(i)*rad,yc1=sin(i)*rad; //D3DTLVERTEX v; //v.fX = x+xc1; v.fY = y+yc1; v.fZ = 0; //v.fRHW = RHW; //v.Color = color; //v.fU = U; v.fV = V; //Circle.push_back(v); Circle.push_back(x+xc1); Circle.push_back(y+yc1); Circle.push_back(0); } d3ddev->DrawPrimitiveUP(D3DPT_LINESTRIP, enigma::circleprecision, &Circle[0], sizeof(float) * 3); } else { //D3DTLVERTEX v; //v.fX = x; v.fY = y; v.fZ = 0; //v.fRHW = RHW; //v.Color = color; //v.fU = U; v.fV = V; //Circle.push_back(v); Circle.push_back(x); Circle.push_back(y); Circle.push_back(0); for (double i = 0; i <= 2*M_PI; i += pr) { double xc1=cos(i)*rad,yc1=sin(i)*rad; //D3DTLVERTEX v; //v.fX = x+xc1; v.fY = y+yc1; v.fZ = 0; //v.fRHW = RHW; //v.Color = color; //v.fU = U; v.fV = V; //Circle.push_back(v); Circle.push_back(x+xc1); Circle.push_back(y+yc1); Circle.push_back(0); } d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, enigma::circleprecision, &Circle[0], sizeof(float) * 3); } } void draw_circle_color(gs_scalar x, gs_scalar y, float rad, int c1, int c2, bool outline) { } void draw_circle_perfect(gs_scalar x, gs_scalar y, float rad, bool outline) { } void draw_circle_color_perfect(gs_scalar x, gs_scalar y, float rad, int c1, int c2, bool outline) { } void draw_ellipse(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, bool outline) { } void draw_ellipse_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, int c1, int c2, bool outline) { } void draw_ellipse_perfect(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, bool outline) { } void draw_triangle(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float x3, float y3, bool outline) { } void draw_triangle_color(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float x3, float y3, int col1, int col2, int col3, bool outline) { } void draw_roundrect(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2,float rad, bool outline) { } void draw_roundrect_color(gs_scalar x1, gs_scalar y1, gs_scalar x2, gs_scalar y2, float rad, int col1, int col2, bool outline) { } void draw_arrow(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, gs_scalar arrow_size, gs_scalar line_size, bool outline) { } void draw_button(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, gs_scalar border_width, bool up) { } //Mind that health is 1-100 void draw_healthbar(gs_scalar x1, gs_scalar y1,gs_scalar x2, gs_scalar y2, float amount, int backcol, int mincol, int maxcol, int dir, bool showback, bool showborder) { } } //#include <endian.h> //TODO: Though serprex, the author of the function below, never included endian.h, // // Doing so is necessary for the function to work at its peak. // // When ENIGMA generates configuration files, one should be included here. namespace enigma_user { int draw_getpixel(int x, int y) { } int draw_mandelbrot(int x, int y, float w, double Zx, double Zy, double Zw, unsigned iter) { } }
[ "robertbcolton@hotmail.com" ]
robertbcolton@hotmail.com
2abdbeb285bbcf1ab1ac3945151585570162bcc6
19a012b6a66374235771a8c2baee19560e98f8d7
/Codeforces/CR51/a.cpp
e1c9e0ee5f568dcef4d3a1b651505a7efed34706
[]
no_license
juancate/CompetitivePrograming
735e992fd6ac9c264059604fb7a2f2dfce74d330
8cea3695fd0dec7122c94ab45b4517cb13232fb3
refs/heads/master
2021-01-25T10:06:47.576470
2018-12-19T01:11:41
2018-12-19T01:11:41
14,966,965
0
0
null
null
null
null
UTF-8
C++
false
false
1,032
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <cctype> #include <cassert> #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <algorithm> #define D(x) cerr << #x << " = " << x << endl #define REP(i,a,n) for(int i=(a); i<(int)(n); i++) #define FOREACH(it,v) for(typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it) #define ALL(v) (v).begin(), (v).end() typedef long long int64; const int INF = (int)(1e9); const int64 INFLL = (int64)(1e18); const double EPS = 1e-13; using namespace std; int main() { ios_base::sync_with_stdio(false); int n; cin >> n; vector<bool> seen(n+1, false); int k = 0, pos = 0; for(;;) { if(seen[pos]) break; seen[pos] = true; pos = (pos + k + 1) % n; k++; } for(int i = 0; i < n; i++) { if(!seen[i]) { cout << "NO\n"; return 0; } } cout << "YES\n"; return 0; }
[ "jcamargo@gmail.com" ]
jcamargo@gmail.com
0624831608292907e205e8c99fbb1cb95176923e
590b56bc2e6fafd6a906c61f3f6dbd66ac5731f2
/src/3rdParty/ImGui/imgui.h
f94fc5a7313ad0617162d01126a6be114d21c6c3
[ "MIT" ]
permissive
erdinckaya/monitorx
508a7e4a6764b4ef67253d1718e74414ae61576c
5e100ed4b36dc4c9b01c2ab5a9a2207b99a460c1
refs/heads/master
2020-04-14T06:00:03.606503
2019-01-07T17:49:17
2019-01-07T17:49:17
163,675,108
1
0
null
null
null
null
UTF-8
C++
false
false
202,270
h
// dear imgui, v1.67 WIP // (headers) // See imgui.cpp file for documentation. // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. // Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui /* Index of this file: // Header mess // Forward declarations and basic types // ImGui API (Dear ImGui end-user API) // Flags & Enumerations // ImGuiStyle // ImGuiIO // Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // Obsolete functions // Helpers (ImVector, ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor) // Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) // Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFont) */ #pragma once // Configuration file (edit imconfig.h or define IMGUI_USER_CONFIG to your own filename) #ifdef IMGUI_USER_CONFIG #include IMGUI_USER_CONFIG #endif #if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) #include "imconfig.h" #endif //----------------------------------------------------------------------------- // Header mess //----------------------------------------------------------------------------- #include <float.h> // FLT_MAX #include <stdarg.h> // va_list #include <stddef.h> // ptrdiff_t, NULL #include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp // Version // (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY00 then bounced up to XYY01 when release tagging happens) #define IMGUI_VERSION "1.67 WIP" #define IMGUI_VERSION_NUM 16602 #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert)) // Define attributes of all API symbols declarations (e.g. for DLL under Windows) // IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default bindings files (imgui_impl_xxx.h) #ifndef IMGUI_API #define IMGUI_API #endif #ifndef IMGUI_IMPL_API #define IMGUI_IMPL_API IMGUI_API #endif // Helper Macros #ifndef IM_ASSERT #include <assert.h> #define IM_ASSERT(_EXPR) assert(_EXPR) // You can override the default assert handler by editing imconfig.h #endif #if defined(__clang__) || defined(__GNUC__) #define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1))) // Apply printf-style warnings to user functions. #define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0))) #else #define IM_FMTARGS(FMT) #define IM_FMTLIST(FMT) #endif #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) // Size of a static C-style array. Don't use on pointers! #define IM_OFFSETOF(_TYPE,_MEMBER) ((size_t)&(((_TYPE*)0)->_MEMBER)) // Offset of _MEMBER within _TYPE. Standardized as offsetof() in modern C++. // Warnings #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wold-style-cast" #elif defined(__GNUC__) && __GNUC__ >= 8 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wclass-memaccess" #endif //----------------------------------------------------------------------------- // Forward declarations and basic types //----------------------------------------------------------------------------- struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) struct ImDrawData; // All draw command lists required to render the frame struct ImDrawList; // A single draw command list (generally one per window, conceptually you may see this as a dynamic "mesh" builder) struct ImDrawListSharedData; // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) struct ImFont; // Runtime data for a single font within a parent ImFontAtlas struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader struct ImFontConfig; // Configuration data when adding a font or merging fonts struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 (*obsolete* please avoid using) #ifndef ImTextureID typedef void* ImTextureID; // User data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) #endif struct ImGuiContext; // ImGui context (opaque) struct ImGuiIO; // Main configuration and I/O between your application and ImGui struct ImGuiInputTextCallbackData; // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use) struct ImGuiListClipper; // Helper to manually clip large list of items struct ImGuiOnceUponAFrame; // Helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro struct ImGuiPayload; // User data payload for drag and drop operations struct ImGuiSizeCallbackData; // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use) struct ImGuiStorage; // Helper for key->value storage struct ImGuiStyle; // Runtime data for styling/colors struct ImGuiTextFilter; // Helper to parse and apply text filters (e.g. "aaaaa[,bbbb][,ccccc]") struct ImGuiTextBuffer; // Helper to hold and append into a text buffer (~string builder) // Typedefs and Enums/Flags (declared as int for compatibility with old C++, to allow using as flags and to not pollute the top of this file) // Use your programming IDE "Go to definition" facility on the names of the center columns to find the actual flags/enum lists. typedef unsigned int ImGuiID; // Unique ID used by widgets (typically hashed from a stack of string) typedef unsigned short ImWchar; // Character for keyboard input/display typedef int ImGuiCol; // -> enum ImGuiCol_ // Enum: A color identifier for styling typedef int ImGuiCond; // -> enum ImGuiCond_ // Enum: A condition for Set*() typedef int ImGuiDataType; // -> enum ImGuiDataType_ // Enum: A primary data type typedef int ImGuiDir; // -> enum ImGuiDir_ // Enum: A cardinal direction typedef int ImGuiKey; // -> enum ImGuiKey_ // Enum: A key identifier (ImGui-side enum) typedef int ImGuiNavInput; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation typedef int ImGuiMouseCursor; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling typedef int ImDrawCornerFlags; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect*() etc. typedef int ImDrawListFlags; // -> enum ImDrawListFlags_ // Flags: for ImDrawList typedef int ImFontAtlasFlags; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas typedef int ImGuiBackendFlags; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags typedef int ImGuiColorEditFlags; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit*(), ColorPicker*() typedef int ImGuiColumnsFlags; // -> enum ImGuiColumnsFlags_ // Flags: for Columns(), BeginColumns() typedef int ImGuiConfigFlags; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags typedef int ImGuiComboFlags; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo() typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: for *DragDrop*() typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText*() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() typedef int ImGuiTabBarFlags; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar() typedef int ImGuiTabItemFlags; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem() typedef int ImGuiTreeNodeFlags; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode*(),CollapsingHeader() typedef int ImGuiWindowFlags; // -> enum ImGuiWindowFlags_ // Flags: for Begin*() typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData *data); typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Scalar data types typedef signed int ImS32; // 32-bit signed integer == int typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors) #if defined(_MSC_VER) && !defined(__clang__) typedef signed __int64 ImS64; // 64-bit signed integer (pre and post C++11 with Visual Studio) typedef unsigned __int64 ImU64; // 64-bit unsigned integer (pre and post C++11 with Visual Studio) #elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100) #include <stdint.h> typedef int64_t ImS64; // 64-bit signed integer (pre C++11) typedef uint64_t ImU64; // 64-bit unsigned integer (pre C++11) #else typedef signed long long ImS64; // 64-bit signed integer (post C++11) typedef unsigned long long ImU64; // 64-bit unsigned integer (post C++11) #endif // 2D vector (often used to store positions, sizes, etc.) struct ImVec2 { float x, y; ImVec2() { x = y = 0.0f; } ImVec2(float _x, float _y) { x = _x; y = _y; } float operator[] (size_t i) const { IM_ASSERT(i <= 1); return (&x)[i]; } // We very rarely use this [] operator, the assert overhead is fine. #ifdef IM_VEC2_CLASS_EXTRA IM_VEC2_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2. #endif }; // 4D vector (often used to store floating-point colors) struct ImVec4 { float x, y, z, w; ImVec4() { x = y = z = w = 0.0f; } ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } #ifdef IM_VEC4_CLASS_EXTRA IM_VEC4_CLASS_EXTRA // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4. #endif }; //----------------------------------------------------------------------------- // ImGui: Dear ImGui end-user API // (Inside a namespace so you can add extra functions in your own separate file. Please don't modify imgui.cpp/.h!) //----------------------------------------------------------------------------- namespace ImGui { // Context creation and access // Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between imgui contexts. // All those functions are not reliant on the current context. IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL); IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context IMGUI_API ImGuiContext* GetCurrentContext(); IMGUI_API void SetCurrentContext(ImGuiContext* ctx); IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert); // Main IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags) IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame. IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until Update()/EndFrame(). IMGUI_API void EndFrame(); // ends the ImGui frame. automatically called by Update(), you likely don't need to call that yourself directly. If you don't need to render data (skipping rendering) you may call EndFrame() but you'll have wasted CPU already! If you don't need to render, better to not create any imgui windows and not call NewFrame() at all! IMGUI_API void Render(); // ends the ImGui frame, finalize the draw data. (Obsolete: optionally call io.RenderDrawListsFn if set. Nowadays, prefer calling your render function yourself.) IMGUI_API ImDrawData* GetDrawData(); // valid after Update() and until the next call to NewFrame(). this is what you have to render. (Obsolete: this used to be passed to your io.RenderDrawListsFn() function.) // Demo, Debug, Information IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create demo/test window (previously called ShowTestWindow). demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application! IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create about window. display Dear ImGui version, credits and build/system information. IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create metrics window. display Dear ImGui internals: draw commands (with individual draw calls and vertices), window list, basic internal state, etc. IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles. IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts. IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls). IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.23" // Styles IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default) IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font // Windows // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack. // - You may append multiple times to the same window during the same frame. // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window, // which clicking will set the boolean to false when clicked. // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting // anything to the window. Always call a matching End() for each Begin() call, regardless of its return value! // [this is due to legacy reason and is inconsistent with most other functions such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. // where the EndXXX call should only be called if the corresponding BeginXXX function returned true.] // - Note that the bottom of window stack always contains a window called "Debug". IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); IMGUI_API void End(); // Child Windows // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child. // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400). // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window. // Always call a matching EndChild() for each BeginChild() call, regardless of its return value [this is due to legacy reason and is inconsistent with most other functions such as BeginMenu/EndMenu, BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function returned true.] IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags flags = 0); IMGUI_API void EndChild(); // Windows Utilities // - "current window" = the window we are appending into while inside a Begin()/End() block. "next window" = next window we will Begin() into. IMGUI_API bool IsWindowAppearing(); IMGUI_API bool IsWindowCollapsed(); IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options. IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ! IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the window, to append your own drawing primitives IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API) IMGUI_API ImVec2 GetWindowSize(); // get current window size IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x) IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y) IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() IMGUI_API float GetContentRegionAvailWidth(); // IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates IMGUI_API float GetWindowContentRegionWidth(); // IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0,0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc. IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ enforce the range of scrollbars). not including window decorations (title bar, menu bar, etc.). set an axis to 0.0f to leave it automatic. call before Begin() IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin() IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily modify ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground. IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position. IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. // Windows Scrolling IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead. IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. // Parameters stacks (shared) IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font IMGUI_API void PopFont(); IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); IMGUI_API void PopStyleColor(int count = 1); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); IMGUI_API void PopStyleVar(int count = 1); IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in. IMGUI_API ImFont* GetFont(); // get current font IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied // Parameters stacks (current window) IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) IMGUI_API void PopItemWidth(); IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space IMGUI_API void PopTextWrapPos(); IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets IMGUI_API void PopAllowKeyboardFocus(); IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. IMGUI_API void PopButtonRepeat(); // Cursor / Layout // - By "cursor" we mean the current output position. // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down. IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. IMGUI_API void SameLine(float local_pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates. IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context. IMGUI_API void Spacing(); // add vertical spacing. IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into. IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if != 0 IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if != 0 IMGUI_API void BeginGroup(); // lock horizontal starting position IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position) IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc. IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList:: IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system. IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.) IMGUI_API void SetCursorPosY(float local_y); // IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item) IMGUI_API float GetTextLineHeight(); // ~ FontSize IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text) IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2 IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets) // ID stack/scopes // - Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most // likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them. // - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others. // - In this header file we use the "label"/"name" terminology to denote a string that will be displayed and used as an ID, // whereas "str_id" denote a string that is only used as an ID and not normally displayed. IMGUI_API void PushID(const char* str_id); // push string identifier into the ID stack. IDs == hash of the entire stack! IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack. IMGUI_API void PushID(int int_id); // push integer into the ID stack. IMGUI_API void PopID(); // pop from the ID stack. IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); IMGUI_API ImGuiID GetID(const void* ptr_id); // Widgets: Text IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text. IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // simple formatted text IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1); IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text() IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1); // Widgets: Main // - Most widgets return true when the value has been changed or when pressed/selected IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); // button behavior without the visuals, useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.) IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding IMGUI_API bool Checkbox(const char* label, bool* v); IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; } IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses // Widgets: Combo Box // - The new BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items. // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0); IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true! IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1); IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0" IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1); // Widgets: Drags // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision). IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, float power = 1.0f); IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); // If v_min >= v_max we have no bound IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d"); IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL); IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* v, float v_speed, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f); IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min = NULL, const void* v_max = NULL, const char* format = NULL, float power = 1.0f); // Widgets: Sliders // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds. // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc. IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display. Use power!=1.0 for power curve sliders IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg"); IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d"); IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d"); IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d"); IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d"); IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f); IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f); IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", float power = 1.0f); IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d"); IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format = NULL, float power = 1.0f); // Widgets: Input with Keyboard // - If you want to use InputText() with a dynamic string type such as std::string or your own, see misc/cpp/imgui_stdlib.h IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL); IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0f, double step_fast = 0.0f, const char* format = "%.6f", ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* v, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step = NULL, const void* step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags extra_flags = 0); // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little colored preview square that can be left-clicked to open a picker, and right-clicked to open an option menu.) // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can the pass the address of a first float element out of a contiguous structure, e.g. &myvector.x IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0); IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL); IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0)); // display a colored square/button, hover for details, return true when pressed. IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls. // Widgets: Trees // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents. IMGUI_API bool TreeNode(const char* label); IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to completely decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // " IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2); IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. IMGUI_API void TreePush(const void* ptr_id = NULL); // " IMGUI_API void TreePop(); // ~ Unindent()+PopId() IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state. IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header // Widgets: Selectables // - A selectable highlights when hovered, and can display another color when selected. // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper. // Widgets: List Boxes // - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them. IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1); IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards. IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true! // Widgets: Data Plotting IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float)); IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0)); // Widgets: Value() Helpers. // - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) IMGUI_API void Value(const char* prefix, bool b); IMGUI_API void Value(const char* prefix, int v); IMGUI_API void Value(const char* prefix, unsigned int v); IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); // Widgets: Menus IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true! IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window). IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true! IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true! IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL // Tooltips IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items). IMGUI_API void EndTooltip(); IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). overidde any previous call to SetTooltip(). IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1); // Popups, Modals // The properties of popups windows are: // - They block normal mouse hovering detection outside them. (*) // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. // - Their visibility state (~bool) is held internally by imgui instead of being held by the programmer as we are used to with regular Begin() calls. // User can manipulate the visibility state by calling OpenPopup(). // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even when normally blocked by a popup. // Those three properties are connected. The library needs to hold their visibility state because it can close popups at any time. IMGUI_API void OpenPopup(const char* str_id); // call to mark popup as open (don't call every frame!). popups are closed when user click outside, or if CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. By default, Selectable()/MenuItem() are calling CloseCurrentPopup(). Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returns true! IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp! IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, int mouse_button = 1, bool also_over_items = true); // helper to open and begin popup when clicked on current window. IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (where there are no imgui windows). IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // modal dialog (regular window with title bar, block interactions behind the modal window, can't close the modal window by clicking outside) IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true! IMGUI_API bool OpenPopupOnItemClick(const char* str_id = NULL, int mouse_button = 1); // helper to open popup when clicked on last item (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors). return true when just opened. IMGUI_API bool IsPopupOpen(const char* str_id); // return true if the popup is open at the current begin-ed level of the popup stack. IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. // Columns // - You can also use SameLine(pos_x) to mimic simplified columns. // - The columns API is work-in-progress and rather lacking (columns are arguably the worst part of dear imgui at the moment!) IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished IMGUI_API int GetColumnIndex(); // get current column index IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column IMGUI_API int GetColumnsCount(); // Tab Bars, Tabs // [BETA API] API may evolve! IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true! IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0);// create a Tab. Returns true if the Tab is selected. IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true! IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name. // Logging/Capture // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging. IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty (stdout) IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard IMGUI_API void LogFinish(); // stop logging (close file, etc.) IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed) // Drag and Drop // [BETA API] API may evolve! IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource() IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t size, ImGuiCond cond = 0);// type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true! IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget() IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released. IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true! IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type. // Clipping IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); IMGUI_API void PopClipRect(); // Focus, Activation // - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item" IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window. IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget. // Item/Widgets Utilities // - Most of the functions are referring to the last/previous item we submitted. // - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions. IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options. IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false) IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation? IMGUI_API bool IsItemClicked(int mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered() IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling) IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets. IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing. IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item). IMGUI_API bool IsAnyItemHovered(); IMGUI_API bool IsAnyItemActive(); IMGUI_API bool IsAnyItemFocused(); IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space) IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space) IMGUI_API ImVec2 GetItemRectSize(); // get size of last item IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. // Miscellaneous Utilities IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame. IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame. IMGUI_API ImDrawList* GetOverlayDrawList(); // this draw list will be the last rendered one, useful to quickly draw overlays shapes/text IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances IMGUI_API const char* GetStyleColorName(ImGuiCol idx); IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it) IMGUI_API ImGuiStorage* GetStateStorage(); IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can. IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window) // Color Utilities IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); // Inputs Utilities IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index]. note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]! IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down). if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down).. IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate IMGUI_API bool IsMouseDown(int button); // is mouse button held (0=left, 1=right, 2=middle) IMGUI_API bool IsAnyMouseDown(); // is any mouse button held IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) (0=left, 1=right, 2=middle) IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block. IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse position at the time of opening popup we have BeginPopup() into IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position. This is locked and return 0.0f until the mouse moves past a distance threshold at least once. If lock_threshold < -1.0f uses io.MouseDraggingThreshold IMGUI_API void ResetMouseDragDelta(int button = 0); // IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Update(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type IMGUI_API void CaptureKeyboardFromApp(bool want_capture_keyboard_value = true); // attention: misleading name! manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard_value"; after the next NewFrame() call. IMGUI_API void CaptureMouseFromApp(bool want_capture_mouse_value = true); // attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse_value;" after the next NewFrame() call. // Clipboard Utilities (also see the LogToClipboard() function to capture or output text data to the clipboard) IMGUI_API const char* GetClipboardText(); IMGUI_API void SetClipboardText(const char* text); // Settings/.Ini Utilities // - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini"). // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually. IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename). IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source. IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. // Memory Utilities // - All those functions are not reliant on the current context. // - If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again. IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data = NULL); IMGUI_API void* MemAlloc(size_t size); IMGUI_API void MemFree(void* ptr); } // namespace ImGui //----------------------------------------------------------------------------- // Flags & Enumerations //----------------------------------------------------------------------------- // Flags for ImGui::Begin() enum ImGuiWindowFlags_ { ImGuiWindowFlags_None = 0, ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame ImGuiWindowFlags_NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file ImGuiWindowFlags_NoMouseInputs = 1 << 9, // Disable catching mouse, hovering test with pass through. ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) ImGuiWindowFlags_NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window ImGuiWindowFlags_NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB) ImGuiWindowFlags_UnsavedDocument = 1 << 20, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker. ImGuiWindowFlags_NoNav = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, ImGuiWindowFlags_NoDecoration = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse, ImGuiWindowFlags_NoInputs = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus, // [Internal] ImGuiWindowFlags_NavFlattened = 1 << 23, // [BETA] Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!) ImGuiWindowFlags_ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild() ImGuiWindowFlags_Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip() ImGuiWindowFlags_Popup = 1 << 26, // Don't use! For internal use by BeginPopup() ImGuiWindowFlags_Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal() ImGuiWindowFlags_ChildMenu = 1 << 28 // Don't use! For internal use by BeginMenu() // [Obsolete] //ImGuiWindowFlags_ShowBorders = 1 << 7, // --> Set style.FrameBorderSize=1.0f / style.WindowBorderSize=1.0f to enable borders around windows and items //ImGuiWindowFlags_ResizeFromAnySide = 1 << 17, // --> Set io.ConfigWindowsResizeFromEdges and make sure mouse cursors are supported by back-end (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) }; // Flags for ImGui::InputText() enum ImGuiInputTextFlags_ { ImGuiInputTextFlags_None = 0, ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Callback on pressing TAB (for completion handling) ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Callback on pressing Up/Down arrows (for history handling) ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Callback on each iteration. User code may query cursor position, modify text buffer. ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter). ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' ImGuiInputTextFlags_NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID(). ImGuiInputTextFlags_CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input) ImGuiInputTextFlags_CallbackResize = 1 << 18, // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this) // [Internal] ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() }; // Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() enum ImGuiTreeNodeFlags_ { ImGuiTreeNodeFlags_None = 0, ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) ImGuiTreeNodeFlags_AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow ImGuiTreeNodeFlags_FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding(). //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 11, // FIXME: TODO: Extend hit box horizontally even if not framed //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 12, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiTreeNodeFlags_AllowOverlapMode = ImGuiTreeNodeFlags_AllowItemOverlap #endif }; // Flags for ImGui::Selectable() enum ImGuiSelectableFlags_ { ImGuiSelectableFlags_None = 0, ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) ImGuiSelectableFlags_AllowDoubleClick = 1 << 2, // Generate press events on double clicks too ImGuiSelectableFlags_Disabled = 1 << 3 // Cannot be selected, display greyed out text }; // Flags for ImGui::BeginCombo() enum ImGuiComboFlags_ { ImGuiComboFlags_None = 0, ImGuiComboFlags_PopupAlignLeft = 1 << 0, // Align the popup toward the left by default ImGuiComboFlags_HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() ImGuiComboFlags_HeightRegular = 1 << 2, // Max ~8 items visible (default) ImGuiComboFlags_HeightLarge = 1 << 3, // Max ~20 items visible ImGuiComboFlags_HeightLargest = 1 << 4, // As many fitting items as possible ImGuiComboFlags_NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button ImGuiComboFlags_NoPreview = 1 << 6, // Display only a square arrow button ImGuiComboFlags_HeightMask_ = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest }; // Flags for ImGui::BeginTabBar() enum ImGuiTabBarFlags_ { ImGuiTabBarFlags_None = 0, ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabBarFlags_NoTabListPopupButton = 1 << 3, ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 5, // Resize tabs when they don't fit ImGuiTabBarFlags_FittingPolicyScroll = 1 << 6, // Add scroll buttons when tabs don't fit ImGuiTabBarFlags_FittingPolicyMask_ = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll, ImGuiTabBarFlags_FittingPolicyDefault_ = ImGuiTabBarFlags_FittingPolicyResizeDown }; // Flags for ImGui::BeginTabItem() enum ImGuiTabItemFlags_ { ImGuiTabItemFlags_None = 0, ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. Also: tab is selected on closure and closure is deferred by one frame to allow code to undo it without flicker. ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programatically make the tab selected when calling BeginTabItem() ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabItemFlags_NoPushId = 1 << 3 // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() }; // Flags for ImGui::IsWindowFocused() enum ImGuiFocusedFlags_ { ImGuiFocusedFlags_None = 0, ImGuiFocusedFlags_ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused ImGuiFocusedFlags_RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy) ImGuiFocusedFlags_AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use ImGui::GetIO().WantCaptureMouse instead. ImGuiFocusedFlags_RootAndChildWindows = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows }; // Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered() // Note: if you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that. Please read the FAQ! // Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls. enum ImGuiHoveredFlags_ { ImGuiHoveredFlags_None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. ImGuiHoveredFlags_ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered ImGuiHoveredFlags_RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) ImGuiHoveredFlags_AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered ImGuiHoveredFlags_AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window //ImGuiHoveredFlags_AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. ImGuiHoveredFlags_AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window ImGuiHoveredFlags_AllowWhenDisabled = 1 << 7, // Return true even if the item is disabled ImGuiHoveredFlags_RectOnly = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped, ImGuiHoveredFlags_RootAndChildWindows = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows }; // Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload() enum ImGuiDragDropFlags_ { ImGuiDragDropFlags_None = 0, // BeginDragDropSource() flags ImGuiDragDropFlags_SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior. ImGuiDragDropFlags_SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item. ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. ImGuiDragDropFlags_SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. ImGuiDragDropFlags_SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. ImGuiDragDropFlags_SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) // AcceptDragDropPayload() flags ImGuiDragDropFlags_AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target. ImGuiDragDropFlags_AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. ImGuiDragDropFlags_AcceptPeekOnly = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect // For peeking ahead and inspecting the payload before delivery. }; // Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui. #define IMGUI_PAYLOAD_TYPE_COLOR_3F "_COL3F" // float[3]: Standard type for colors, without alpha. User code may use this type. #define IMGUI_PAYLOAD_TYPE_COLOR_4F "_COL4F" // float[4]: Standard type for colors. User code may use this type. // A primary data type enum ImGuiDataType_ { ImGuiDataType_S32, // int ImGuiDataType_U32, // unsigned int ImGuiDataType_S64, // long long, __int64 ImGuiDataType_U64, // unsigned long long, unsigned __int64 ImGuiDataType_Float, // float ImGuiDataType_Double, // double ImGuiDataType_COUNT }; // A cardinal direction enum ImGuiDir_ { ImGuiDir_None = -1, ImGuiDir_Left = 0, ImGuiDir_Right = 1, ImGuiDir_Up = 2, ImGuiDir_Down = 3, ImGuiDir_COUNT }; // User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array enum ImGuiKey_ { ImGuiKey_Tab, ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow, ImGuiKey_PageUp, ImGuiKey_PageDown, ImGuiKey_Home, ImGuiKey_End, ImGuiKey_Insert, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_A, // for text edit CTRL+A: select all ImGuiKey_C, // for text edit CTRL+C: copy ImGuiKey_V, // for text edit CTRL+V: paste ImGuiKey_X, // for text edit CTRL+X: cut ImGuiKey_Y, // for text edit CTRL+Y: redo ImGuiKey_Z, // for text edit CTRL+Z: undo ImGuiKey_COUNT }; // Gamepad/Keyboard directional navigation // Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays. // Gamepad: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Back-end: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). // Read instructions in imgui.cpp for more details. Download PNG/PSD at http://goo.gl/9LgVZW. enum ImGuiNavInput_ { // Gamepad Mapping ImGuiNavInput_Activate, // activate / open / toggle / tweak value // e.g. Cross (PS4), A (Xbox), A (Switch), Space (Keyboard) ImGuiNavInput_Cancel, // cancel / close / exit // e.g. Circle (PS4), B (Xbox), B (Switch), Escape (Keyboard) ImGuiNavInput_Input, // text input / on-screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard) ImGuiNavInput_Menu, // tap: toggle menu / hold: focus, move, resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard) ImGuiNavInput_DpadLeft, // move / tweak / resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard) ImGuiNavInput_DpadRight, // ImGuiNavInput_DpadUp, // ImGuiNavInput_DpadDown, // ImGuiNavInput_LStickLeft, // scroll / move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down ImGuiNavInput_LStickRight, // ImGuiNavInput_LStickUp, // ImGuiNavInput_LStickDown, // ImGuiNavInput_FocusPrev, // next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) ImGuiNavInput_FocusNext, // prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) ImGuiNavInput_TweakSlow, // slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch) ImGuiNavInput_TweakFast, // faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch) // [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them. // Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from io.KeysDown[] instead of io.NavInputs[]. ImGuiNavInput_KeyMenu_, // toggle menu // = io.KeyAlt ImGuiNavInput_KeyLeft_, // move left // = Arrow keys ImGuiNavInput_KeyRight_, // move right ImGuiNavInput_KeyUp_, // move up ImGuiNavInput_KeyDown_, // move down ImGuiNavInput_COUNT, ImGuiNavInput_InternalStart_ = ImGuiNavInput_KeyMenu_ }; // Configuration flags stored in io.ConfigFlags. Set by user/application. enum ImGuiConfigFlags_ { ImGuiConfigFlags_None = 0, ImGuiConfigFlags_NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeysDown[]. ImGuiConfigFlags_NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[]. Back-end also needs to set ImGuiBackendFlags_HasGamepad. ImGuiConfigFlags_NavEnableSetMousePos = 1 << 2, // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth. ImGuiConfigFlags_NavNoCaptureKeyboard = 1 << 3, // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set. ImGuiConfigFlags_NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the back-end. ImGuiConfigFlags_NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility. Use if the back-end cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead. // User storage (to allow your back-end/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core ImGui) ImGuiConfigFlags_IsSRGB = 1 << 20, // Application is SRGB-aware. ImGuiConfigFlags_IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse. }; // Back-end capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom back-end. enum ImGuiBackendFlags_ { ImGuiBackendFlags_None = 0, ImGuiBackendFlags_HasGamepad = 1 << 0, // Back-end supports gamepad and currently has one connected. ImGuiBackendFlags_HasMouseCursors = 1 << 1, // Back-end supports honoring GetMouseCursor() value to change the OS cursor shape. ImGuiBackendFlags_HasSetMousePos = 1 << 2 // Back-end supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set). }; // Enumeration for PushStyleColor() / PopStyleColor() enum ImGuiCol_ { ImGuiCol_Text, ImGuiCol_TextDisabled, ImGuiCol_WindowBg, // Background of normal windows ImGuiCol_ChildBg, // Background of child windows ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows ImGuiCol_Border, ImGuiCol_BorderShadow, ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive, ImGuiCol_TitleBg, ImGuiCol_TitleBgActive, ImGuiCol_TitleBgCollapsed, ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, ImGuiCol_CheckMark, ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive, ImGuiCol_Header, ImGuiCol_HeaderHovered, ImGuiCol_HeaderActive, ImGuiCol_Separator, ImGuiCol_SeparatorHovered, ImGuiCol_SeparatorActive, ImGuiCol_ResizeGrip, ImGuiCol_ResizeGripHovered, ImGuiCol_ResizeGripActive, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive, ImGuiCol_PlotLines, ImGuiCol_PlotLinesHovered, ImGuiCol_PlotHistogram, ImGuiCol_PlotHistogramHovered, ImGuiCol_TextSelectedBg, ImGuiCol_DragDropTarget, ImGuiCol_NavHighlight, // Gamepad/keyboard: current highlighted item ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB ImGuiCol_NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active ImGuiCol_ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active ImGuiCol_COUNT // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiCol_ChildWindowBg = ImGuiCol_ChildBg, ImGuiCol_Column = ImGuiCol_Separator, ImGuiCol_ColumnHovered = ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive = ImGuiCol_SeparatorActive , ImGuiCol_ModalWindowDarkening = ImGuiCol_ModalWindowDimBg //ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered, // [unused since 1.60+] the close button now uses regular button colors. //ImGuiCol_ComboBg, // [unused since 1.53+] ComboBg has been merged with PopupBg, so a redirect isn't accurate. #endif }; // Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. // NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly. // NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. enum ImGuiStyleVar_ { // Enum name ......................// Member in ImGuiStyle structure (see ImGuiStyle for descriptions) ImGuiStyleVar_Alpha, // float Alpha ImGuiStyleVar_WindowPadding, // ImVec2 WindowPadding ImGuiStyleVar_WindowRounding, // float WindowRounding ImGuiStyleVar_WindowBorderSize, // float WindowBorderSize ImGuiStyleVar_WindowMinSize, // ImVec2 WindowMinSize ImGuiStyleVar_WindowTitleAlign, // ImVec2 WindowTitleAlign ImGuiStyleVar_ChildRounding, // float ChildRounding ImGuiStyleVar_ChildBorderSize, // float ChildBorderSize ImGuiStyleVar_PopupRounding, // float PopupRounding ImGuiStyleVar_PopupBorderSize, // float PopupBorderSize ImGuiStyleVar_FramePadding, // ImVec2 FramePadding ImGuiStyleVar_FrameRounding, // float FrameRounding ImGuiStyleVar_FrameBorderSize, // float FrameBorderSize ImGuiStyleVar_ItemSpacing, // ImVec2 ItemSpacing ImGuiStyleVar_ItemInnerSpacing, // ImVec2 ItemInnerSpacing ImGuiStyleVar_IndentSpacing, // float IndentSpacing ImGuiStyleVar_ScrollbarSize, // float ScrollbarSize ImGuiStyleVar_ScrollbarRounding, // float ScrollbarRounding ImGuiStyleVar_GrabMinSize, // float GrabMinSize ImGuiStyleVar_GrabRounding, // float GrabRounding ImGuiStyleVar_TabRounding, // float TabRounding ImGuiStyleVar_ButtonTextAlign, // ImVec2 ButtonTextAlign ImGuiStyleVar_COUNT // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiStyleVar_Count_ = ImGuiStyleVar_COUNT, ImGuiStyleVar_ChildWindowRounding = ImGuiStyleVar_ChildRounding #endif }; // Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() enum ImGuiColorEditFlags_ { ImGuiColorEditFlags_None = 0, ImGuiColorEditFlags_NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer). ImGuiColorEditFlags_NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square. ImGuiColorEditFlags_NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. ImGuiColorEditFlags_NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs) ImGuiColorEditFlags_NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square). ImGuiColorEditFlags_NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. ImGuiColorEditFlags_NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). ImGuiColorEditFlags_NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead. ImGuiColorEditFlags_NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source. // User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup. ImGuiColorEditFlags_AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. ImGuiColorEditFlags_AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque. ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque. ImGuiColorEditFlags_HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well). ImGuiColorEditFlags_RGB = 1 << 20, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX. ImGuiColorEditFlags_HSV = 1 << 21, // [Inputs] // " ImGuiColorEditFlags_HEX = 1 << 22, // [Inputs] // " ImGuiColorEditFlags_Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. ImGuiColorEditFlags_Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. ImGuiColorEditFlags_PickerHueBar = 1 << 25, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value. ImGuiColorEditFlags_PickerHueWheel = 1 << 26, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value. // [Internal] Masks ImGuiColorEditFlags__InputsMask = ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_HSV|ImGuiColorEditFlags_HEX, ImGuiColorEditFlags__DataTypeMask = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_Float, ImGuiColorEditFlags__PickerMask = ImGuiColorEditFlags_PickerHueWheel|ImGuiColorEditFlags_PickerHueBar, ImGuiColorEditFlags__OptionsDefault = ImGuiColorEditFlags_Uint8|ImGuiColorEditFlags_RGB|ImGuiColorEditFlags_PickerHueBar // Change application default using SetColorEditOptions() }; // Enumeration for GetMouseCursor() // User code may request binding to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here enum ImGuiMouseCursor_ { ImGuiMouseCursor_None = -1, ImGuiMouseCursor_Arrow = 0, ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. ImGuiMouseCursor_ResizeAll, // (Unused by imgui functions) ImGuiMouseCursor_ResizeNS, // When hovering over an horizontal border ImGuiMouseCursor_ResizeEW, // When hovering over a vertical border or a column ImGuiMouseCursor_ResizeNESW, // When hovering over the bottom-left corner of a window ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window ImGuiMouseCursor_Hand, // (Unused by imgui functions. Use for e.g. hyperlinks) ImGuiMouseCursor_COUNT // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiMouseCursor_Count_ = ImGuiMouseCursor_COUNT #endif }; // Enumateration for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions // Represent a condition. // Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. enum ImGuiCond_ { ImGuiCond_Always = 1 << 0, // Set the variable ImGuiCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) ImGuiCond_FirstUseEver = 1 << 2, // Set the variable if the object/window has no persistently saved data (no entry in .ini file) ImGuiCond_Appearing = 1 << 3 // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS , ImGuiSetCond_Always = ImGuiCond_Always, ImGuiSetCond_Once = ImGuiCond_Once, ImGuiSetCond_FirstUseEver = ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing = ImGuiCond_Appearing #endif }; //----------------------------------------------------------------------------- // ImGuiStyle // You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame(). // During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, // and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors. //----------------------------------------------------------------------------- struct ImGuiStyle { float Alpha; // Global alpha applies to everything in ImGui. ImVec2 WindowPadding; // Padding within a window. float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints(). ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows. float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding) float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets). float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly). ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines. ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label). ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar. float ScrollbarRounding; // Radius of grab corners for scrollbar. float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. float TabBorderSize; // Thickness of border around tabs. ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly! float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. bool AntiAliasedFill; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. ImVec4 Colors[ImGuiCol_COUNT]; IMGUI_API ImGuiStyle(); IMGUI_API void ScaleAllSizes(float scale_factor); }; //----------------------------------------------------------------------------- // ImGuiIO // Communicate most settings and inputs/outputs to Dear ImGui using this structure. // Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage. //----------------------------------------------------------------------------- struct ImGuiIO { //------------------------------------------------------------------ // Configuration (fill once) // Default value //------------------------------------------------------------------ ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by back-end (imgui_impl_xxx files or custom back-end) to communicate features supported by the back-end. ImVec2 DisplaySize; // <unset> // Main display size, in pixels. For clamping windows positions. float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. float IniSavingRate; // = 5.0f // Minimum time between saving positions/sizes to .ini file, in seconds. const char* IniFilename; // = "imgui.ini" // Path to .ini file. Set NULL to disable automatic .ini loading/saving, if e.g. you want to manually load/save from memory. const char* LogFilename; // = "imgui_log.txt"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified). float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging. int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state. float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds. void* UserData; // = NULL // Store your own data for retrieval by callbacks. ImFontAtlas*Fonts; // <auto> // Load, rasterize and pack one or more fonts into a single texture. float FontGlobalScale; // = 1.0f // Global scale all fonts bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0]. ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. ImVec2 DisplayVisibleMin; // <unset> // [OBSOLETE] If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. ImVec2 DisplayVisibleMax; // <unset> // [OBSOLETE] Just use io.DisplaySize! If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize // Miscellaneous configuration options bool MouseDrawCursor; // = false // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by back-end implementations. bool ConfigMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl (was called io.OptMacOSXBehaviors prior to 1.63) bool ConfigInputTextCursorBlink; // = true // Set to false to disable blinking cursor, for users who consider it distracting. (was called: io.OptCursorBlink prior to 1.63) bool ConfigWindowsResizeFromEdges; // = true // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be the a per-window ImGuiWindowFlags_ResizeFromAnySide flag) bool ConfigWindowsMoveFromTitleBarOnly;// = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected. //------------------------------------------------------------------ // Platform Functions // (the imgui_impl_xxxx back-end files are setting those up for you) //------------------------------------------------------------------ // Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + User data for back-end/wrappers to store their own stuff. const char* BackendPlatformName; // = NULL const char* BackendRendererName; // = NULL void* BackendPlatformUserData; // = NULL void* BackendRendererUserData; // = NULL void* BackendLanguageUserData; // = NULL // Optional: Access OS clipboard // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) const char* (*GetClipboardTextFn)(void* user_data); void (*SetClipboardTextFn)(void* user_data, const char* text); void* ClipboardUserData; // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows) // (default to use native imm32 api on Windows) void (*ImeSetInputScreenPosFn)(int x, int y); void* ImeWindowHandle; // = NULL // (Windows) Set this to your HWND to get automatic IME cursor positioning. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // [OBSOLETE since 1.60+] Rendering function, will be automatically called in Update(). Please call your rendering function yourself now! // You can obtain the ImDrawData* by calling ImGui::GetDrawData() after Update(). See example applications if you are unsure of how to implement this. void (*RenderDrawListsFn)(ImDrawData* data); #else // This is only here to keep ImGuiIO the same size, so that IMGUI_DISABLE_OBSOLETE_FUNCTIONS can exceptionally be used outside of imconfig.h. void* RenderDrawListsFnUnused; #endif //------------------------------------------------------------------ // Input - Fill before calling NewFrame() //------------------------------------------------------------------ ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.) bool MouseDown[5]; // Mouse buttons: 0=left, 1=right, 2=middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. float MouseWheel; // Mouse wheel Vertical: 1 unit scrolls about 5 lines text. float MouseWheelH; // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends. bool KeyCtrl; // Keyboard modifier pressed: Control bool KeyShift; // Keyboard modifier pressed: Shift bool KeyAlt; // Keyboard modifier pressed: Alt bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows bool KeysDown[512]; // Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys). ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs (keyboard keys will be auto-mapped and be written here by ImGui::NewFrame, all values will be cleared back to zero in ImGui::EndFrame) // Functions IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[] IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually //------------------------------------------------------------------ // Output - Retrieve after calling NewFrame() //------------------------------------------------------------------ bool WantCaptureMouse; // When io.WantCaptureMouse is true, imgui will use the mouse inputs, do not dispatch them to your main game/application (in both cases, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, imgui will use the keyboard inputs, do not dispatch them to your main game/application (in both cases, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). bool WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled. bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. IMPORTANT: You need to clear io.WantSaveIniSettings yourself. bool NavActive; // Directional navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag. bool NavVisible; // Directional navigation is visible and allowed (will handle ImGuiKey_NavXXX events). float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames int MetricsRenderVertices; // Vertices output during last call to Update() int MetricsRenderIndices; // Indices output during last call to Update() = number of triangles * 3 int MetricsRenderWindows; // Number of visible windows int MetricsActiveWindows; // Number of active windows int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts. ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. //------------------------------------------------------------------ // [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed! //------------------------------------------------------------------ ImVec2 MousePosPrev; // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) ImVec2 MouseClickedPos[5]; // Position at time of clicking double MouseClickedTime[5]; // Time of last click (used to figure out double-click) bool MouseClicked[5]; // Mouse button went from !Down to Down bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? bool MouseReleased[5]; // Mouse button went from Down to !Down bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) float MouseDownDurationPrev[5]; // Previous time the mouse button has been down ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed) float KeysDownDurationPrev[512]; // Previous duration the key has been down float NavInputsDownDuration[ImGuiNavInput_COUNT]; float NavInputsDownDurationPrev[ImGuiNavInput_COUNT]; IMGUI_API ImGuiIO(); }; //----------------------------------------------------------------------------- // Misc data structures //----------------------------------------------------------------------------- // Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. // The callback function should return 0 by default. // Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details) // - ImGuiInputTextFlags_CallbackCompletion: Callback on pressing TAB // - ImGuiInputTextFlags_CallbackHistory: Callback on pressing Up/Down arrows // - ImGuiInputTextFlags_CallbackAlways: Callback on each iteration // - ImGuiInputTextFlags_CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. // - ImGuiInputTextFlags_CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. struct ImGuiInputTextCallbackData { ImGuiInputTextFlags EventFlag; // One ImGuiInputTextFlags_Callback* // Read-only ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only void* UserData; // What user passed to InputText() // Read-only // Arguments for the different callback events // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary. // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state. ImWchar EventChar; // Character input // Read-write // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0; ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only // [Completion,History] char* Buf; // Text buffer // Read-write // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer! int BufTextLen; // Text length (in bytes) // Read-write // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length() int BufSize; // Buffer size (in bytes) = capacity+1 // Read-only // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1 bool BufDirty; // Set if you modify Buf/BufTextLen! // Write // [Completion,History,Always] int CursorPos; // // Read-write // [Completion,History,Always] int SelectionStart; // // Read-write // [Completion,History,Always] == to SelectionEnd when no selection) int SelectionEnd; // // Read-write // [Completion,History,Always] // Helper functions for text manipulation. // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection. IMGUI_API ImGuiInputTextCallbackData(); IMGUI_API void DeleteChars(int pos, int bytes_count); IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL); bool HasSelection() const { return SelectionStart != SelectionEnd; } }; // Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). // NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. struct ImGuiSizeCallbackData { void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() ImVec2 Pos; // Read-only. Window position, for reference. ImVec2 CurrentSize; // Read-only. Current window size. ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. }; // Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() struct ImGuiPayload { // Members void* Data; // Data (copied and owned by dear imgui) int DataSize; // Data size // [Internal] ImGuiID SourceId; // Source item id ImGuiID SourceParentId; // Source parent id (if available) int DataFrameCount; // Data timestamp char DataType[32+1]; // Data type tag (short user-supplied string, 32 characters max) bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets) bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item. ImGuiPayload() { Clear(); } void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; } bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; } bool IsPreview() const { return Preview; } bool IsDelivery() const { return Delivery; } }; //----------------------------------------------------------------------------- // Obsolete functions (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details) //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS namespace ImGui { // OBSOLETED in 1.66 (from Sep 2018) static inline void SetScrollHere(float center_ratio=0.5f){ SetScrollHereY(center_ratio); } // OBSOLETED in 1.63 (from Aug 2018) static inline bool IsItemDeactivatedAfterChange() { return IsItemDeactivatedAfterEdit(); } // OBSOLETED in 1.61 (from Apr 2018) IMGUI_API bool InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags = 0); // Use the 'const char* format' version instead of 'decimal_precision'! IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags = 0); IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags = 0); // OBSOLETED in 1.60 (from Dec 2017) static inline bool IsAnyWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); } static inline bool IsAnyWindowHovered() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } static inline ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = 0.f) { (void)on_edge; (void)outward; IM_ASSERT(0); return pos; } // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017) static inline void ShowTestWindow() { return ShowDemoWindow(); } static inline bool IsRootWindowFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); } static inline bool IsRootWindowOrAnyChildFocused() { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); } static inline void SetNextWindowContentWidth(float w) { SetNextWindowContentSize(ImVec2(w, 0.0f)); } static inline float GetItemsLineHeightWithSpacing() { return GetFrameHeightWithSpacing(); } // OBSOLETED in 1.52 (between Aug 2017 and Oct 2017) IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha_override = -1.0f, ImGuiWindowFlags flags = 0); // Use SetNextWindowSize(size, ImGuiCond_FirstUseEver) + SetNextWindowBgAlpha() instead. static inline bool IsRootWindowOrAnyChildHovered() { return IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); } static inline void AlignFirstTextHeightToWidgets() { AlignTextToFramePadding(); } static inline void SetNextWindowPosCenter(ImGuiCond c=0) { ImGuiIO& io = GetIO(); SetNextWindowPos(ImVec2(io.DisplaySize.x * 0.5f, io.DisplaySize.y * 0.5f), c, ImVec2(0.5f, 0.5f)); } // OBSOLETED in 1.51 (between Jun 2017 and Aug 2017) static inline bool IsItemHoveredRect() { return IsItemHovered(ImGuiHoveredFlags_RectOnly); } static inline bool IsPosHoveringAnyWindow(const ImVec2&) { IM_ASSERT(0); return false; } // This was misleading and partly broken. You probably want to use the ImGui::GetIO().WantCaptureMouse flag instead. static inline bool IsMouseHoveringAnyWindow() { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); } static inline bool IsMouseHoveringWindow() { return IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); } } typedef ImGuiInputTextCallback ImGuiTextEditCallback; // OBSOLETE in 1.63 (from Aug 2018): made the names consistent typedef ImGuiInputTextCallbackData ImGuiTextEditCallbackData; #endif //----------------------------------------------------------------------------- // Helpers //----------------------------------------------------------------------------- // Helper: Lightweight std::vector<> like class to avoid dragging dependencies (also: Windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). // *Important* Our implementation does NOT call C++ constructors/destructors. This is intentional, we do not require it but you have to be mindful of that. Do _not_ use this class as a std::vector replacement in your code! template<typename T> class ImVector { public: int Size; int Capacity; T* Data; typedef T value_type; typedef value_type* iterator; typedef const value_type* const_iterator; inline ImVector() { Size = Capacity = 0; Data = NULL; } inline ~ImVector() { if (Data) ImGui::MemFree(Data); } inline ImVector(const ImVector<T>& src) { Size = Capacity = 0; Data = NULL; operator=(src); } inline ImVector<T>& operator=(const ImVector<T>& src) { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(value_type)); return *this; } inline bool empty() const { return Size == 0; } inline int size() const { return Size; } inline int capacity() const { return Capacity; } inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } inline iterator begin() { return Data; } inline const_iterator begin() const { return Data; } inline iterator end() { return Data + Size; } inline const_iterator end() const { return Data + Size; } inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; } inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; } inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; } inline void swap(ImVector<value_type>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } inline int _grow_capacity(int sz) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > sz ? new_capacity : sz; } inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } inline void resize(int new_size,const value_type& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; } inline void reserve(int new_capacity) { if (new_capacity <= Capacity) return; value_type* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); ImGui::MemFree(Data); } Data = new_data; Capacity = new_capacity; } // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden. inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; } inline void pop_back() { IM_ASSERT(Size > 0); Size--; } inline void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); } inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } inline iterator erase(const_iterator it, const_iterator it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(value_type)); Size -= (int)count; return Data + off; } inline iterator erase_unsorted(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(value_type)); Size--; return Data + off; } inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; } inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; } inline int index_from_pointer(const_iterator it) const { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; return (int)off; } }; // Helper: IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE() macros to call MemAlloc + Placement New, Placement Delete + MemFree // We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. // Defining a custom placement new() with a dummy parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions. struct ImNewDummy {}; inline void* operator new(size_t, ImNewDummy, void* ptr) { return ptr; } inline void operator delete(void*, ImNewDummy, void*) {} // This is only required so we can use the symetrical new() #define IM_PLACEMENT_NEW(_PTR) new(ImNewDummy(), _PTR) #define IM_NEW(_TYPE) new(ImNewDummy(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE template<typename T> void IM_DELETE(T* p) { if (p) { p->~T(); ImGui::MemFree(p); } } // Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. // Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text("This will be called only once per frame"); struct ImGuiOnceUponAFrame { ImGuiOnceUponAFrame() { RefFrame = -1; } mutable int RefFrame; operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } }; // Helper: Macro for ImGuiOnceUponAFrame. Attention: The macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS // Will obsolete #define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf; if (imgui_oaf) #endif // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" struct ImGuiTextFilter { IMGUI_API ImGuiTextFilter(const char* default_filter = ""); IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const; IMGUI_API void Build(); void Clear() { InputBuf[0] = 0; Build(); } bool IsActive() const { return !Filters.empty(); } // [Internal] struct TextRange { const char* b; const char* e; TextRange() { b = e = NULL; } TextRange(const char* _b, const char* _e) { b = _b; e = _e; } const char* begin() const { return b; } const char* end () const { return e; } bool empty() const { return b == e; } IMGUI_API void split(char separator, ImVector<TextRange>* out) const; }; char InputBuf[256]; ImVector<TextRange> Filters; int CountGrep; }; // Helper: Growable text buffer for logging/accumulating text // (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') struct ImGuiTextBuffer { ImVector<char> Buf; static char EmptyString[1]; ImGuiTextBuffer() { } inline char operator[](int i) { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; } const char* begin() const { return Buf.Data ? &Buf.front() : EmptyString; } const char* end() const { return Buf.Data ? &Buf.back() : EmptyString; } // Buf is zero-terminated, so end() will point on the zero-terminator int size() const { return Buf.Data ? Buf.Size - 1 : 0; } bool empty() { return Buf.Size <= 1; } void clear() { Buf.clear(); } void reserve(int capacity) { Buf.reserve(capacity); } const char* c_str() const { return Buf.Data ? Buf.Data : EmptyString; } IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2); IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2); }; // Helper: Key->Value storage // Typically you don't have to worry about this since a storage is held within each Window. // We use it to e.g. store collapse state for a tree (Int 0/1) // This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame) // You can use it as custom user storage for temporary values. Declare your own storage if, for example: // - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). // - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient) // Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. struct ImGuiStorage { struct Pair { ImGuiID key; union { int val_i; float val_f; void* val_p; }; Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } }; ImVector<Pair> Data; // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) // - Set***() functions find pair, insertion on demand if missing. // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. void Clear() { Data.clear(); } IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; IMGUI_API void SetInt(ImGuiID key, int val); IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; IMGUI_API void SetBool(ImGuiID key, bool val); IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; IMGUI_API void SetFloat(ImGuiID key, float val); IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL IMGUI_API void SetVoidPtr(ImGuiID key, void* val); // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct) // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); // Use on your own storage if you know only integer are being stored (open/close all tree nodes) IMGUI_API void SetAllInt(int val); // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. IMGUI_API void BuildSortByKey(); }; // Helper: Manually clip large list of items. // If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. // The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. // ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. // Usage: // ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) // ImGui::Text("line number %d", i); // - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). // - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. // - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) // - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. struct ImGuiListClipper { float StartPosY; float ItemsHeight; int ItemsCount, StepNo, DisplayStart, DisplayEnd; // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing(). // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. }; // Helpers macros to generate 32-bits encoded colors #ifdef IMGUI_USE_BGRA_PACKED_COLOR #define IM_COL32_R_SHIFT 16 #define IM_COL32_G_SHIFT 8 #define IM_COL32_B_SHIFT 0 #define IM_COL32_A_SHIFT 24 #define IM_COL32_A_MASK 0xFF000000 #else #define IM_COL32_R_SHIFT 0 #define IM_COL32_G_SHIFT 8 #define IM_COL32_B_SHIFT 16 #define IM_COL32_A_SHIFT 24 #define IM_COL32_A_MASK 0xFF000000 #endif #define IM_COL32(R,G,B,A) (((ImU32)(A)<<IM_COL32_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT)) #define IM_COL32_WHITE IM_COL32(255,255,255,255) // Opaque white = 0xFFFFFFFF #define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black #define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black = 0x00000000 // Helper: ImColor() implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) // Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API. // **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE. // **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed. struct ImColor { ImVec4 Value; ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } ImColor(const ImVec4& col) { Value = col; } inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } inline operator ImVec4() const { return Value; } // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers. inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } }; //----------------------------------------------------------------------------- // Draw List API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListFlags, ImDrawList, ImDrawData) // Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. //----------------------------------------------------------------------------- // Draw callbacks for advanced uses. // NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, // you can poke into the draw list for that! Draw callback may be useful for example to: A) Change your GPU render state, // B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. // The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); // Typically, 1 command = 1 GPU draw call (unless command is a callback) struct ImDrawCmd { unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. void* UserCallbackData; // The draw callback code can access this. ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = (ImTextureID)NULL; UserCallback = NULL; UserCallbackData = NULL; } }; // Vertex index (override with '#define ImDrawIdx unsigned int' in imconfig.h) #ifndef ImDrawIdx typedef unsigned short ImDrawIdx; #endif // Vertex layout #ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; ImVec2 uv; ImU32 col; }; #else // You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h // The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. // The type has to be described within the macro (you can either declare the struct or use a typedef) // NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM. IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; #endif // Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. // You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. struct ImDrawChannel { ImVector<ImDrawCmd> CmdBuffer; ImVector<ImDrawIdx> IdxBuffer; }; enum ImDrawCornerFlags_ { ImDrawCornerFlags_TopLeft = 1 << 0, // 0x1 ImDrawCornerFlags_TopRight = 1 << 1, // 0x2 ImDrawCornerFlags_BotLeft = 1 << 2, // 0x4 ImDrawCornerFlags_BotRight = 1 << 3, // 0x8 ImDrawCornerFlags_Top = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight, // 0x3 ImDrawCornerFlags_Bot = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight, // 0xC ImDrawCornerFlags_Left = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft, // 0x5 ImDrawCornerFlags_Right = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight, // 0xA ImDrawCornerFlags_All = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a convenience }; enum ImDrawListFlags_ { ImDrawListFlags_None = 0, ImDrawListFlags_AntiAliasedLines = 1 << 0, // Lines are anti-aliased (*2 the number of triangles for 1.0f wide line, otherwise *3 the number of triangles) ImDrawListFlags_AntiAliasedFill = 1 << 1 // Filled shapes have anti-aliased edges (*2 the number of vertices) }; // Draw command list // This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. // Each ImGui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to access the current window draw list and draw custom primitives. // You can interleave normal ImGui:: calls and adding primitives to the current draw list. // All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), but you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well) // Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects. struct ImDrawList { // This is what you have to render ImVector<ImDrawCmd> CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those ImVector<ImDrawVert> VtxBuffer; // Vertex buffer. ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive. // [Internal, used while building lists] const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context) const char* _OwnerName; // Pointer to owner window's name for debugging unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) ImVector<ImVec4> _ClipRectStack; // [Internal] ImVector<ImTextureID> _TextureIdStack; // [Internal] ImVector<ImVec2> _Path; // [Internal] current path building int _ChannelsCurrent; // [Internal] current channel number (0) int _ChannelsCount; // [Internal] number of active channels (1+) ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui) ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); } ~ImDrawList() { ClearFreeMemory(); } IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Update-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) IMGUI_API void PushClipRectFullScreen(); IMGUI_API void PopClipRect(); IMGUI_API void PushTextureID(ImTextureID texture_id); IMGUI_API void PopTextureID(); inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); } inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); } // Primitives IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF); IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All); IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness); IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order. IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); // Stateful path API, add points then finish with PathFillConvex() or PathStroke() inline void PathClear() { _Path.resize(0); } inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); PathClear(); } // Note: Anti-aliased filling requires points to be in clockwise order. inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); PathClear(); } IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // Channels // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) IMGUI_API void ChannelsSplit(int channels_count); IMGUI_API void ChannelsMerge(); IMGUI_API void ChannelsSetCurrent(int channel_index); // Advanced IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible IMGUI_API ImDrawList* CloneOutput() const; // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer. // Internal helpers // NB: all primitives needs to be reserved via PrimReserve() beforehand! IMGUI_API void Clear(); IMGUI_API void ClearFreeMemory(); IMGUI_API void PrimReserve(int idx_count, int vtx_count); IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } IMGUI_API void UpdateClipRect(); IMGUI_API void UpdateTextureID(); }; // All draw data to render an ImGui frame // (NB: the style and the naming convention here is a little inconsistent but we preserve them for backward compatibility purpose) struct ImDrawData { bool Valid; // Only valid after Update() is called and before the next NewFrame() is called. ImDrawList** CmdLists; // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here. int CmdListsCount; // Number of ImDrawList* to render int TotalIdxCount; // For convenience, sum of all ImDrawList's IdxBuffer.Size int TotalVtxCount; // For convenience, sum of all ImDrawList's VtxBuffer.Size ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use) ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use) // Functions ImDrawData() { Valid = false; Clear(); } ~ImDrawData() { Clear(); } void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; DisplayPos = DisplaySize = ImVec2(0.f, 0.f); } // The ImDrawList are owned by ImGuiContext! IMGUI_API void DeIndexAllBuffers(); // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. }; //----------------------------------------------------------------------------- // Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFont) //----------------------------------------------------------------------------- struct ImFontConfig { void* FontData; // // TTF/OTF data int FontDataSize; // // TTF/OTF data size bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). int FontNo; // 0 // Index of font within TTF/OTF file float SizePixels; // // Size in pixels for rasterizer (more or less maps to the resulting font height). int OversampleH; // 3 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. int OversampleV; // 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now. ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input. const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one. float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable. // [Internal] char Name[40]; // Name (strictly to ease debugging) ImFont* DstFont; IMGUI_API ImFontConfig(); }; struct ImFontGlyph { ImWchar Codepoint; // 0x0000..0xFFFF float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in) float X0, Y0, X1, Y1; // Glyph corners float U0, V0, U1, V1; // Texture coordinates }; enum ImFontAtlasFlags_ { ImFontAtlasFlags_None = 0, ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two ImFontAtlasFlags_NoMouseCursors = 1 << 1 // Don't build software mouse cursors into the atlas }; // Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: // - One or more fonts. // - Custom graphics data needed to render the shapes needed by Dear ImGui. // - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas). // It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api. // - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you. // - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. // - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples) // - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API. // This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details. // Common pitfalls: // - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the // atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data. // - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction. // You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed, // - Even though many functions are suffixed with "TTF", OTF data is supported just as well. // - This is an old API and it is currently awkward for those and and various other reasons! We will address them in the future! struct ImFontAtlas { IMGUI_API ImFontAtlas(); IMGUI_API ~ImFontAtlas(); IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed. IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp. IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter. IMGUI_API void ClearInputData(); // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts. IMGUI_API void ClearTexData(); // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. IMGUI_API void ClearFonts(); // Clear output font data (glyphs storage, UV coordinates). IMGUI_API void Clear(); // Clear all input and output. // Build atlas, retrieve pixel data. // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID(). // The pitch is always = Width * BytesPerPixels (1 or 4) // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste. IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions. IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel bool IsBuilt() { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); } void SetTexID(ImTextureID id) { TexID = id; } //------------------------------------------- // Glyph Ranges //------------------------------------------- // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details. // NB: Consider using GlyphRangesBuilder to build glyph ranges from textual data. IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters // Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges(). struct GlyphRangesBuilder { ImVector<unsigned char> UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used) GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); } bool GetBit(int n) const { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; } void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array void AddChar(ImWchar c) { SetBit(c); } // Add character IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added) IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges }; //------------------------------------------- // Custom Rectangles/Glyphs API //------------------------------------------- // You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels. // You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs. struct CustomRect { unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data. unsigned short Width, Height; // Input // Desired rectangle dimension unsigned short X, Y; // Output // Packed position in Atlas float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; } bool IsPacked() const { return X != 0xFFFF; } }; IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font. const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; } // [Internal] IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max); IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]); //------------------------------------------- // Members //------------------------------------------- bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_) ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure. int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1. // [Internal] // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you. unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 int TexWidth; // Texture width calculated during Build(). int TexHeight; // Texture height calculated during Build(). ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight) ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. ImVector<CustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas. ImVector<ImFontConfig> ConfigData; // Internal data int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList }; // Font runtime data and rendering // ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). struct ImFont { // Members: Hot ~62/78 bytes float FontSize; // <user set> // Height of characters, set during loading (don't change after loading) float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() ImVec2 DisplayOffset; // = (0.f,0.f) // Offset font rendering by xx pixels ImVector<ImFontGlyph> Glyphs; // // All glyphs. ImVector<float> IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). ImVector<ImWchar> IndexLookup; // // Sparse. Index glyphs by Unicode code-point. const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) float FallbackAdvanceX; // == FallbackGlyph->AdvanceX ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() // Members: Cold ~18/26 bytes short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData ImFontAtlas* ContainerAtlas; // // What we has been loaded into float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] bool DirtyLookupTables; int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs) // Methods IMGUI_API ImFont(); IMGUI_API ~ImFont(); IMGUI_API void ClearOutputData(); IMGUI_API void BuildLookupTable(); IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const; IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const; IMGUI_API void SetFallbackChar(ImWchar c); float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; } bool IsLoaded() const { return ContainerAtlas != NULL; } const char* GetDebugName() const { return ConfigData ? ConfigData->Name : "<unknown>"; } // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const; IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; // [Internal] IMGUI_API void GrowIndex(int new_size); IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x); IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS typedef ImFontGlyph Glyph; // OBSOLETE 1.52+ #endif }; #if defined(__clang__) #pragma clang diagnostic pop #elif defined(__GNUC__) && __GNUC__ >= 8 #pragma GCC diagnostic pop #endif // Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h) #ifdef IMGUI_INCLUDE_IMGUI_USER_H #include "imgui_user.h" #endif
[ "erdinckaya@yandex.com" ]
erdinckaya@yandex.com
e811c19394f4861bbd3ab100ac1d671a66d6a467
f67629586414cfe28929c10f30e09ce82ea342bc
/Benchmark Engineering Tool/example/BenchmarkLibUnbuilt/src-gen/stateMachine/AbstractMachineElement.hpp
a875c394458854b66dd69ecb31cbdea2936ad642
[]
no_license
Mohamedgalil/plug-and-bench
cb259258fbb9a09a7ed084d395ca5a49d17c8a6b
44d02a6eb0eb7de289364e2dffe5dc0d63cc9516
refs/heads/master
2020-04-25T15:31:23.868541
2019-04-16T07:20:24
2019-04-16T07:20:24
172,881,559
1
0
null
null
null
null
UTF-8
C++
false
false
2,566
hpp
// -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*- /* * stateMachine/AbstractMachineElement.hpp * This file was created by EMF4CPP 2.0.0 and is copyrighted by the * respective user and/or provider of the processed ECORE model. * * EMF4CPP is free software. You can obtain it from * https://github.com/catedrasaes-umu/emf4cpp */ #ifndef STATEMACHINE_ABSTRACTMACHINEELEMENT_HPP #define STATEMACHINE_ABSTRACTMACHINEELEMENT_HPP #include <ecorecpp/mapping_forward.hpp> #include <ecore/EObject.hpp> #include <stateMachine/dllStateMachine.hpp> #include <stateMachine_forward.hpp> #include "StateMachinePackage.hpp" /*PROTECTED REGION ID(AbstractMachineElement_pre) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ namespace stateMachine { class EXPORT_STATEMACHINE_DLL AbstractMachineElement : public virtual ::ecore::EObject { public: AbstractMachineElement(); virtual ~AbstractMachineElement(); virtual void _initialize(); // Operations // Attributes // References /* This is the same value as getClassifierId() returns, but as a static * value it can be used in template expansions. */ static const int classifierId = StateMachinePackage::ABSTRACTMACHINEELEMENT; /*PROTECTED REGION ID(AbstractMachineElement) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ // EObjectImpl virtual ::ecore::EJavaObject eGet ( ::ecore::EInt _featureID, ::ecore::EBoolean _resolve); virtual void eSet ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue); virtual ::ecore::EBoolean eIsSet ( ::ecore::EInt _featureID); virtual void eUnset ( ::ecore::EInt _featureID); virtual ::ecore::EClass_ptr _eClass (); virtual void _inverseAdd ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _newValue); virtual void _inverseRemove ( ::ecore::EInt _featureID, ::ecore::EJavaObject const& _oldValue); /*PROTECTED REGION ID(AbstractMachineElementImpl) START*/ // Please, enable the protected region if you add manually written code. // To do this, add the keyword ENABLED before START. /*PROTECTED REGION END*/ protected: AbstractMachineElement_ptr _this() { return AbstractMachineElement_ptr(this);} // Attributes // References }; } // stateMachine #endif // STATEMACHINE_ABSTRACTMACHINEELEMENT_HPP
[ "mohamed.el-shamouty@ipa.fraunhofer.de" ]
mohamed.el-shamouty@ipa.fraunhofer.de
888de065a43c643dab1eed5f4c0d89650b614d2d
f43543ac545c96daf74ee763e7fb1497f7ddf309
/Chapter5/ass4.cpp
3acadb4e27c8e4dbe54cda8e92040d4280370a46
[]
no_license
Cyrus07/Cpp_pp
bb272e5fbdb100ade2aba4c268c0abd6072e4601
89450593a63bdc70ec9bf648e3a250e9e0e0f71c
refs/heads/master
2021-01-10T17:38:26.006926
2016-01-07T14:36:24
2016-01-07T14:36:24
48,879,960
0
0
null
null
null
null
UTF-8
C++
false
false
294
cpp
#include<iostream> int main() { using std::cout; using std::endl; double Daphne=100.0, Cleo=100.0; int i=0; while (Cleo <= Daphne) { i++; Cleo*=1.05; Daphne+=10; } cout << "Daphne: " << Daphne << endl << "Cleo: " << Cleo << endl << "It's year " << i << endl; return 0; }
[ "teamworkhlc@gmail.com" ]
teamworkhlc@gmail.com
ee7e7a92a1f1a1fa9ac67a95c2ec7fa53c1b346f
e426bfa4943daf4206030415cba2012ffc45c532
/include/common/snippets/asc2bin.h
3030d16a2c633fcb6fbbcaa15d292dee3aa2f548
[]
no_license
shawwn/codesuppository
952c43b48fb12fc70c6c7057119cc4af30e03385
da9905802797c8e42bb0016d2929d3d768aea332
refs/heads/master
2020-03-21T07:14:32.497634
2019-06-11T06:56:49
2019-06-11T06:56:49
138,269,183
1
0
null
null
null
null
UTF-8
C++
false
false
2,883
h
#ifndef ASC2BIN_H #define ASC2BIN_H #include "UserMemAlloc.h" /*! ** ** Copyright (c) 2007 by John W. Ratcliff mailto:jratcliff@infiniplex.net ** ** Portions of this source has been released with the PhysXViewer application, as well as ** Rocket, CreateDynamics, ODF, and as a number of sample code snippets. ** ** If you find this code useful or you are feeling particularily generous I would ** ask that you please go to http://www.amillionpixels.us and make a donation ** to Troy DeMolay. ** ** DeMolay is a youth group for young men between the ages of 12 and 21. ** It teaches strong moral principles, as well as leadership skills and ** public speaking. The donations page uses the 'pay for pixels' paradigm ** where, in this case, a pixel is only a single penny. Donations can be ** made for as small as $4 or as high as a $100 block. Each person who donates ** will get a link to their own site as well as acknowledgement on the ** donations blog located here http://www.amillionpixels.blogspot.com/ ** ** If you wish to contact me you can use the following methods: ** ** Skype Phone: 636-486-4040 (let it ring a long time while it goes through switches) ** Skype ID: jratcliff63367 ** Yahoo: jratcliff63367 ** AOL: jratcliff1961 ** email: jratcliff@infiniplex.net ** ** ** The MIT license: ** ** Permission is hereby granted, MEMALLOC_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. */ // types: // // f : 4 byte NxF32 // d : 4 byte integer // c : 1 byte character // b : 1 byte integer // h : 2 byte integer // p : 4 byte const char * // x1 : 1 byte hex // x2 : 2 byte hex // x4 : 4 byte hex (etc) // example usage: // // Asc2Bin("1 2 3 4 5 6",1,"fffff",0); namespace NVSHARE { void * Asc2Bin(const char *source,const NxI32 count,const char *ctype,void *dest=0); }; // #endif
[ "shawnpresser@gmail.com" ]
shawnpresser@gmail.com
1f8199c241d96eab456cc804103218b6e89b1e4c
a19c02e59d9d5990a92ee64d97d3deab2d8b7f0f
/src/Robot.cpp
b06d36d0cee76b87fe81cb141955d9f1b43304fd
[]
no_license
CloverBots/steamworks-2017
556b08dd546c54738656c15b09208e671692491c
174d807b4bd33e8c846d5833a594176112895e5d
refs/heads/master
2021-01-14T08:03:09.567910
2017-08-05T23:32:04
2017-08-05T23:32:04
81,898,666
0
0
null
null
null
null
UTF-8
C++
false
false
4,222
cpp
#include <memory> #include <Commands/Command.h> #include <Commands/PlaceGearCenter.h> #include <Commands/PlaceGearLeft.h> #include <Commands/PlaceGearRight.h> #include <Commands/ShootSequence.h> #include <Commands/Scheduler.h> #include <IterativeRobot.h> #include <LiveWindow/LiveWindow.h> #include <SmartDashboard/SendableChooser.h> #include <SmartDashboard/SmartDashboard.h> #include "CommandBase.h" #include "Commands/DriveForward.h" class Robot : public frc::IterativeRobot { public: void RobotInit() override { CommandBase::Init(); chooser.AddDefault("Do Nothing", 0); chooser.AddObject("Shoot Immediately", new ShootSequence()); chooser.AddObject("Drive Forward", new DriveForward()); chooser.AddObject("Place Gear (Center)", new PlaceGearCenter()); chooser.AddObject("Place Gear (Left)", new PlaceGearLeft(false)); chooser.AddObject("Place Gear (Left, Boiler)", new PlaceGearLeft(true)); chooser.AddObject("Place Gear (Right)", new PlaceGearRight(false)); chooser.AddObject("Place Gear (Right, Boiler)", new PlaceGearRight(true)); frc::SmartDashboard::PutData("Auto Modes", &chooser); // frc::SmartDashboard::PutNumber("Shooter Speed", 0.0); // frc::SmartDashboard::PutNumber("Shooter P", 0.0); // frc::SmartDashboard::PutNumber("Shooter I", 0.0); // frc::SmartDashboard::PutNumber("Shooter D", 0.0); } /** * This function is called once each time the robot enters Disabled mode. * You can use it to reset any subsystem information you want to clear when * the robot is disabled. */ void DisabledInit() override { CommandBase::shooterSubsystem->SetPIDEnabled(false); //SmartDashboard::PutString("Enabled:", "False"); } void DisabledPeriodic() override { frc::Scheduler::GetInstance()->Run(); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable * chooser code works with the Java SmartDashboard. If you prefer the * LabVIEW Dashboard, remove all of the chooser code and uncomment the * GetString code to get the auto name from the text box below the Gyro. * * You can add additional auto modes by adding additional commands to the * chooser code above (like the commented example) or additional comparisons * to the if-else structure below with additional strings & commands. */ void AutonomousInit() override { //CommandBase::shooterSubsystem->SetPIDEnabled(true); CommandBase::pDriveSystem->ResetGyro(); /* std::string autoSelected = frc::SmartDashboard::GetString("Auto Selector", "Default"); if (autoSelected == "My Auto") { autonomousCommand.reset(new MyAutoCommand()); } else { autonomousCommand.reset(new ExampleCommand()); } */ autonomousCommand.reset(chooser.GetSelected()); if (autonomousCommand.get() != nullptr) { autonomousCommand->Start(); } } void AutonomousPeriodic() override { frc::Scheduler::GetInstance()->Run(); } void TeleopInit() override { CommandBase::shooterSubsystem->SetPIDEnabled(false); CommandBase::pDriveSystem->ResetGyro(); //SmartDashboard::PutString("Enabled:", "True"); // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand != nullptr) { autonomousCommand->Cancel(); } } void TeleopPeriodic() override { // if (CommandBase::oi->GetOperatorStick()->GetRawButton(7) || CommandBase::oi->GetDriveStick()->GetRawButton(7)) // { // frc::Scheduler::GetInstance()->SetEnabled(false); // frc::Scheduler::GetInstance()-> // SmartDashboard::PutString("Enabled:", "False"); // } // else if (CommandBase::oi->GetOperatorStick()->GetRawButton(8) || CommandBase::oi->GetDriveStick()->GetRawButton(8)) // { // frc::Scheduler::GetInstance()->SetEnabled(true); // SmartDashboard::PutString("Enabled:", "True"); // } frc::Scheduler::GetInstance()->Run(); } void TestPeriodic() override { frc::LiveWindow::GetInstance()->Run(); } private: std::unique_ptr<frc::Command> autonomousCommand; frc::SendableChooser<frc::Command*> chooser; }; START_ROBOT_CLASS(Robot)
[ "mackinnonman@icloud.com" ]
mackinnonman@icloud.com
3b139f3fc58ad68d3b2d13e90abf569b968816a5
30b7ffd17845db982883a91ce8d04551281658c4
/Codeforces/Round/Round 496/New folder/New folder/asdasd/A.cpp
da0dc00a172c173d83cff0b5dfb693b6f230ce98
[]
no_license
shas9/codehub
95418765b602b52edb0d48a473ad7e7a798f76e5
bda856bf6ca0f3a1d59980895cfab82f690c75a2
refs/heads/master
2023-06-21T01:09:34.275708
2021-07-26T14:54:03
2021-07-26T14:54:03
389,404,954
0
0
null
null
null
null
UTF-8
C++
false
false
1,506
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long #define pb push_back vector<ll>graph[123459]; ll ara[123459], chk[200009]; ll node1, dist1 = 0, node2, dist2 = 0; void dfs(ll u, ll p, ll lv) { if(lv > dist1 && chk[u]) { dist1 = lv; node1 = u; } for(ll i = 0; i < graph[u].size(); i++) { ll nd = graph[u][i]; if(nd == p) continue; dfs(nd, u, lv + 1); } } void dfs2(ll u, ll p, ll lv) { if(lv > dist2 && chk[u]) { dist2 = lv; node2 = u; } else if(lv == dist2 && chk[u]) { node2 = min(node2, u); } for(ll i = 0; i < graph[u].size(); i++) { ll nd = graph[u][i]; if(nd == p) continue; dfs2(nd, u, lv + 1); } } ll dist = 0; ll dfs3(ll node, ll par, ll lv) { for(ll i = 0; i < graph[u].size(); i++) { ll nd = graph[u][i]; if(nd == p) continue; ll tmp = dfs3(nd, u, lv + 1); if(tmp > 0) dist += tmp; } } int main() { ll n,m; scanf("%lld %lld",&n,&m); for(ll i=1;i<n;i++) { ll u, v; scanf("%lld %lld",&u,&v); graph[u].pb(v); graph[v].pb(u); } for(ll i=1;i<=m;i++){ scanf("%lld",&ara[i]); chk[ara[i]]=1; } dfs(1, -1, 1); dfs2(node1, -1, 1); cout << node2 << endl; ans = dfs3(node, -1); return 0; }
[ "shahwathasnaine@gmail.com" ]
shahwathasnaine@gmail.com
fb2180a2d18769f3b385f371856efbb2ede9d67b
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/f2/72edad4d84f47a/main.cpp
4470ae6eff6c0f6fa0922d36cced79597c37b590
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
1,590
cpp
#include <iostream> #include <string> #include <sstream> struct name_value_pair { std::string name; int value; }; // convert object of type name_value_pair into a sequence of characters std::string to_string( name_value_pair nvpair ) { // step 1. create an output stringstream std::ostringstream stm; // step 2. write name and value into the stream stm << "{ name: '" << nvpair.name << "', value: " << nvpair.value << " }"; // step 3. get a copy of the underlying string; and return it. return stm.str(); } // convert string back to object of type name_value_pair name_value_pair to_nvpair( std::string str ) { // step 1. crate a name_value_pair object name_value_pair nvpair = { "anonymous", 0 }; // step 2. create an input stringstream to read from the given string std::istringstream stm(str); // step 2. read the information in the string std::string temp ; std::getline( stm, temp, '\'' ); // 2a. discard everuthing upto the first ' std::getline( stm, nvpair.name, '\'' ); // 2b. read the name std::getline( stm, temp, ':' ); // 2c. discard everuthing upto the next : stm >> nvpair.value; // 2d. read the value // step 3. return the object. return nvpair ; } int main() { name_value_pair pcount = { "post count", 59 }; const std::string str = to_string(pcount); std::cout << "str contains: " << str << '\n'; name_value_pair pcount2 = to_nvpair(str) ; std::cout << pcount2.name << " => " << pcount2.value << '\n' ; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
5098989ecd4b0ca852ea8bd0aa5940afb369e5d9
5f3fe02df7fd5f65ca8966eede31ea01ea7e7316
/homework2/code.ino/code.ino.ino
a39fdd8692fdb860b13b79b1890b7dddd6409c49
[]
no_license
CloakedGhost07/Martin_CSE_236
d6bb2d0b9003399adecee2612c1d1bf0d0837857
a2b3626388c401be3d6a7f70875cded380b69969
refs/heads/master
2020-12-13T08:15:28.879351
2020-05-01T15:11:45
2020-05-01T15:11:45
234,358,659
0
0
null
null
null
null
UTF-8
C++
false
false
3,297
ino
/*-------------------------------------------------------------------- Name: Michael Martin Date: 1/30/2020 Course: CSCE 236 Embedded Systems (Spring 2020) File: HW/Lab: Lab 1, programming component Purp: Source code for Arduino board, Doc: Academic Integrity Statement: I certify that, while others may have assisted me in brain storming, debugging and validating this program, the program itself is my own work. I understand that submitting code which is the work of other individuals is a violation of the honor code. I also understand that if I knowingly give my original work to another individual is also a violation of the honor code. --------------------------------------------------------------------*/ #include<stdint.h> #include<Arduino.h> #define LED_PIN 13 int in_byte =0; int flashcount = 0; int speed = 0; int i; uint32_t bit32count; uint16_t bit16count = 0xffff; uint16_t bit16countB = 0xffff; uint8_t bit8countA; uint8_t bit8countB; uint8_t bit8countC; void setup() { Serial.begin(9600); while(!Serial){}; //pinMode(LED_PIN,OUTPUT); /* Serial.println("cycle start"); for(bit16count = 0; bit16count < 0x3fffff; bit16count++){ asm volatile("nop"); } Serial.println("cycle done"); */ pinMode(LED_PIN,OUTPUT); blinkSequenceUsingBits(); } void blinkSequenceUsingBits(){ Serial.println("cycle start for 3 sec"); digitalWrite(LED_PIN,HIGH); for(bit32count = 0; bit32count < 0x13ffff ; bit32count++){ asm volatile("nop"); } digitalWrite(LED_PIN,LOW); Serial.println("32 bit cycle done"); delay(500); digitalWrite(LED_PIN,HIGH); delay(500); digitalWrite(LED_PIN,LOW); delay(500); Serial.println("cycle start for 6 sec"); digitalWrite(LED_PIN,HIGH); for(bit16countB = 0; bit16countB < 0x48; bit16countB++){ for(bit16count = 0; bit16count < 0xffff; bit16count ++){ asm volatile("nop"); }} digitalWrite(LED_PIN,LOW); Serial.println("16 bit cycle done"); delay(500); digitalWrite(LED_PIN,HIGH); delay(500); digitalWrite(LED_PIN,LOW); delay(500); digitalWrite(LED_PIN,HIGH); delay(500); digitalWrite(LED_PIN,LOW); delay(500); digitalWrite(LED_PIN,HIGH); Serial.println("cycle start for 2 sec"); for(bit8countA = 0; bit8countA < 41; bit8countA++){ for(bit8countB = 0; bit8countB < 0xff; bit8countB++){ for(bit8countC = 0; bit8countC < 0xff; bit8countC++){ asm volatile("nop"); } } } digitalWrite(LED_PIN,LOW); Serial.println("8 bit cycle done"); } void flashSerial(){ if(Serial.available()>0){ in_byte = Serial.read(); if(in_byte != 10){ Serial.print("This is what I read: "); Serial.println(in_byte); if(in_byte >= 48 && in_byte <= 57){ flashcount = in_byte - 48; Serial.println(flashcount); } else if(in_byte == 102){ speed = 1; Serial.println("Speed set to fast."); } else if(in_byte == 115){ speed = 0; Serial.println("Speed set to slow"); } } for(i = 0; i < flashcount; i++){ digitalWrite(LED_PIN,HIGH); if(speed == 0){delay(750);} delay(250); digitalWrite(LED_PIN,LOW); if(speed == 0){delay(750);} delay(250); } flashcount = 0; } } void loop() { flashSerial(); }
[ "46792241+CloakedGhost07@users.noreply.github.com" ]
46792241+CloakedGhost07@users.noreply.github.com
2d318f4e6113cf57a7545631601a94e3a85d9179
62a9e86743572b2c1c485809d181419e5229ae22
/leetcode/apple/461-Hamming-Distance.cpp
f44d8b5da918b1d53ef637554499fd37a9253bf3
[]
no_license
BinWangGBLW/leetcode
7fbe7d02fb9a7667f708cd8d9d4fa75f0fa48a7a
cd8c0b25866d7a25dc12c137ac92ae35627c99b3
refs/heads/master
2021-04-06T05:58:43.554030
2018-03-20T21:38:34
2018-03-20T21:38:34
125,078,742
0
0
null
null
null
null
UTF-8
C++
false
false
783
cpp
#include <iostream> #include <vector> /* The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. */ using namespace std; class Solution { public: int hammingDistance(int x, int y) { int res = 0; for (int i = 0; i < 32; ++i) { if ((x & (1 << i)) ^ (y & (1 << i))) { ++res; } } return res; } }; int main () { Solution s; cout << s.hammingDistance(1, 4) << endl; }
[ "b.wang@qub.ac.uk" ]
b.wang@qub.ac.uk
0caf860b2208eba1eceed5d16e0bbf1b1db68f81
81dc36fe44f0d9df4f17f70959925816b5fe385e
/license-client/include/tcpclient.h
b955fab05874ff3cec435cf95ad13a8ea91fc5e6
[ "MIT" ]
permissive
stallion5632/license-services
6dd5beb076de762ccbcc8bef0bcddc12d1156b9f
e46be0a89fdee4037aa8804411b6ec135ce25887
refs/heads/master
2020-03-29T12:13:17.721950
2018-09-23T02:00:23
2018-09-23T02:00:23
149,889,481
2
1
null
null
null
null
UTF-8
C++
false
false
676
h
 #ifndef TCP_CLIENT_H #define TCP_CLIENT_H #include <boost/asio.hpp> #include "tcp_message.hpp" #include "messagebus.hpp" #include "common.h" #include "rockapi.h" struct ClientConfig; class TcpClientImpl; class ROCK_NET_API TcpClient { public: TcpClient(boost::asio::io_context& io_context, const ClientConfig &cfg, const MessageType_t &messageTypes); ~TcpClient(); // 发送tcp消息 // note: _syncBytes _msgSeq _bodyLen _fullMsgLen这三个字段会自动补全,可以不用填写 void write(TcpMessage &msg); // 关闭tcpsession void close(); MessageBus<> &messagebus(); void start(); private: TcpClientImpl* _pImpl; }; #endif
[ "stallion5632@163.com" ]
stallion5632@163.com
eb79d0f6badde2f8c9cbb97596d00736cd362920
e2188ff27e1002b665bfe0d9060a1bae1c2e2d37
/c++/12_EquityMC/Pricer.h
813448d80740d08b64180e9a52e820e3732e0ade
[]
no_license
Claudio911015/UMA
b8fb28de32cf87d707c1eaf4f9886bb8a345148a
032b901ea3a558aa703ab00b89a24f96da75ff37
refs/heads/master
2021-08-18T05:49:31.676008
2019-05-04T19:06:49
2019-05-04T19:06:49
184,843,589
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
#ifndef PRICER_H #define PRICER_H #include <random> #include "MarketData.h" #include "Payoff.h" class Results{ public: double m_price; double m_standardDeviation; //the standard error of m_price double m_delta; double m_gamma; }; class Pricer{ public: Pricer(int nPaths):m_numIndependentPaths(nPaths){} Results go(const MarketData& m, const Payoff& p); private: int m_numIndependentPaths; std::mt19937 m_rnd; }; //perhaps add antithetic MC, more greeks, LR greeks, path dependent payoff. #endif
[ "claudiocp_2@hotmail.com" ]
claudiocp_2@hotmail.com
36db34649a60e9c0ca55183ddfab404c9c31988c
89be38f4428c37df62fae8a3f1a0d44f4b68f93d
/src/main.h
936f0c7eea91728da04bd7920b8e53515232b4e2
[ "MIT" ]
permissive
blackwhitecoin/Blackwhitecoin
1a2e9fde6a86e30d0ae9a3a73967b049abd7a1a1
78f2774a3f5ee2d2e381f2707ea6d63ce76932bb
refs/heads/master
2016-09-05T09:02:03.761406
2014-04-23T13:52:25
2014-04-23T13:52:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
45,167
h
// Copyright (c) 2009-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. #ifndef BITCOIN_MAIN_H #define BITCOIN_MAIN_H #include "bignum.h" #include "sync.h" #include "net.h" #include "script.h" #include "scrypt_mine.h" #include <list> class CWallet; class CBlock; class CBlockIndex; class CKeyItem; class CReserveKey; class COutPoint; class CAddress; class CInv; class CRequestTracker; class CNode; static const unsigned int MAX_BLOCK_SIZE = 1000000; static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2; static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100; static const unsigned int MAX_INV_SZ = 30000; static const int64 MIN_TX_FEE = .01 * CENT; static const int64 MIN_RELAY_TX_FEE = .01 * CENT; static const int64 MAX_MONEY = 500000000 * COIN; static const int64 MAX_MONEY2 = 300000000 * COIN; // 70 bil static const int64 CIRCULATION_MONEY = MAX_MONEY2; static const double TAX_PERCENTAGE = 0.0078; static const int64 MAX_MINT_PROOF_OF_STAKE = 0.02 * COIN; // 5% annual interest static const int64 MIN_TXOUT_AMOUNT = MIN_TX_FEE; inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } // Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC #ifdef USE_UPNP static const int fHaveUPnP = true; #else static const int fHaveUPnP = false; #endif static const uint256 hashGenesisBlockOfficial("0x00000549c9a6f5ad16ad5b614827a5a82bf9f1f8cad6fb2dec45080993470468"); static const uint256 hashGenesisBlockTestNet ("0x"); static const int64 nMaxClockDrift = 2 * 60 * 60; // two hours extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern std::map<uint256, CBlockIndex*> mapBlockIndex; extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen; extern uint256 hashGenesisBlock; extern CBlockIndex* pindexGenesisBlock; extern unsigned int nStakeMinAge; extern int nCoinbaseMaturity; extern int nBestHeight; extern CBigNum bnBestChainTrust; extern CBigNum bnBestInvalidTrust; extern uint256 hashBestChain; extern CBlockIndex* pindexBest; extern unsigned int nTransactionsUpdated; extern uint64 nLastBlockTx; extern uint64 nLastBlockSize; extern int64 nLastCoinStakeSearchInterval; extern const std::string strMessageMagic; extern double dHashesPerSec; extern int64 nHPSTimerStart; extern int64 nTimeBestReceived; extern CCriticalSection cs_setpwalletRegistered; extern std::set<CWallet*> setpwalletRegistered; extern unsigned char pchMessageStart[4]; extern std::map<uint256, CBlock*> mapOrphanBlocks; // Settings extern int64 nTransactionFee; // Minimum disk space required - used in CheckDiskSpace() static const uint64 nMinDiskSpace = 52428800; class CReserveKey; class CTxDB; class CTxIndex; void RegisterWallet(CWallet* pwalletIn); void UnregisterWallet(CWallet* pwalletIn); void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true); bool ProcessBlock(CNode* pfrom, CBlock* pblock); bool CheckDiskSpace(uint64 nAdditionalBytes=0); FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb"); FILE* AppendBlockFile(unsigned int& nFileRet); bool LoadBlockIndex(bool fAllowNew=true); void PrintBlockTree(); CBlockIndex* FindBlockByHeight(int nHeight); bool ProcessMessages(CNode* pfrom); bool SendMessages(CNode* pto, bool fSendTrickle); bool LoadExternalBlockFile(FILE* fileIn); void GenerateBitcoins(bool fGenerate, CWallet* pwallet); CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false); void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce); void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1); bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey); bool CheckProofOfWork(uint256 hash, unsigned int nBits); int64 GetProofOfWorkReward(int nHeight, int64 nFees, uint256 prevHash); int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, int nHeight); unsigned int ComputeMinWork(unsigned int nBase, int64 nTime); unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime); int GetNumBlocksOfPeers(); bool IsInitialBlockDownload(); std::string GetWarnings(std::string strFor); bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock); uint256 WantedByOrphan(const CBlock* pblockOrphan); const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake); void BitcoinMiner(CWallet *pwallet, bool fProofOfStake); void ResendWalletTransactions(); bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut); /** Position on disk for a particular transaction. */ class CDiskTxPos { public: unsigned int nFile; unsigned int nBlockPos; unsigned int nTxPos; CDiskTxPos() { SetNull(); } CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn) { nFile = nFileIn; nBlockPos = nBlockPosIn; nTxPos = nTxPosIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; } bool IsNull() const { return (nFile == (unsigned int) -1); } friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b) { return (a.nFile == b.nFile && a.nBlockPos == b.nBlockPos && a.nTxPos == b.nTxPos); } friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b) { return !(a == b); } std::string ToString() const { if (IsNull()) return "null"; else return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos); } void print() const { printf("%s", ToString().c_str()); } }; /** An inpoint - a combination of a transaction and an index n into its vin */ class CInPoint { public: CTransaction* ptx; unsigned int n; CInPoint() { SetNull(); } CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; } void SetNull() { ptx = NULL; n = (unsigned int) -1; } bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); } }; /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { public: uint256 hash; unsigned int n; COutPoint() { SetNull(); } COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { hash = 0; n = (unsigned int) -1; } bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); } friend bool operator<(const COutPoint& a, const COutPoint& b) { return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); } friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); } friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); } std::string ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n); } void print() const { printf("%s\n", ToString().c_str()); } }; /** An input of a transaction. It contains the location of the previous * transaction's output that it claims and a signature that matches the * output's public key. */ class CTxIn { public: COutPoint prevout; CScript scriptSig; unsigned int nSequence; CTxIn() { nSequence = std::numeric_limits<unsigned int>::max(); } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } IMPLEMENT_SERIALIZE ( READWRITE(prevout); READWRITE(scriptSig); READWRITE(nSequence); ) bool IsFinal() const { return (nSequence == std::numeric_limits<unsigned int>::max()); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n); } std::string ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig).c_str()); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str()); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** An output of a transaction. It contains the public key that the next input * must be able to sign with to claim it. */ class CTxOut { public: int64 nValue; CScript scriptPubKey; CTxOut() { SetNull(); } CTxOut(int64 nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; } IMPLEMENT_SERIALIZE ( READWRITE(nValue); READWRITE(scriptPubKey); ) void SetNull() { nValue = -1; scriptPubKey.clear(); } bool IsNull() { return (nValue == -1); } void SetEmpty() { nValue = 0; scriptPubKey.clear(); } bool IsEmpty() const { return (nValue == 0 && scriptPubKey.empty()); } uint256 GetHash() const { return SerializeHash(*this); } friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey); } friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); } std::string ToStringShort() const { return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str()); } std::string ToString() const { if (IsEmpty()) return "CTxOut(empty)"; if (scriptPubKey.size() < 6) return "CTxOut(error)"; return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; enum GetMinFee_mode { GMF_BLOCK, GMF_RELAY, GMF_SEND, }; typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx; /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: static const int CURRENT_VERSION=1; int nVersion; unsigned int nTime; std::vector<CTxIn> vin; std::vector<CTxOut> vout; unsigned int nLockTime; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CTransaction() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nTime); READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); ) void SetNull() { nVersion = CTransaction::CURRENT_VERSION; nTime = GetAdjustedTime(); vin.clear(); vout.clear(); nLockTime = 0; nDoS = 0; // Denial-of-service prevention } bool IsNull() const { return (vin.empty() && vout.empty()); } uint256 GetHash() const { return SerializeHash(*this); } bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const { // Time based nLockTime implemented in 0.1.6 if (nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, vin) if (!txin.IsFinal()) return false; return true; } bool IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1); } bool IsCoinStake() const { // ppcoin: the coin stake transaction is marked with the first output empty return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty()); } /** Check for standard transaction types @return True if all outputs (scriptPubKeys) use only standard transaction forms */ bool IsStandard() const; /** Check for standard transaction types @param[in] mapInputs Map of previous transactions that have outputs we're spending @return True if all inputs (scriptSigs) use only standard transaction forms @see CTransaction::FetchInputs */ bool AreInputsStandard(const MapPrevTx& mapInputs) const; /** Count ECDSA signature operations the old-fashioned (pre-0.6) way @return number of sigops this transaction's outputs will produce when spent @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount() const; /** Count ECDSA signature operations in pay-to-script-hash inputs. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return maximum number of sigops required to validate this transaction's inputs @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const; /** Amount of bitcoins spent by this transaction. @return sum of all outputs (note: does not include fees) */ int64 GetValueOut() const { int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } /** Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything besides the hash of previous transactions, so may not be able to calculate this. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return Sum of value of all inputs (scriptSigs) @see CTransaction::FetchInputs */ int64 GetValueIn(const MapPrevTx& mapInputs) const; static bool AllowFree(double dPriority) { // Large (in bytes) low-priority (new, small-coin) transactions // need a fee. return dPriority > COIN * 2880 / 250; } int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK) const; bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL) { CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CTransaction::ReadFromDisk() : OpenBlockFile failed"); // Read transaction if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : fseek failed"); try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Return file pointer if (pfileRet) { if (fseek(filein, pos.nTxPos, SEEK_SET) != 0) return error("CTransaction::ReadFromDisk() : second fseek failed"); *pfileRet = filein.release(); } return true; } friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.nVersion == b.nVersion && a.nTime == b.nTime && a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); } std::string ToStringShort() const { std::string str; str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user")); return str; } std::string ToString() const { std::string str; str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction"); str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n", GetHash().ToString().substr(0,10).c_str(), nTime, nVersion, vin.size(), vout.size(), nLockTime ); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void print() const { printf("%s", ToString().c_str()); } bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet); bool ReadFromDisk(CTxDB& txdb, COutPoint prevout); bool ReadFromDisk(COutPoint prevout); bool DisconnectInputs(CTxDB& txdb); /** Fetch from memory and/or disk. inputsRet keys are transaction hashes. @param[in] txdb Transaction database @param[in] mapTestPool List of pending changes to the transaction index database @param[in] fBlock True if being called to add a new best-block to the chain @param[in] fMiner True if being called by CreateNewBlock @param[out] inputsRet Pointers to this transaction's inputs @param[out] fInvalid returns true if transaction is invalid @return Returns true if all inputs are in txdb or mapTestPool */ bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid); /** Sanity check previous transactions, then, if all checks succeed, mark them as spent by this transaction. @param[in] inputs Previous transactions (from FetchInputs) @param[out] mapTestPool Keeps track of inputs that need to be updated on disk @param[in] posThisTx Position of this transaction on disk @param[in] pindexBlock @param[in] fBlock true if called from ConnectBlock @param[in] fMiner true if called from CreateNewBlock @param[in] fStrictPayToScriptHash true if fully validating p2sh transactions @return Returns true if all checks succeed */ bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true); bool ClientConnectInputs(); bool CheckTransaction() const; bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL); bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age protected: const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const; }; /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { public: uint256 hashBlock; std::vector<uint256> vMerkleBranch; int nIndex; // memory only mutable bool fMerkleVerified; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = 0; nIndex = -1; fMerkleVerified = false; } IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); ) int SetMerkleBranch(const CBlock* pblock=NULL); int GetDepthInMainChain(CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { return GetDepthInMainChain() > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true); bool AcceptToMemoryPool(); }; /** A txdb record that contains the disk location of a transaction and the * locations of transactions that spend its outputs. vSpent is really only * used as a flag, but having the location is very helpful for debugging. */ class CTxIndex { public: CDiskTxPos pos; std::vector<CDiskTxPos> vSpent; CTxIndex() { SetNull(); } CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs) { pos = posIn; vSpent.resize(nOutputs); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(pos); READWRITE(vSpent); ) void SetNull() { pos.SetNull(); vSpent.clear(); } bool IsNull() { return pos.IsNull(); } friend bool operator==(const CTxIndex& a, const CTxIndex& b) { return (a.pos == b.pos && a.vSpent == b.vSpent); } friend bool operator!=(const CTxIndex& a, const CTxIndex& b) { return !(a == b); } int GetDepthInMainChain() const; }; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. * * Blocks are appended to blk0001.dat files on disk. Their location on disk * is indexed by CBlockIndex objects in memory. */ class CBlock { public: // header static const int CURRENT_VERSION=4; int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; // network and disk std::vector<CTransaction> vtx; // ppcoin: block signature - signed by one of the coin base txout[N]'s owner std::vector<unsigned char> vchBlockSig; // memory only mutable std::vector<uint256> vMerkleTree; // Denial-of-service detection: mutable int nDoS; bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; } CBlock() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); // ConnectBlock depends on vtx following header to generate CDiskTxPos if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY))) { READWRITE(vtx); READWRITE(vchBlockSig); } else if (fRead) { const_cast<CBlock*>(this)->vtx.clear(); const_cast<CBlock*>(this)->vchBlockSig.clear(); } ) void SetNull() { nVersion = CBlock::CURRENT_VERSION; hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; vtx.clear(); vchBlockSig.clear(); vMerkleTree.clear(); nDoS = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const { uint256 thash; void * scratchbuff = scrypt_buffer_alloc(); scrypt_hash(CVOIDBEGIN(nVersion), sizeof(block_header), UINTBEGIN(thash), scratchbuff); scrypt_buffer_free(scratchbuff); return thash; } int64 GetBlockTime() const { return (int64)nTime; } void UpdateTime(const CBlockIndex* pindexPrev); // ppcoin: entropy bit for stake modifier if chosen by modifier unsigned int GetStakeEntropyBit(unsigned int nHeight) const { // Take last bit of block hash as entropy bit unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu); if (fDebug && GetBoolArg("-printstakemodifier")) printf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetHash().ToString().c_str(), nEntropyBit); return nEntropyBit; } // ppcoin: two types of block: proof-of-work or proof-of-stake bool IsProofOfStake() const { return (vtx.size() > 1 && vtx[1].IsCoinStake()); } bool IsProofOfWork() const { return !IsProofOfStake(); } std::pair<COutPoint, unsigned int> GetProofOfStake() const { return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0); } // ppcoin: get max transaction timestamp int64 GetMaxTransactionTime() const { int64 maxTransactionTime = 0; BOOST_FOREACH(const CTransaction& tx, vtx) maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime); return maxTransactionTime; } uint256 BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } std::vector<uint256> GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet) { // Open history file to append CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlock::WriteToDisk() : AppendBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlock::WriteToDisk() : ftell failed"); nBlockPosRet = fileOutPos; fileout << *this; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0) FileCommit(fileout); return true; } bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true) { SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlock::ReadFromDisk() : OpenBlockFile failed"); if (!fReadTransactions) filein.nType |= SER_BLOCKHEADERONLY; // Read block try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits)) return error("CBlock::ReadFromDisk() : errors in block header"); return true; } void print() const { printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n", GetHash().ToString().c_str(), nVersion, hashPrevBlock.ToString().c_str(), hashMerkleRoot.ToString().c_str(), nTime, nBits, nNonce, vtx.size(), HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str()); for (unsigned int i = 0; i < vtx.size(); i++) { printf(" "); vtx[i].print(); } printf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str()); printf("\n"); } bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex); bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false); bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true); bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew); bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos); bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const; bool AcceptBlock(); bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block bool SignBlock(const CKeyStore& keystore); bool CheckBlockSignature() const; private: bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew); }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. pprev and pnext link a path through the * main/longest chain. A blockindex may have multiple pprev pointing back * to it, but pnext will only point forward to the longest branch, or will * be null if the block is not part of the longest chain. */ class CBlockIndex { public: const uint256* phashBlock; CBlockIndex* pprev; CBlockIndex* pnext; unsigned int nFile; unsigned int nBlockPos; CBigNum bnChainTrust; // ppcoin: trust score of block chain int nHeight; int64 nMint; int64 nMoneySupply; unsigned int nFlags; // ppcoin: block index flags enum { BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier }; uint64 nStakeModifier; // hash modifier for proof-of-stake unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only // proof-of-stake specific fields COutPoint prevoutStake; unsigned int nStakeTime; uint256 hashProofOfStake; // block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockIndex() { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = 0; nBlockPos = 0; nHeight = 0; bnChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProofOfStake = 0; prevoutStake.SetNull(); nStakeTime = 0; nVersion = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block) { phashBlock = NULL; pprev = NULL; pnext = NULL; nFile = nFileIn; nBlockPos = nBlockPosIn; nHeight = 0; bnChainTrust = 0; nMint = 0; nMoneySupply = 0; nFlags = 0; nStakeModifier = 0; nStakeModifierChecksum = 0; hashProofOfStake = 0; if (block.IsProofOfStake()) { SetProofOfStake(); prevoutStake = block.vtx[1].vin[0].prevout; nStakeTime = block.vtx[1].nTime; } else { prevoutStake.SetNull(); nStakeTime = 0; } nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CBlock GetBlockHeader() const { CBlock block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64 GetBlockTime() const { return (int64)nTime; } CBigNum GetBlockTrust() const; bool IsInMainChain() const { return (pnext || this == pindexBest); } bool CheckIndex() const { return true; } enum { nMedianTimeSpan=11 }; int64 GetMedianTimePast() const { int64 pmedian[nMedianTimeSpan]; int64* pbegin = &pmedian[nMedianTimeSpan]; int64* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } int64 GetMedianTime() const { const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan/2; i++) { if (!pindex->pnext) return GetBlockTime(); pindex = pindex->pnext; } return pindex->GetMedianTimePast(); } /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last nToCheck blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck); bool IsProofOfWork() const { return !(nFlags & BLOCK_PROOF_OF_STAKE); } bool IsProofOfStake() const { return (nFlags & BLOCK_PROOF_OF_STAKE); } void SetProofOfStake() { nFlags |= BLOCK_PROOF_OF_STAKE; } unsigned int GetStakeEntropyBit() const { return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1); } bool SetStakeEntropyBit(unsigned int nEntropyBit) { if (nEntropyBit > 1) return false; nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0); return true; } bool GeneratedStakeModifier() const { return (nFlags & BLOCK_STAKE_MODIFIER); } void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier) { nStakeModifier = nModifier; if (fGeneratedStakeModifier) nFlags |= BLOCK_STAKE_MODIFIER; } std::string ToString() const { return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)", pprev, pnext, nFile, nBlockPos, nHeight, FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(), GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW", nStakeModifier, nStakeModifierChecksum, hashProofOfStake.ToString().c_str(), prevoutStake.ToString().c_str(), nStakeTime, hashMerkleRoot.ToString().c_str(), GetBlockHash().ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; uint256 hashNext; CDiskBlockIndex() { hashPrev = 0; hashNext = 0; } explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : 0); hashNext = (pnext ? pnext->GetBlockHash() : 0); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(hashNext); READWRITE(nFile); READWRITE(nBlockPos); READWRITE(nHeight); READWRITE(nMint); READWRITE(nMoneySupply); READWRITE(nFlags); READWRITE(nStakeModifier); if (IsProofOfStake()) { READWRITE(prevoutStake); READWRITE(nStakeTime); READWRITE(hashProofOfStake); } else if (fRead) { const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull(); const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0; const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0; } // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); ) uint256 GetBlockHash() const { CBlock block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)", GetBlockHash().ToString().c_str(), hashPrev.ToString().c_str(), hashNext.ToString().c_str()); return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ class CBlockLocator { protected: std::vector<uint256> vHave; public: CBlockLocator() { } explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); } explicit CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); ) void SetNull() { vHave.clear(); } bool IsNull() { return vHave.empty(); } void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); } int GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet); } int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } }; class CTxMemPool { public: mutable CCriticalSection cs; std::map<uint256, CTransaction> mapTx; std::map<COutPoint, CInPoint> mapNextTx; bool accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs); bool addUnchecked(const uint256& hash, CTransaction &tx); bool remove(CTransaction &tx); void clear(); void queryHashes(std::vector<uint256>& vtxid); unsigned long size() { LOCK(cs); return mapTx.size(); } bool exists(uint256 hash) { return (mapTx.count(hash) != 0); } CTransaction& lookup(uint256 hash) { return mapTx[hash]; } }; extern CTxMemPool mempool; #endif
[ "root@localhost.localdomain" ]
root@localhost.localdomain
8871d673d5d2d1d2fed836530caf4ba084fde102
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/ProvidesEndpoint/UNIX_ProvidesEndpoint_SOLARIS.hxx
0e588878e083edfb93d18e7bf5b4eb13b7077919
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
130
hxx
#ifdef PEGASUS_OS_SOLARIS #ifndef __UNIX_PROVIDESENDPOINT_PRIVATE_H #define __UNIX_PROVIDESENDPOINT_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com