text
stringlengths
8
6.88M
// ************************************** // File: KTimer.h // Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved. // Website: http://www.nuiengine.com // Description: This code is part of NUI Engine (NUI Graphics Lib) // Comments: // Rev: 2 // Created: 2017/4/12 // Last edit: 2017/4/28 // Author: Chen Zhi // E-mail: cz_666@qq.com // License: APACHE V2.0 (see license file) // *************************************** #ifndef KTimer_DEFINED #define KTimer_DEFINED #include "NE_type.h" #include <boost/enable_shared_from_this.hpp> #include <boost/timer/timer.hpp> #include <boost/thread.hpp> #include "sigslot.h" //#include "KView.h" class KScreen; typedef kn_int TimerID; using boost::timer::cpu_times; using boost::timer::nanosecond_type; class KView; typedef boost::weak_ptr<KView> KView_WEAK_PTR; class NUI_API KTimer:public boost::enable_shared_from_this<KTimer> { public: KTimer(); KTimer(int interval, int times = -1); //间隔时间 千分之一秒 和触发次数 -1无限次 ~KTimer(); bool isActive() const; //是否活动 start开始活动 stop则不活动 void setInterval(int v); kn_int getInterval() const; void setTimes(int value); int getTimes(); bool start(); //如果不传入screen,使用m_p_view的screen,如果m_p_view也为空,则启动无效 void restart(); void stop(); bool check(); //定时检查函数 kn_int64 elapsedTime(); //设置view,更安全,不设置,需要上层保证定时器调用时对应的回调对象是有效的 void setView(KView_WEAK_PTR); typedef sigslot::signal1<kn_int> TimeOutSignal; TimeOutSignal m_timeout_signal; private: KView_WEAK_PTR m_p_view; boost::timer::cpu_timer m_timer; kn_int m_interval; int m_times; int m_time; // 运行次数 kn_bool m_b_run; nanosecond_type m_last_time; }; typedef boost::shared_ptr<KTimer> KTimer_PTR; typedef std::list<KTimer_PTR> LSTTIMER; //全局的插入函数 void AddNUITimer(KTimer_PTR); void CheckNUITimer(); ///////////////////////////////////////////// class NUI_API KThreadTimer:public boost::noncopyable { public: KThreadTimer(); ~KThreadTimer(); // 该函数不宜内联 bool IsActive() const; TimerID GetTimerID() const; kn_int Interval() const; void SetSingleShot(bool value); bool IsSingleShot() const; bool Start(TimerID id, kn_int msec); void Stop(); kn_int64 ElapsedTime(); typedef sigslot::signal1<kn_int> TimeOutSignal; TimeOutSignal m_timeoutSignal; private: static void ThreadProc(KThreadTimer* p); boost::timer::cpu_timer m_timer; boost::thread* m_pThread; TimerID m_id; kn_int m_interval; bool m_bSingleShot; }; #endif
#define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb/stb_image_resize.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" #include <filesystem> #include <iostream> #include <vector> #include "Generator.hpp" int main( int argc, char** argv ){ if( argc < 2 ){ std::cout << "Usage: " << argv[0] << " folder_to_save_into" << std::endl; return 1; } std::filesystem::path save_path( argv[1] ); if( !std::filesystem::exists( save_path )){ std::cout << save_path.string() << " doesn't exist."; } size_t size = 65536 * 2; std::vector<uint8_t> testimage( size * size ); for( size_t i = 0; i < size_t(65536) * size_t(65536); ++i ){ testimage[i] = std::abs((long)i * 2 - 255) % 255; } constexpr size_t layers = 2; constexpr size_t compression_per_run = 16; size_t total_iterations = 0; for( size_t i = 0; i < layers; ++i ){ total_iterations += std::pow( std::pow( compression_per_run, layers - i - 1 ), 2 ); } std::cout << total_iterations << std::endl; size_t counter = 0; for( size_t res = 0; res < layers; ++res ){ auto curr_path = save_path / std::to_string( res ); if( std::filesystem::exists( curr_path )) std::filesystem::remove_all( curr_path ); std::filesystem::create_directory( curr_path ); const size_t tiles = std::pow( compression_per_run, layers - res - 1 ); const size_t tile_size = size / tiles; const size_t pixels_to_compress = std::pow( compression_per_run, res ); // std::cout << size << " " << pixels_to_compress << " " << tile_size / pixels_to_compress << "\n\n"; for( size_t y = 0; y < tiles; ++y ){ for( size_t x = 0; x < tiles; ++x ){ auto output = TerrainGen::compress( testimage, size, pixels_to_compress, tile_size / pixels_to_compress, x, y ); ++counter; if( !(counter % 1)){ printf( "\r%6.2f%%", double( counter ) / double( total_iterations ) * 100.0); fflush( stdout ); } /* for( auto i: output ) std::cout << (unsigned)i << " "; std::cout << std::endl; */ stbi_write_png(( curr_path / ( std::to_string( x ) + "_" + std::to_string( y ) + ".png" )).c_str(), tile_size / pixels_to_compress, tile_size / pixels_to_compress, 1, output.data(), tile_size / pixels_to_compress ); } } printf( "\n" ); } }
//#include "../../lexertl/debug.hpp" #include "../../lexertl/generator.hpp" #include "../../lexertl/lookup.hpp" #include "../../lexertl/memory_file.hpp" int main(int argc, char *argv[]) { enum {eoi, word, ws, newline}; lexertl::rules rules_; lexertl::state_machine sm_; rules_.insert_macro("ws", "[ \t]"); rules_.insert_macro("nonws", "[^ \t\n]"); rules_.push("{nonws}+", word); rules_.push("{ws}+", ws); rules_.push("\r|\n|\r\n", newline); lexertl::generator::build(rules_, sm_); // lexertl::debug::dump(sm_, std::cout); lexertl::memory_file if_(argc == 2 ? argv[1] : "lexertl/licence_1_0.txt"); const char *start_ = if_.data(); const char *end_ = start_ + if_.size(); lexertl::cmatch results_(start_, end_); int cc = 0, wc = 0, lc = 0; do { lexertl::lookup(sm_, results_); switch (results_.id) { case eoi: break; case word: cc += results_.second - results_.first; ++wc; break; case ws: cc += results_.second - results_.first; break; case newline: ++lc; cc += results_.second - results_.first; break; default: assert(0); break; } } while (results_.id != eoi); std::cout << "lines: " << lc << ", words: " << wc << ", chars: " << cc << '\n'; return 0; }
#include <QDebug> #include "Connector.h" #include "NameLabel.h" #include "TcpBus.h" #include "Vna.h" using namespace RsaToolbox; #include <QString> #include <QtTest> #include <QSignalSpy> #include <QScopedPointer> class test_Vna : public QObject { Q_OBJECT public: test_Vna(); private: Vna vna; QScopedPointer<Log> log; int cycle; bool isZva; QString appName; QString appVersion; QString filename; QString logPath; private Q_SLOTS: void init(); void cleanup(); void isError(); void connectors(); void calKits(); void importCalKit(); void exportCalKit(); void channels(); void createChannel(); void traces(); void createTrace(); void diagrams(); void createDiagram(); }; test_Vna::test_Vna() { cycle = 0; isZva = false; appName = "test_VnaSettings"; appVersion = "0"; filename = "%1 %2 Log.txt"; logPath = "../RsaToolboxTest/Results/Vna Test Logs"; } void test_Vna::init() { log.reset(new Log(logPath, filename.arg(cycle++).arg("init()"), appName, appVersion)); log->printApplicationHeader(); vna.resetBus(new TcpBus(TCPIP_CONNECTION, "127.0.0.1", 1000)); vna.useLog(log.data()); vna.printInfo(); vna.settings().setEmulationOff(); QVERIFY(vna.settings().isEmulationOff()); vna.settings().resetIdString(); vna.settings().resetOptionsString(); vna.settings().userPresetOff(); vna.settings().calibrationPresetOff(); vna.preset(); vna.clearStatus(); vna.disconnectLog(); } void test_Vna::cleanup() { vna.disconnectLog(); log.reset(new Log(logPath, filename.arg(cycle++).arg("cleanup()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); vna.clearStatus(); vna.resetBus(); vna.disconnectLog(); } void test_Vna::isError() { log.reset(new Log(logPath, filename.arg(cycle++).arg("isError()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); int code; QString msg; vna.clearStatus(); vna.write("Even more; junk!\n"); QVERIFY(vna.nextError(code, msg)); QVERIFY(code != 0); QVERIFY(!msg.isEmpty()); QVERIFY(vna.nextError(code, msg)); QVERIFY(code != 0); QVERIFY(!msg.isEmpty()); QVERIFY(!vna.nextError(code, msg)); QVERIFY(code == 0); QVERIFY(msg.isEmpty()); vna.clearStatus(); vna.write("JUNK\n"); QVERIFY(vna.isError()); vna.clearStatus(); QVERIFY(!vna.isError()); QVERIFY(!vna.isError()); vna.clearStatus(); vna.disconnectLog(); } void test_Vna::connectors() { log.reset(new Log(logPath, filename.arg(cycle++).arg("connectors()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QVector<Connector> types = vna.connectorTypes(); bool hasN50 = false; Connector N50(N_50_OHM_CONNECTOR, MALE_GENDER); foreach(Connector type, types) { hasN50 = hasN50 || type.isType(N50); } QVERIFY(hasN50); QVERIFY(vna.isConnectorType(N50)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::calKits() { log.reset(new Log(logPath, filename.arg(cycle++).arg("calKits()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QVector<NameLabel> kits = vna.calKits(); NameLabel n50Ideal("N 50 Ohm Ideal Kit", ""); bool hasN50Ideal = false; foreach (NameLabel kit, kits) { hasN50Ideal = hasN50Ideal || (kit == n50Ideal); } QVERIFY(hasN50Ideal); QVERIFY(vna.isCalKit(n50Ideal)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::importCalKit() { log.reset(new Log(logPath, filename.arg(cycle++).arg("importCalKit()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QString pathName; NameLabel calkit; if (isZva) { calkit = NameLabel("importCalKit",""); pathName = "C:\\Rohde&Schwarz\\Nwa\\Calibration\\Kits\\importCalKit.calkit"; } else { calkit = NameLabel(); pathName = ""; } QVERIFY(vna.isNotCalKit(calkit)); vna.importCalKit(pathName); QVERIFY(vna.isCalKit(calkit)); vna.deleteCalKit(calkit); QVERIFY(vna.isNotCalKit(calkit)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::exportCalKit() { log.reset(new Log(logPath, filename.arg(cycle++).arg("exportCalKit()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QString pathName; NameLabel calkit; if (isZva) { calkit = NameLabel("exportCalKit",""); pathName = "C:\\Rohde&Schwarz\\Nwa\\Calibration\\Kits\\exportCalKit.calkit"; } else { calkit = NameLabel("",""); pathName = ""; } QVERIFY(vna.isCalKit(calkit)); QVERIFY(vna.fileSystem().isNotFile(pathName)); vna.exportCalKit(calkit, pathName); QVERIFY(vna.fileSystem().isFile(pathName)); vna.fileSystem().deleteFile(pathName); QVERIFY(vna.fileSystem().isNotFile(pathName)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::channels() { log.reset(new Log(logPath, filename.arg(cycle++).arg("channels()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QVector<uint> channels = vna.channels(); QVERIFY(channels.isEmpty() == false); QCOMPARE(channels.first(), uint(1)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::createChannel() { log.reset(new Log(logPath, filename.arg(cycle++).arg("createChannel()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); uint myChannel = vna.createChannel(); QVERIFY(vna.isChannel(myChannel)); vna.deleteChannel(myChannel); QVERIFY(vna.isNotChannel(myChannel)); vna.createChannel(); vna.createChannel(); vna.createChannel(); vna.deleteChannels(); QVERIFY(vna.channels().isEmpty()); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::traces() { log.reset(new Log(logPath, filename.arg(cycle++).arg("traces()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QStringList traces = vna.traces(); QVERIFY(traces.isEmpty() == false); QCOMPARE(traces.first(), QString("Trc1")); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::createTrace() { log.reset(new Log(logPath, filename.arg(cycle++).arg("createTrace()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QString myTrace = "myTrace"; vna.createTrace(myTrace, 1); QVERIFY(vna.isTrace(myTrace)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::diagrams() { log.reset(new Log(logPath, filename.arg(cycle++).arg("diagrams()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); QVector<uint> diagrams = vna.diagrams(); QVERIFY(diagrams.isEmpty() == false); QCOMPARE(diagrams.first(), uint(1)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } void test_Vna::createDiagram() { log.reset(new Log(logPath, filename.arg(cycle++).arg("createDiagrams()"), appName, appVersion)); log->printApplicationHeader(); vna.useLog(log.data()); vna.printInfo(); uint myDiagram = vna.createDiagram(); QVERIFY(vna.isDiagram(myDiagram)); QVERIFY(vna.isError() == false); vna.disconnectLog(); } QTEST_APPLESS_MAIN(test_Vna) #include "test_Vna.moc"
#include "Bike.h" #include <iostream> using namespace std; Bike::Bike() : Vehicle(2, 2) { cout << "ctor bike " << wheels << " " << capacity << endl; } Bike::Bike(const Bike& bike) : Vehicle::Vehicle(bike) { this->wheels = bike.wheels; this->capacity = bike.capacity; cout << "cctor bike " << wheels << " " << capacity << endl; } Bike::~Bike() { cout << "dtor bike " << wheels << " " << capacity << endl; } Bike& Bike::operator=(const Bike& bike) { this->wheels = bike.wheels; this->capacity = bike.capacity; cout << "assign bike " << wheels << " " << capacity << endl; return *this; } void Bike::ride() { cout << "someone is riding this bike " << wheels << " " << capacity << endl; } void Bike::clean() { cout << "someone is cleaning this bike " << wheels << " " << capacity << endl; } void Bike::park() { cout << "someone is parking this bike " << wheels << " " << capacity << endl; }
#ifndef CoinConf_H #define CoinConf_H #include "hiredis.h" #include "CDL_TCP_Handler.h" #include "CDL_Timer_Handler.h" #include "Packet.h" #include "Player.h" class Player; class CoinConf; class RedisRTimer:public CCTimer { public: RedisRTimer(){} ; virtual ~RedisRTimer() {}; inline void init(CoinConf* redissrv){this->redissrv=redissrv;}; private: virtual int ProcessOnTimerOut(); CoinConf* redissrv; }; class CoinConf { public: public: static CoinConf* getInstance(); virtual ~CoinConf(); int InitRedis(); int pingSrv(); int getCoinCfg(CoinCfg * coincfg); bool isUserInBlackList(int uid); private: bool isConnect; redisContext *m_redis; //Á¬˝Óhiredis redisReply *reply; //hiredis»Ř¸´ CoinConf(); RedisRTimer* heartBeatTimer; }; #endif
#include<bits/stdc++.h> using namespace std; struct frac{ int num; int dem; double dValue = double(num)/double(dem); }; int gcd(int x, int y){ while(x*y != 0){ if(x > y) x %= y; else y %= x; } return x + y; } frac simplify(frac f){ int cd = gcd(f.num, f.dem); return frac{f.num/cd, f.dem/cd}; } bool rule(frac a, frac b){ return a.dValue < b.dValue; } int main(){ freopen("SPXS.inp", "r", stdin); freopen("SPXS.out", "w", stdout); map<double,bool>visited; vector<frac> a; int n, k; cin >> n >> k; for(int i = 1; i <= n; i++){ for(int j = 0; j <= i; j++){ frac simplified = simplify({j,i}); if(visited[simplified.dValue] == 0){ a.push_back(simplified); visited[simplified.dValue] = 1; } } } sort(a.begin(), a.end(), rule); cout << a[k-1].num << "/" << a[k-1].dem; return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ int n,k; double l,v1,v2; cin>>n>>l>>v1>>v2>>k; int p=(n-1)/k+1; double t=l/((double)p*v2-(v2-v1)/(v2+v1)*v2*((double)p-1)); cout<<setiosflags(ios::fixed)<<setprecision(10)<<(l-v2*t)/v1+t; return 0; }
#ifndef MAINWIDGET_H #define MAINWIDGET_H #include <QWidget> #include <QPalette> #include <QPushButton> #include <QLabel> namespace Ui { class MainWidget; } class MainWidget : public QWidget { Q_OBJECT public: explicit MainWidget(QWidget *parent = 0); ~MainWidget(); //声明槽函数 public slots: void startBtnSlot(); private: QPushButton * start;//开始和退出按钮 QPushButton * exit; QPalette palette;//调色板 QLabel * instruction;//游戏说明标签 Ui::MainWidget *ui; }; #endif // MAINWIDGET_H
#include <plot_lib/utils.h> namespace as64_ { namespace pl_ { void Semaphore::notify() { std::lock_guard<decltype(mutex_)> lock(mutex_); // ++count_; count_ = true; condition_.notify_one(); } void Semaphore::wait() { std::unique_lock<decltype(mutex_)> lock(mutex_); // Handle spurious wake-ups. while(!count_) condition_.wait(lock); // --count_; count_ = false; } bool Semaphore::try_wait() { std::lock_guard<decltype(mutex_)> lock(mutex_); if(count_) { // --count_; count_ = false; return true; } return false; } } // namespace pl_ } // namespace as64_
#include <iostream> #include <algorithm> #include <fstream> #include <complex> #include <vector> #include <math.h> using namespace std; typedef complex<double> cld; typedef long long ll; const int M = 16; const int N = 1 << M; const int MOD = 786433; const double PI = acos(-1.); cld roots[N], a[N], b[N], f[M + 3][N], invf[M + 3][N]; int revbit[N]; void fft(cld* arr, cld* out) { for (int i = 0; i < N; ++i) { out[ revbit[i] ] = arr[i]; } for (int window = 2; window <= N; window += window) { for (int L = 0; L < N; L += window) { int k = N / window; int pos = k; int shift = window / 2; for (int l = L, r = L + shift; l < r; ++l) { cld a = out[l], b = out[l + shift]; out[l] = a + roots[pos] * b; out[l + shift] = a - roots[pos] * b; pos += k; } } } } int main() { freopen("avl.in", "r", stdin); freopen("avl.out", "w", stdout); roots[0] = 1; double rootAngle = 2. * PI / N; roots[1] = cld(cos(rootAngle), sin(rootAngle)); for (int i = 2; i < N; ++i) { roots[i] = cld(cos(rootAngle * i), sin(rootAngle * i)); } for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) if (i & (1 << j)) { revbit[i] += (1 << (M - j - 1)); } } f[0][0] = 1; f[0][1] = 1; f[1][2] = 2; f[1][3] = 1; fft(f[0], invf[0]); fft(f[1], invf[1]); for (int h = 2; h < M; ++h) { for (int i = 0; i < N; ++i) { invf[h][i] = invf[h - 1][i] * invf[h - 1][i]; if (h > 1) { invf[h][i] += 2. * invf[h - 1][i] * invf[h - 2][i]; } } fft(invf[h], f[h]); reverse(f[h], f[h] + N); for (int i = N - 1; i; --i) { ll value = ll(f[h][i - 1].real() / N + 0.5); f[h][i] = double(value % MOD); } f[h][0] = 0; fft(f[h], invf[h]); } for (int n = 1; n <= 10; ++n) for (int h = 1; h <= n; ++h) cerr << n << " " << h << ": " << ll(f[h][n].real() + 0.5) << endl; int n, h; cin >> n >> h; cout << ll(f[h][n].real() + 0.5) << endl; return 0; }
////////////////////////////////////////////////////////////////////// ///Copyright (C) 2011-2012 Benjamin Quach // //This file is part of the "Lost Horizons" video game demo // //"Lost Horizons" 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/>. // /////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "gamemanager.h" #include "GFramework.h" #define SELECTDISTANCE 32 #define CARGODISTANCE 500 #define SHOOTTIME 600 #define THINKTIME 100 //constructor gameManager::gameManager(irr::IrrlichtDevice *graphics, KeyListener *receiver, irrklang::ISoundEngine *sound) { //save vaariables for later use this->graphics=graphics; this->receiver = receiver; this->sound = sound; pd_think_time = graphics->getTimer()->getTime(); playerDead=false; think_time = 0; } //super nuke gameManager::~gameManager() { //nuke function //delete everything for(int i=0; i<ship_manager.size(); i++) { ship_manager[i]->drop(); ship_manager.erase(ship_manager.begin()+i); } ship_manager.clear(); for(int i=0; i<fighter_manager.size(); i++) { fighter_manager[i]->drop(); fighter_manager.erase(fighter_manager.begin()+i); } fighter_manager.clear(); for(int i=0; i<projectile_manager.size(); i++) { projectile_manager[i]->drop(); projectile_manager.erase(projectile_manager.begin()+i); } projectile_manager.clear(); for(int i=0; i<pd_manager.size(); i++) { pd_manager[i]->drop(); pd_manager.erase(pd_manager.begin()+i); } pd_manager.clear(); for(int i=0; i<planet_manager.size(); i++) { planet_manager[i]->drop(); planet_manager.erase(planet_manager.begin()+i); } planet_manager.clear(); for(int i=0; i<cargo_manager.size(); i++) { cargo_manager[i]->drop(); cargo_manager.erase(cargo_manager.begin()+i); } cargo_manager.clear(); } void gameManager::drop() { delete this; } //---------------------------------------------------------------------------------------------- //Insert AI functions here //Call from gamemanager loop CShip *gameManager::getClosestShip(CShip *ship) { core::vector3df pos = ship->getPos(); //unsigned for double the spaec for(unsigned int i = 0; i<ship_manager.size(); i++) { if(pos.getDistanceFrom(ship_manager[i]->getPos())<7000) { return ship_manager[i]; } } return 0; } CShip *gameManager::getClosestAlliedShip(CShip *ship) { core::vector3df pos = ship->getPos(); for(unsigned int i = 0; i < ship_manager.size(); i ++) { //make sure it cant attack ships that are neutral if(ship_manager[i]->getShipFaction()!=FACTION_NEUTRAL) { if(ship_manager[i]->getShipFaction()==ship->getShipFaction()) { if(pos.getDistanceFrom(ship_manager[i]->getPos())<7000) { return ship_manager[i]; } } } } return 0; } //gets closest enemy ship within 7km CShip *gameManager::getClosestEnemyShip(CShip *ship) { core::vector3df pos = ship->getPos(); //scan the ship array for(unsigned int i = 0; i < ship_manager.size(); i ++) { //make sure it cant attack ships that are neutral if(ship_manager[i]->getShipFaction()!=FACTION_NEUTRAL) { if(ship_manager[i]->getShipFaction()!=ship->getShipFaction()) { if(pos.getDistanceFrom(ship_manager[i]->getPos())<7000) { if(ship_manager[i]->getHullPoints()>0) return ship_manager[i]; } } } } return 0; } //function to determine the closest hostile station CShip *gameManager::getClosestEnemyStation(CShip *ship) { core::vector3df pos = ship->getPos(); //temporary variables int min_value_so_far = 0; int min_value_temp = 0; CShip *temp = 0; for(unsigned int i = 0; i<station_manager.size(); i++) { if(station_manager[i]->getShipFaction()!=FACTION_NEUTRAL) { if(station_manager[i]->getShipFaction()!=ship->getShipFaction()) { //stores the distance from current station min_value_temp = pos.getDistanceFrom(station_manager[i]->getPos()); //if the i variable hits station manager size (-1 of course, since the count starts at 0) if(i = station_manager.size()-1) { return temp; } else { //initializer if(min_value_so_far = 0) { min_value_so_far = min_value_temp; temp = station_manager[i]; } else { //if the value is smaller than the other ones //store until another smaller variable appears. if(min_value_temp < min_value_so_far) { min_value_so_far = min_value_temp; temp = station_manager[i]; } } } } } } } CShip *gameManager::getClosestEnemyShipFighter(fighter *f) { core::vector3df pos = f->getPos(); //scan the ship array for(unsigned int i = 0; i < ship_manager.size(); i ++) { //make sure it cant attack ships that are neutral if(ship_manager[i]->getShipFaction()!=FACTION_NEUTRAL) { if(ship_manager[i]->getShipFaction()!=f->getFighterFaction()) { if(pos.getDistanceFrom(ship_manager[i]->getPos())<7000) { return ship_manager[i]; } } } } return 0; } //function to determine the closest hostile station planet *gameManager::getClosestEnemyPlanet(CShip *ship) { core::vector3df pos = ship->getPos(); //temporary variables int min_value_so_far = 0; planet *temp = 0; for(unsigned int i = 0; i<planet_manager.size(); i++) { if(planet_manager[i]->getFaction()!=FACTION_NEUTRAL) { if(planet_manager[i]->getFaction()!= ship->getShipFaction()) { if(min_value_so_far == 0) { min_value_so_far = pos.getDistanceFrom(planet_manager[i]->getPos()); temp = planet_manager[i]; } else { if(pos.getDistanceFrom(planet_manager[i]->getPos()) < min_value_so_far) { min_value_so_far = pos.getDistanceFrom(planet_manager[i]->getPos()); temp = planet_manager[i]; } } } } } return temp; } //same as above function except that it searches for allied planets planet *gameManager::getClosestAlliedPlanet(CShip *ship) { core::vector3df pos = ship->getPos(); int min_value_so_far = 0; planet *temp = 0; for(unsigned int i = 0; i<planet_manager.size(); i++) { if(planet_manager[i]->getFaction()!=FACTION_NEUTRAL) { if(planet_manager[i]->getFaction()== ship->getShipFaction()) { if(min_value_so_far == 0) { min_value_so_far = pos.getDistanceFrom(planet_manager[i]->getPos()); temp = planet_manager[i]; } else { if(pos.getDistanceFrom(planet_manager[i]->getPos()) < min_value_so_far) { min_value_so_far = pos.getDistanceFrom(planet_manager[i]->getPos()); temp = planet_manager[i]; } } } } } return temp; } fighter *gameManager::getClosestEnemyFighter(fighter *f) { core::vector3df pos = f->getPos(); //scan the ship array for(unsigned int i = 0; i < fighter_manager.size(); i ++) { //make sure it cant attack ships that are neutral if(fighter_manager[i]->getFighterFaction()!=FACTION_NEUTRAL) { if(fighter_manager[i]->getFighterFaction()!=f->getFighterFaction()) { if(pos.getDistanceFrom(fighter_manager[i]->getPos())<1000) { return fighter_manager[i]; } } } } return 0; } fighter *gameManager::getClosestEnemyFighterShip(CShip *ship) { core::vector3df pos = ship->getPos(); //scan the ship array for(unsigned int i = 0; i < fighter_manager.size(); i ++) { //make sure it cant attack ships that are neutral if(fighter_manager[i]->getFighterFaction()!=FACTION_NEUTRAL) { if(fighter_manager[i]->getFighterFaction()!=ship->getShipFaction()) { if(pos.getDistanceFrom(fighter_manager[i]->getPos())<1000) { return fighter_manager[i]; } } } } return 0; } void gameManager::searchForTarget(CShip *ship, Player *CPlayer, f32 frameDeltaTime) { //if player is really close, he takes priority //other than that, other ai ships get shot at first if(ship->getWarping()==false) { if(getClosestEnemyShip(ship)!=0 || ship->getPos().getDistanceFrom(CPlayer->getPos()) < 7000) { if(ship->getHostileToPlayer()==true) { if(ship->getPos().getDistanceFrom(CPlayer->getPos())<7000) { //attack player //since player isnt actually of CShip object, this has to occur ship->engagePlayer(aimAtPlayer(CPlayer),frameDeltaTime); } else { ship->setTarget(getClosestEnemyShip(ship)); } } else { ship->setTarget(getClosestEnemyShip(ship)); } } } } //i'm kind of stupid and made ship and gamemanager function named the same void gameManager::engageCurrentTarget(CShip *ship, Player *CPlayer, f32 frameDeltaTime) { //ai has target //engage if(ship->getTarget()->ship) { if(ship->getHostileToPlayer()==true) { //if player is closer than the current target //engage the player if(ship->getPos().getDistanceFrom(CPlayer->getPos())<ship->getPos().getDistanceFrom(ship->getTarget()->getPos())) { ship->engagePlayer(aimAtPlayer(CPlayer),frameDeltaTime); if(ship->getNumFighters()>0) { //make timer for fighter creation if(ship->getFighterCreationTime() < graphics->getTimer()->getTime()) { if(ship->getShipFaction()==FACTION_PROVIAN_CONSORTIUM) { vector3df pos = ship->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,ship->getPos(),ship->getRot(),fighters().PROV_RAPTOR,ship->getShipFaction(),ship->ship); f->moveToPoint(CPlayer->getPos()); addFighter(f); ship->modNumFighters(-1); ship->setFighterCreationTime(graphics->getTimer()->getTime()+1000); } } } } else { ship->engageCurrentTarget(frameDeltaTime); } } else { ship->engageCurrentTarget(frameDeltaTime); } } else { //if current target died //set current target to zero ship->setTarget(0); } } //makes turrets be able to aim at the player core::vector3df gameManager::aimAtPlayer(Player *CPlayer) { float Y = CPlayer->getRot().Y; float X = -CPlayer->getRot().X; core::vector3df pPos; //pPos.Y = CPlayer->getVelocity() * sin(Y * 3.1415/ 180); pPos.Y = CPlayer->getPos().Y; pPos.X = CPlayer->getVelocity() * cos(Y *3.1415/180); pPos.X += CPlayer->getPos().X; pPos.Z = CPlayer->getVelocity() * cos( X *3.1415 / 180 ); pPos.Z += CPlayer->getPos().Z; return pPos; } //end ai funcs //----------------------------------------------------------------------------------------------------------- //monster func //controls ships void gameManager::gameManagerLoop(f32 frameDeltaTime, irrklang::ISoundEngine *sound, Player* CPlayer, CAlertBox *alertBox, ShaderCallBack *callback) { //AI ship loop //Controls the ship AI // //Heres how the projectile shooting works. //Its not the best way to do it I'm sure //In order to have projectiles be able to collide with other objects without resorting to the inbuild irrlicht collision system because I don't understand it //You need to create the projectile in the gameManager class so it can be added to the projectile array //Since there is no way to send objects 'up' a heirachy level, the gameManager class needs to be constantly checking the ship classes if it wants to shoot //If the ship wants to shoot, the ship returns true for the primary_shoot variable //The ship itself does not create the projectile, the gameManager class does //So the gameManager object constantly scans each ship object to see if it wants to shoot, and then creates the projectile in a higher hierchy //Not the best way to do it, but I can't figure out any other ways. // //Also, the ship_manager loop MUST go before the projectile manager loop for(unsigned int i=0;i<ship_manager.size();i++) { if(ship_manager[i]->getHullPoints()>0) { ship_manager[i]->AIRun(frameDeltaTime); core::vector3df pos = ship_manager[i]->getPos(); //if ship is over 10km away from the player, it is out of range if(pos.getDistanceFrom(CPlayer->getPos())>10000) { ship_manager[i]->setTargetArrayVisible(false); } else { //make sure that player cannot target ships outside of range if(showShips != false) ship_manager[i]->setTargetArrayVisible(true); else ship_manager[i]->setTargetArrayVisible(false); } //hides ships when they are 50km away from the camera //otherwise, make them visible if(pos.getDistanceFrom(graphics->getSceneManager()->getActiveCamera()->getPosition())>CAMERA_HIDE_DISTANCE) { ship_manager[i]->setVisible(false); } else { ship_manager[i]->setVisible(true); } //BEGIN AI FUNCTIONS ///////////////////////////////////////////////////////// if(ship_manager[i]->getHullPoints() <800) { ship_manager[i]->setState(STATE_FLEE); } //target search //make sure ship doesnt have a target first //before searching if(ship_manager[i]->getState() == STATE_SEARCH) { //having problems with ships shooting wreckages //ship_manager[i]->resetCannons(); if(ship_manager[i]->getTarget()==0) { if(pos.getDistanceFrom(CPlayer->getPos())>6000 || ship_manager[i]->getHostileToPlayer()==false) ship_manager[i]->resetCannons(); //ship_manager[i]->resetCannons(); //search if ship has no current target if(ship_manager[i]->getShipFaction()!=FACTION_NEUTRAL) { searchForTarget(ship_manager[i],CPlayer,frameDeltaTime); ship_manager[i]->setVelocity(ship_manager[i]->getMaxVelocity()/2); if(getClosestAlliedPlanet(ship_manager[i])->getPos().getDistanceFrom(pos) < 30000) { ship_manager[i]->patrolArea(getClosestAlliedPlanet(ship_manager[i])->getPos()); } } //ai roles come into effect here } else { //if it has a target, shoot at it if(ship_manager[i]->getTarget()->getHullPoints()>0) { if(pos.getDistanceFrom(ship_manager[i]->getTarget()->getPos())<10000) engageCurrentTarget(ship_manager[i],CPlayer,frameDeltaTime); else ship_manager[i]->setTarget(0); } else { ship_manager[i]->setTarget(0); } if(ship_manager[i]->getNumFighters()>0) { //make timer for fighter creation if(ship_manager[i]->getFighterCreationTime() < graphics->getTimer()->getTime()) { if(ship_manager[i]->getShipFaction()==FACTION_TERRAN_FEDERATION) { vector3df pos = ship_manager[i]->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,ship_manager[i]->getPos(),ship_manager[i]->getRot(),fighters().TERR_DRAGONFLY,ship_manager[i]->getShipFaction(),ship_manager[i]->ship); f->setTarget(getClosestEnemyShip(ship_manager[i])); addFighter(f); ship_manager[i]->modNumFighters(-1); ship_manager[i]->setFighterCreationTime(graphics->getTimer()->getTime()+1000); } if(ship_manager[i]->getShipFaction()==FACTION_PROVIAN_CONSORTIUM) { vector3df pos = ship_manager[i]->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,ship_manager[i]->getPos(),ship_manager[i]->getRot(),fighters().PROV_RAPTOR,ship_manager[i]->getShipFaction(),ship_manager[i]->ship); f->setTarget(getClosestEnemyShip(ship_manager[i])); addFighter(f); ship_manager[i]->modNumFighters(-1); ship_manager[i]->setFighterCreationTime(graphics->getTimer()->getTime()+1000); } } } } } if(ship_manager[i]->getState() == STATE_FLEE) { ship_manager[i]->resetCannons(); //warp to closest allied planet if it is farther than warp dist if(getClosestAlliedPlanet(ship_manager[i])->getPos().getDistanceFrom(pos) > SHIP_WARP_DISTANCE) { ship_manager[i]->warpToPlanet(getClosestAlliedPlanet(ship_manager[i])); } } if(ship_manager[i]->getState()== STATE_ATTACK) { } //use point defenses if(getClosestEnemyFighterShip(ship_manager[i])!=0) { ship_manager[i]->PDatPoint(getClosestEnemyFighterShip(ship_manager[i])->getPos(),frameDeltaTime); ship_manager[i]->pdShoot(); if(ship_manager[i]->getNumFighters()>0) { //make timer for fighter creation if(ship_manager[i]->getFighterCreationTime() < graphics->getTimer()->getTime()) { if(ship_manager[i]->getShipFaction()==FACTION_TERRAN_FEDERATION) { vector3df pos = ship_manager[i]->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,ship_manager[i]->getPos(),ship_manager[i]->getRot(),fighters().TERR_DRAGONFLY,ship_manager[i]->getShipFaction(),ship_manager[i]->ship); f->setFighterTarget(getClosestEnemyFighterShip(ship_manager[i])); addFighter(f); ship_manager[i]->modNumFighters(-1); ship_manager[i]->setFighterCreationTime(graphics->getTimer()->getTime()+1000); } if(ship_manager[i]->getShipFaction()==FACTION_PROVIAN_CONSORTIUM) { vector3df pos = ship_manager[i]->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,ship_manager[i]->getPos(),ship_manager[i]->getRot(),fighters().PROV_RAPTOR,ship_manager[i]->getShipFaction(),ship_manager[i]->ship); f->setFighterTarget(getClosestEnemyFighterShip(ship_manager[i])); addFighter(f); ship_manager[i]->modNumFighters(-1); ship_manager[i]->setFighterCreationTime(graphics->getTimer()->getTime()+1000); } } } } else ship_manager[i]->resetPD(); //END AI FUNCS /////////////////////////// //ship collision funcs //basic bounding box collision //nothin fancy for(unsigned int l=i+1; l<ship_manager.size();l++) { //cant crash with oneself if(ship_manager[l]!=ship_manager[i]) { if(ship_manager[i]->ship->getTransformedBoundingBox().intersectsWithBox(ship_manager[l]->ship->getTransformedBoundingBox())) { //collision vector3df pos = ship_manager[l]->getPos()-ship_manager[i]->getPos(); vector3df rot = -(pos.getHorizontalAngle()); ship_manager[i]->applyForce(rot,ship_manager[i]->getVelocity(),frameDeltaTime); } } } if(ship_manager[i]->ship->getTransformedBoundingBox().intersectsWithBox(CPlayer->ship->getTransformedBoundingBox())) { //collision vector3df pos = CPlayer->getPos()-ship_manager[i]->getPos(); vector3df rot = pos.getHorizontalAngle(); ship_manager[i]->applyForce(-rot,ship_manager[i]->getVelocity(),frameDeltaTime); CPlayer->applyForce(rot,CPlayer->getVelocity(),frameDeltaTime); } //if ship wants to shoot //shoot primary turrets //havent implemented secondary turrets for ai yet if(ship_manager[i]->cannon.light_shoot==true) { for(unsigned int t = 0; t<ship_manager[i]->getLightTurretManager().size();t++) { if(rand()%ship_manager[i]->getLightTurretManager()[t]->getReloadTime()<SHOOTTIME*frameDeltaTime) { sound->play3D("res/sounds/weapons/gatling.wav",ship_manager[i]->getPos(),false,false,false); projectile *p = new gatlingBullet(graphics, ship_manager[i]->getLightTurretManager()[t]->getPos(), ship_manager[i]->getLightTurretManager()[t]->getRot(),CPlayer->ship); pd_manager.push_back(p); } } } if(ship_manager[i]->getShipFaction()==FACTION_PROVIAN_CONSORTIUM) { if(ship_manager[i]->cannon.primary_shoot==true) { for(unsigned int t = 0; t<ship_manager[i]->getTurretManager().size();t++) { if(rand()%ship_manager[i]->getTurretManager()[t]->getReloadTime()<SHOOTTIME*frameDeltaTime) { sound->play3D("res/sounds/weapons/photon.wav",ship_manager[i]->getPos(),false,false,false); projectile *p = new photonCannonShot(graphics, ship_manager[i]->getTurretManager()[t]->getPos(), ship_manager[i]->getTurretManager()[t]->getRot(),ship_manager[i]->ship); projectile_manager.push_back(p); } } } if(ship_manager[i]->cannon.secondary_shoot==true) { for(unsigned int t = 0; t<ship_manager[i]->getSecondaryTurretManager().size();t++) { if(rand()%ship_manager[i]->getSecondaryTurretManager()[t]->getReloadTime()<SHOOTTIME*frameDeltaTime) { sound->play3D("res/sounds/weapons/plasma.wav",ship_manager[i]->getPos(),false,false,false); projectile *p = new plasmaShot(graphics, ship_manager[i]->getSecondaryTurretManager()[t]->getPos(), ship_manager[i]->getSecondaryTurretManager()[t]->getRot(),ship_manager[i]->ship); projectile_manager.push_back(p); } } } } else { if(ship_manager[i]->cannon.primary_shoot==true) { for(unsigned int t = 0; t<ship_manager[i]->getTurretManager().size();t++) { if(rand()%ship_manager[i]->getTurretManager()[t]->getReloadTime()<SHOOTTIME*frameDeltaTime) { sound->play3D("res/sounds/weapons/rail.wav",ship_manager[i]->getPos(),false,false,false); projectile *p = new railgunShot(graphics, ship_manager[i]->getTurretManager()[t]->getPos(), ship_manager[i]->getTurretManager()[t]->getRot(),ship_manager[i]->ship); projectile_manager.push_back(p); } } } if(ship_manager[i]->cannon.secondary_shoot==true) { for(unsigned int t = 0; t<ship_manager[i]->getSecondaryTurretManager().size();t++) { if(rand()%ship_manager[i]->getSecondaryTurretManager()[t]->getReloadTime()<SHOOTTIME*frameDeltaTime) { sound->play3D("res/sounds/weapons/antimatter.wav",ship_manager[i]->getPos(),false,false,false); projectile *p = new antiMatterShot(graphics, ship_manager[i]->getSecondaryTurretManager()[t]->getPos(), ship_manager[i]->getSecondaryTurretManager()[t]->getRot(),ship_manager[i]->ship); projectile_manager.push_back(p); } } } } //if the current ship is also a station //run through stationloop function for the ship as well //stations are essential ships that cannot move //and they also let other ships dock with them //no real difference other than that if(ship_manager[i]->getIsStation()==true) { stationLoop(frameDeltaTime,sound,ship_manager[i], callback); } } else { //exploldes ship_manager[i]->alive=false; } } //Player function, see below //required loop processes for each object in the game cargoManager(frameDeltaTime,CPlayer, alertBox); aoeManager(CPlayer); fighterManager(frameDeltaTime,sound,CPlayer); pdAnimationManager(frameDeltaTime,sound); projectileAnimationManager(frameDeltaTime,sound, CPlayer); missileAnimationManager(frameDeltaTime,sound,CPlayer); planetAnimationManager(frameDeltaTime); effectAnimationManager(); destroyObjects(CPlayer); } //remember //the CSHIP CLASS doubles as a station //make sure station definitions dont let stations move though //or else that would look really fucking stupid void gameManager::stationLoop(f32 frameDeltaTime, irrklang::ISoundEngine *sound, CShip *station, ShaderCallBack *callback) { if(station->getHullPoints()>0) { //assign station a planet for resources for ship production //basically, check if there is a friendly planet within 20km, then use that planet for resources if(station->getHomePlanet()==0) { for (unsigned int l =0; l<planet_manager.size(); l++) { if(station->getPos().getDistanceFrom(planet_manager[l]->getPos())<SHIP_WARP_DISTANCE) { station->setHomePlanet(planet_manager[l]); } } } else { //if station has a home planet //begin ship production //if(station->getShipClass() == ships().HQ) //{ //only HQs can build ships //or else that would be broken if(station->getStarshipCreationTime() < graphics->getTimer()->getTime()) { const wchar_t *pname = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; if(station->getShipFaction()==FACTION_PROVIAN_CONSORTIUM) { CShip *newship = new CShip(graphics,sound,station->getPos(),station->getRot(),ships().PROV_ISHTAR_CRUISER,FACTION_PROVIAN_CONSORTIUM, pname, callback); addShip(newship); //six minute timer before creating a anew ship //TODO: change with ship station->setStarshipCreationTime(graphics->getTimer()->getTime() + 360000); } if(station->getShipFaction()==FACTION_TERRAN_FEDERATION) { const wchar_t *tname = ships().terran_ship_name[rand()%ships().terran_ship_name.size()]; CShip *newship = new CShip(graphics,sound,station->getPos(),station->getRot(),ships().TERR_PRAETORIAN_CRUISER,FACTION_TERRAN_FEDERATION,tname, callback); addShip(newship); station->setStarshipCreationTime(graphics->getTimer()->getTime() + 360000); } } //} } //if there are ships around launch fighters if(getClosestEnemyShip(station)!=0) { if(station->getNumFighters()>0) { //make timer for fighter creation if(station->getFighterCreationTime() < graphics->getTimer()->getTime()) { if(station->getShipFaction()==FACTION_TERRAN_FEDERATION) { vector3df pos = station->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,station->getPos(),station->getRot(),fighters().TERR_DRAGONFLY,station->getShipFaction(),station->ship); f->setTarget(getClosestEnemyShip(station)); addFighter(f); station->modNumFighters(-1); station->setFighterCreationTime(graphics->getTimer()->getTime()+1000); } if(station->getShipFaction()==FACTION_PROVIAN_CONSORTIUM) { vector3df pos = station->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,station->getPos(),station->getRot(),fighters().PROV_RAPTOR,station->getShipFaction(),station->ship); f->setTarget(getClosestEnemyShip(station)); addFighter(f); station->modNumFighters(-1); station->setFighterCreationTime(graphics->getTimer()->getTime()+1000); } } } } //if under attack launch distress } } //--------------------------------------------------------------------------------------------------------------------- //fighter run code void gameManager::fighterManager(f32 frameDeltaTime, irrklang::ISoundEngine *sound, Player *CPlayer) { //similar to how the main loop manages ships //this manages fighters //fighters thankfully, are much dumber for(unsigned int i=0; i<fighter_manager.size(); i++) { //ensures no crashes occur if(fighter_manager[i]->getHullPoints()>0) { //only fight if still have fuel vector3df pos = fighter_manager[i]->getPos(); fighter_manager[i]->AIRun(frameDeltaTime); //MAX SPEED! fighter_manager[i]->setVelocity(fighter_manager[i]->getMaxVelocity()); //theres not really a good way i could make the fighters that are owned by the player respond to its command //and make the player and fighter control sync //so i have to do some ugly functions that i know will work //but look out of place and are in bad locations if(fighter_manager[i]->getFuel()<graphics->getTimer()->getTime()) fighter_manager[i]->setReturnHome(true); if(fighter_manager[i]->getReturnHome()!=true) { //fighting other fighters is a bigger priority if(fighter_manager[i]->getFighterTarget()==0) { if(fighter_manager[i]->getFighterFaction()==FACTION_PROVIAN_CONSORTIUM) { if(pos.getDistanceFrom(CPlayer->getPos())<5000) { //attack player fighter_manager[i]->moveToPoint(CPlayer->getPos()); if(pos.getDistanceFrom(CPlayer->getPos())<1000) { fighter_manager[i]->fireMissile(); fighter_manager[i]->moveAwayFromPoint(CPlayer->getPos()); } } } if(getClosestEnemyFighter(fighter_manager[i])!=0) { //shootin tiempo fighter_manager[i]->setFighterTarget(getClosestEnemyFighter(fighter_manager[i])); } if(fighter_manager[i]->getTarget()==0) { //if no target patroll around n stuff fighter_manager[i]->patrol(fighter_manager[i]->getHomeBase()->getPosition()); if(getClosestEnemyShipFighter(fighter_manager[i])!=0) { fighter_manager[i]->setTarget(getClosestEnemyShipFighter(fighter_manager[i])); } } else { //protect from crashes if(fighter_manager[i]->getTarget()->alive==true) { //attack //if fighter too far aim at target if(pos.getDistanceFrom(CPlayer->getPos())<pos.getDistanceFrom(fighter_manager[i]->getTarget()->getPos())) { if(fighter_manager[i]->getFighterFaction()==FACTION_PROVIAN_CONSORTIUM) { if(pos.getDistanceFrom(CPlayer->getPos())<5000) { //attack player fighter_manager[i]->moveToPoint(CPlayer->getPos()); if(pos.getDistanceFrom(CPlayer->getPos())<1000) { fighter_manager[i]->fireMissile(); fighter_manager[i]->moveAwayFromPoint(CPlayer->getPos()); } } } } else { if(pos.getDistanceFrom(fighter_manager[i]->getTarget()->getPos())>FIGHTER_CLOSE_RANGE) { fighter_manager[i]->moveToPoint(fighter_manager[i]->getTarget()->getPos()); } else { //shoot missile and then bounce fighter_manager[i]->fireMissile(); fighter_manager[i]->moveAwayFromPoint(fighter_manager[i]->getTarget()->getPos()); if(pos.getDistanceFrom(fighter_manager[i]->getTarget()->getPos())>FIGHTER_FAR_RANGE) { //break off fighter_manager[i]->setTarget(0); } } } //missile launch code if(fighter_manager[i]->cannon.missile==true) { if(pos.getDistanceFrom(CPlayer->getPos()) < 1000) { missile *m = new missile(graphics,pos,fighter_manager[i]->getRot(),CPlayer->ship); missile_manager.push_back(m); } else { missile *m = new missile(graphics,pos,fighter_manager[i]->getRot(),fighter_manager[i]->getTarget()->ship); missile_manager.push_back(m); } } } else { //target dead fighter_manager[i]->setTarget(0); } } } else { //dogfight fighter_manager[i]->setTarget(0); //huge crashing problem with fighters //its really annoying if(!fighter_manager[i]->getFighterTarget()->fighter_model) fighter_manager[i]->setFighterTarget(0); else { if(fighter_manager[i]->getFighterTarget()->getHullPoints()>0 && fighter_manager[i]->getFighterTarget()->alive!=false) { if(pos.getDistanceFrom(fighter_manager[i]->getFighterTarget()->getPos())>500) { fighter_manager[i]->moveToPoint(fighter_manager[i]->getFighterTarget()->getPos()); } else { fighter_manager[i]->shoot(); fighter_manager[i]->moveAwayFromPoint(fighter_manager[i]->getFighterTarget()->getPos()); } if(fighter_manager[i]->cannon.cannon==true) { //projectile *p = new gatlingBullet(graphics,fighter_manager[i]->getPos(),fighter_manager[i]->getRot(),0); //pd_manager.push_back(p); if(rand()%3<2) fighter_manager[i]->getFighterTarget()->damageFighter(4); } } else fighter_manager[i]->setFighterTarget(0); } } } else { //return home //test this out later //could cause problems //if(fighter_manager[i]->getHomeBase()!=0) { fighter_manager[i]->moveToPoint(fighter_manager[i]->getHomeBase()->getPosition()); if(pos.getDistanceFrom(fighter_manager[i]->getHomeBase()->getPosition()) < FIGHTER_DOCK_RANGE) { //dock if(CPlayer->ship==fighter_manager[i]->getHomeBase()) { CPlayer->addFighterCount(1); fighter_manager[i]->alive = false; //fighter_manager[i]->drop(); //fighter_manager.erase(fighter_manager.begin()+i); } else { for(int n=0; n<ship_manager.size(); n++) { if(ship_manager[n]->ship==fighter_manager[i]->getHomeBase()) { ship_manager[n]->modNumFighters(1); fighter_manager[i]->alive = false; //fighter_manager[i]->drop(); //fighter_manager.erase(fighter_manager.begin()+i); } } } } } } } else { //explode //smallexplosion *e = new smallexplosion(graphics,sound,fighter_manager[i]->getPos()); //effect_manager.push_back(e); fighter_manager[i]->alive = false; //fighter_manager[i]->drop(); //fighter_manager.erase(fighter_manager.begin()+i); } } } //------------------------------------------------------------------------------------------- //projectileAnimationManager //This function is designed in order to update each projectile created by the game //BEGIN FUNC void gameManager::projectileAnimationManager(f32 frameDeltaTime,irrklang::ISoundEngine *sound, Player *CPlayer) { //This function scans through each projectile and runs them //irrlicht collision detection isnt used //I do not understand it //So, heres my ghetto collision detection //12/4 currently the collision detection kills fps by about 30 //get new collision detection //TODO: properly integrate irrlicht/bullet collision detection for(unsigned int i=0;i<projectile_manager.size();++i) { core::vector3df dist = (projectile_manager[i]->bullet->getPosition()); bool tmp; tmp = false; if(projectile_manager[i]->checkRange()<projectile_manager[i]->getRange()) { projectile_manager[i]->projRun(frameDeltaTime); //Make sure the projectile created by the player doesn't destroy the players own ship if(projectile_manager[i]->getShip()!=CPlayer->ship) { if(CPlayer->ship->getTransformedBoundingBox().isPointInside(projectile_manager[i]->bullet->getPosition())) { irrklang::ISound *impactsound = sound->play3D("res/sounds/hit.wav",CPlayer->getPos(),false,false,false); CPlayer->damagePlayer(projectile_manager[i]->damage); impact *imp = new impact(graphics,sound,dist); effect_manager.push_back(imp); tmp = true; } } //attempt to make brute force approach not so brute force //double axis aligned collision checking std::vector<CShip*> speed; speed = ship_manager; for(unsigned int l=0; l<speed.size();l++) { bool tmp=false; if(speed[l]->getPos().X > projectile_manager[i]->bullet->getPosition().X + 600) { tmp=true; } if(speed[l]->getPos().X < projectile_manager[i]->bullet->getPosition().X - 600) { tmp=true; } if(speed[l]->getPos().Y > projectile_manager[i]->bullet->getPosition().Y + 600) { tmp=true; } if(speed[l]->getPos().Y < projectile_manager[i]->bullet->getPosition().Y - 600) { tmp=true; } if(tmp==true) speed.erase(speed.begin()+l); } for(unsigned int l=0;l<speed.size();l++) { //Make sure AI doesn't destroy itself if(speed[l]->ship!=projectile_manager[i]->getShip()) { if(speed[l]->getHullPoints()>0) { if(speed[l]->ship->getTransformedBoundingBox().isPointInside(projectile_manager[i]->bullet->getPosition())) { irrklang::ISound *impactsound = sound->play3D("res/sounds/hit.wav",speed[l]->getPos(),false,false,false); speed[l]->damageShip(projectile_manager[i]->damage); //create impact impact *imp = new impact(graphics,sound,dist); effect_manager.push_back(imp); tmp = true; } } } } //the tmp bool MUST be used, or else the program can crash //If it is not used, then projectile_manager might call a projectile object that was recently deleted //giving an out of range error if(tmp==true) { //delete the projectile if its hit something projectile_manager[i]->drop(); projectile_manager.erase(projectile_manager.begin()+i); } } else { //delete projectiles that have exceeded their maximum range projectile_manager[i]->drop(); projectile_manager.erase(projectile_manager.begin()+i); } } } //END FUNC //----------------------------------------------------------------------------------------------- //for fighters void gameManager::pdAnimationManager(f32 frameDeltaTime, irrklang::ISoundEngine *sound) { for(unsigned int i=0;i<pd_manager.size();i++) { core::vector3df dist = (pd_manager[i]->bullet->getPosition()); bool tmp; tmp = false; if(pd_manager[i]->checkRange() < pd_manager[i]->getRange()) { pd_manager[i]->projRun(frameDeltaTime); for(int l=0; l<fighter_manager.size();l++) { if(fighter_manager[l]->getHullPoints()>0) { if(dist.getDistanceFrom(fighter_manager[l]->getPos())<20) { //damage irrklang::ISound *impactsound = sound->play3D("res/sounds/hit.wav",fighter_manager[l]->getPos(),false,false,false); fighter_manager[l]->damageFighter(pd_manager[i]->damage); //create impact impact *imp = new impact(graphics,sound,dist); effect_manager.push_back(imp); tmp = true; } } } for(int l = 0; l<missile_manager.size();l++) { if(missile_manager[l]->getHealth()>0) { if(dist.getDistanceFrom(missile_manager[l]->getPos())<50) { missile_manager[l]->damage(pd_manager[i]->damage); tmp=true; } } } if(tmp==true) { //delete the projectile if its hit something pd_manager[i]->drop(); pd_manager.erase(pd_manager.begin()+i); } } else { pd_manager[i]->drop(); pd_manager.erase(pd_manager.begin()+i); } } } //END FUNCT //---------------------------------------------------------------------------------------------------------- void gameManager::missileAnimationManager(f32 frameDeltaTime, irrklang::ISoundEngine *sound, Player *CPlayer) { for(unsigned int i=0 ;i<missile_manager.size();i++) { //missiles only impact the ship they're shooting at //for speed issues vector3df pos = missile_manager[i]->getPos(); bool tmp; tmp=false; if(missile_manager[i]->checkRange()<missile_manager[i]->getRange()) { if(missile_manager[i]->getHealth()>0) { missile_manager[i]->loop(frameDeltaTime); //explode at certain range if(missile_manager[i]->getDistFromTarget()<50) { //create aoe cause missiles are like that smallexplosion *e = new smallexplosion(graphics,sound,pos); effect_manager.push_back(e); areaofeffect *a = new areaofeffect(graphics,pos,400,400,10); aoe_manager.push_back(a); tmp=true; } } else { smallexplosion *e = new smallexplosion(graphics,sound,pos); effect_manager.push_back(e); tmp=true; } if(tmp==true) { missile_manager[i]->drop(); missile_manager.erase(missile_manager.begin()+i); } } else { //delete missile_manager[i]->drop(); missile_manager.erase(missile_manager.begin()+i); } } } //--------------------------------------------------------------------------------------- void gameManager::aoeManager(Player *CPlayer) { for(unsigned int i=0; i<aoe_manager.size();i++) { vector3df pos = aoe_manager[i]->getPos(); for(unsigned int l=0; l<ship_manager.size();l++) { //inside radius if(ship_manager[l]->getHullPoints()>0) { if(pos.getDistanceFrom(ship_manager[l]->getPos())<aoe_manager[i]->getRadius()) { int dist = pos.getDistanceFrom(ship_manager[l]->getPos()); int max_d = aoe_manager[i]->getMaxDamage()/2 - aoe_manager[i]->getMaxDamage()/dist; ship_manager[l]->damageShip(max_d); } } } if(pos.getDistanceFrom(CPlayer->getPos())< aoe_manager[i]->getRadius()) { int dist = pos.getDistanceFrom(CPlayer->getPos()); int max_d = aoe_manager[i]->getMaxDamage()/dist; CPlayer->damagePlayer(max_d); } //delete the aoe after its done its dirty deeds aoe_manager[i]->drop(); aoe_manager.erase(aoe_manager.begin()+i); } } //-------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------- //rotates the cargo void gameManager::cargoManager(f32 frameDeltaTime, Player *CPlayer, CAlertBox *alertBox) { for(unsigned int i=0; i<cargo_manager.size();i++) { cargo_manager[i]->loop(frameDeltaTime); //if player is close enough //pick it up if(CPlayer->getPos().getDistanceFrom(cargo_manager[i]->getPos())<CARGODISTANCE) { std::vector<item*> temp = cargo_manager[i]->getInventory(); for(unsigned int l=0; l<temp.size();l++) { CPlayer->addItemToCargo(temp[l]); } //player gets random amount of cash int cash = rand()%600; CPlayer->setMoney(CPlayer->getMoney()+cash); alertBox->addText(L"Cargo Loaded", NORMAL); //then delete cargo_manager[i]->drop(); cargo_manager.erase(cargo_manager.begin()+i); } } } //----------------------------------------------------------------------------------------- //show planet targetting reticules void gameManager::showPlanetTargets(bool ishidden) { for (unsigned int i = 0; i<planet_manager.size(); i++) { planet_manager[i]->setArrayVisible(ishidden); } } //ditto for ships void gameManager::showShipTargets(bool ishidden) { showShips = ishidden; } void gameManager::planetAnimationManager(f32 frameDeltaTime) { //Rotates the planets //minor function for(unsigned int i = 0;i<planet_manager.size();i++) { //corrona faces cam core::vector3df diff = planet_manager[i]->model->getPosition() - graphics->getSceneManager()->getActiveCamera()->getPosition(); core::vector3df angle = diff.getHorizontalAngle(); planet_manager[i]->rotate(frameDeltaTime); if(planet_manager[i]->getPlanetType()->corona==true) planet_manager[i]->corona->setRotation(angle); //hide plant clouds when camera is far away if(planet_manager[i]->getPos().getDistanceFrom(graphics->getSceneManager()->getActiveCamera()->getPosition())>CAMERA_HIDE_DISTANCE) planet_manager[i]->setCloudsVisible(false); else planet_manager[i]->setCloudsVisible(true); } } //this function simply runs through each effect void gameManager::effectAnimationManager() { for(unsigned int i=0; i <effect_manager.size();i++) { if(effect_manager[i]->getEnd()==false) { effect_manager[i]->loop(); } else { effect_manager[i]->drop(); effect_manager.erase(effect_manager.begin()+i); } } } //----------------------------------------------------------------------------------------------------------- //function for playershoot //called from the gameloop //all the shooting management is done in this file because all the other ships are managed in this file //so shooting has to be done in the same file void gameManager::playerShoot(irr::IrrlichtDevice *graphics,Player* CPlayer, irrklang::ISoundEngine *sound, CShip *player_target, f32 frameDeltaTime, int subsys) { //The same thing that applies to ships applies to the player //However, the Player projectiles must also come from the turret //and shoot different projectiles depending on what type of turret the player has installed //turn off broadsides only for demo purposes if(CPlayer->cannonFired.primary==true) { for(unsigned int i=0;i<CPlayer->turret_manager.size();i++) { //if(angleY + 40 < CPlayer->getRot().Y || angleY-40 > CPlayer->getRot().Y) //{ //most turrets can only fire broadsides //cause broadsiding is cool as shit //Scan through the turrets that the player has /* float x = CPlayer->turret_manager[i]->getPos().X - CPlayer->getPos().X; float y = CPlayer->turret_manager[i]->getPos().Y - CPlayer->getPos().Y; float z = CPlayer->turret_manager[i]->getPos().Z - CPlayer->getPos().Z; float angleY = std::atan2(x,z)*180/3.14; */ if(rand()%CPlayer->turret_manager[i]->getReloadTime()<SHOOTTIME*frameDeltaTime) { if(CPlayer->getPrimaryTurret()->name==items().PRI_RAIL->name) { sound->play3D("res/sounds/weapons/rail.wav",CPlayer->turret_manager[i]->getPos(),false,false,false); projectile *p = new railgunShot(graphics, CPlayer->turret_manager[i]->getFirePos(), CPlayer->turret_manager[i]->getRot(),CPlayer->ship); projectile_manager.push_back(p); } if(CPlayer->getPrimaryTurret()->name==items().PRI_PHOTON->name) { sound->play3D("res/sounds/weapons/photon.wav",CPlayer->turret_manager[i]->getPos(),false,false,false); projectile *p = new photonCannonShot(graphics, CPlayer->turret_manager[i]->getFirePos(), CPlayer->turret_manager[i]->getRot(),CPlayer->ship); projectile_manager.push_back(p); } muzzleflash *m = new muzzleflash(graphics,sound,CPlayer->turret_manager[i]->getFirePos(), CPlayer->turret_manager[i]->getRot(), CPlayer->turret_manager[i]->getBone()); effect_manager.push_back(m); if(player_target!=0) { if(rand()%300<3) { if(player_target->getShieldPoints()<1) { if(subsys==0) { player_target->subsystem.engine-=rand()%10; } if(subsys==1) { player_target->subsystem.warpdrive-=rand()%10; } if(subsys==2) { player_target->subsystem.primary_weapons-=rand()%10; } if(subsys==3) { player_target->subsystem.secondary_weapons-=rand()%10; } if(subsys==4) { player_target->subsystem.light_weapons-=rand()%10; } } } } } //} } } if(CPlayer->cannonFired.secondary == true) { //Scan through the turrets that the player has /* float x = player_target->getPos().X - CPlayer->getPos().X; float y = player_target->getPos().Y - CPlayer->getPos().Y; float z = player_target->getPos().Z - CPlayer->getPos().Z; float angleY = std::atan2(x,z)*180/3.14; */ for(unsigned int i = 0; i< CPlayer->secondary_turret_manager.size();i++) { if(rand()%CPlayer->secondary_turret_manager[i]->getReloadTime()<SHOOTTIME*frameDeltaTime) { //if(angleY + 40 < CPlayer->getRot().Y || angleY-40 > CPlayer->getRot().Y) //{ sound->play3D("res/sounds/weapons/antimatter.wav",CPlayer->secondary_turret_manager[i]->getPos(),false,false,false); projectile *p = new antiMatterShot(graphics, CPlayer->secondary_turret_manager[i]->getFirePos(), CPlayer->secondary_turret_manager[i]->getRot(),CPlayer->ship); projectile_manager.push_back(p); muzzleflash *m = new muzzleflash(graphics,sound,CPlayer->secondary_turret_manager[i]->getFirePos(), CPlayer->secondary_turret_manager[i]->getRot(), CPlayer->secondary_turret_manager[i]->getBone()); effect_manager.push_back(m); //} } } } if(CPlayer->cannonFired.light == true) { for(unsigned int i=0; i<CPlayer->light_turret_manager.size();i++) { if(rand()%CPlayer->light_turret_manager[i]->getReloadTime()<SHOOTTIME*frameDeltaTime) { sound->play3D("res/sounds/weapons/gatling.wav",CPlayer->light_turret_manager[i]->getPos(),false,false,false); projectile *p = new gatlingBullet(graphics, CPlayer->light_turret_manager[i]->getFirePos(), CPlayer->light_turret_manager[i]->getRot(),CPlayer->ship); pd_manager.push_back(p); muzzleflash *m = new muzzleflash(graphics,sound,CPlayer->light_turret_manager[i]->getFirePos(), CPlayer->light_turret_manager[i]->getRot(), CPlayer->light_turret_manager[i]->getBone()); effect_manager.push_back(m); } } } //BUG: point defense turrets never stop shooting int tmp=0; for(unsigned int i=0;i<fighter_manager.size();i++) { if(fighter_manager[i]->getHostileToPlayer()==true) { if(CPlayer->getPos().getDistanceFrom(fighter_manager[i]->getPos())<2000) { CPlayer->aimPd(fighter_manager[i]->getPos(),frameDeltaTime); CPlayer->shootPD(); tmp+=1; } //else //CPlayer->resetPD(); } } if(tmp==0) CPlayer->resetPD(); } //end funct //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------- //destroyObjects() //cleaner function //call this last in order to make everything way way more clean //should no longer have reference errors with this function void gameManager::destroyObjects(Player *CPlayer) { for(int i=0;i<ship_manager.size();i++) { //if no longer alive //delete the object if(ship_manager[i]->alive!=true) { explosion* e = new explosion(graphics,sound,ship_manager[i]->getPos()); effect_manager.push_back(e); irrklang::ISound *s = sound->play3D("res/sounds/reactor_explo.wav",ship_manager[i]->getPos(),false,false,true); s->setMinDistance(5000.f); s->drop(); cargo *c = new cargo(graphics,ship_manager[i]->getPos()); cargo_manager.push_back(c); ship_manager[i]->drop(); ship_manager.erase(ship_manager.begin()+i); } } for(int i=0;i< fighter_manager.size(); i++) { if(fighter_manager[i]->alive!=true) { smallexplosion *e = new smallexplosion(graphics,sound,fighter_manager[i]->getPos()); irrklang::ISound *impactsound = sound->play3D("res/sounds/hit.wav",fighter_manager[i]->getPos(),false,false,false); effect_manager.push_back(e); fighter_manager[i]->drop(); fighter_manager.erase(fighter_manager.begin()+i); } } // i need this, but i dont know why the hell i put it here //creates explosion on player death if(CPlayer->getHull()<1) { if(playerDead==false) { explosion* e = new explosion(graphics,sound,CPlayer->getPos()); effect_manager.push_back(e); playerDead=true; } } } //end funct // destroyObjects() //------------------------------------------------------------------- //----------------------------------------------------------- //IMPORTANT MISC FUNCTIONS //legacy code, probably won't be used void gameManager::addProjectile(projectile* shot) { projectile_manager.push_back(shot); } //used by the gameloop object to add ships to the ship manager void gameManager::addShip(CShip* ship) { ship_manager.push_back(ship); } void gameManager::addFighter(fighter* f) { fighter_manager.push_back(f); } //legacy void gameManager::addStation(CShip* station) { ship_manager.push_back(station); } void gameManager::addPlanet(planet* p) { planet_manager.push_back(p); } CShip* gameManager::getTarget() { //Some pretty basic code here //Just scan through all the ships inside the ship_manager array //and then get the position of the mouse //get the distance between the target icon on the ship and the mouse using trig //then if the mouse is closer than 32 pixels to the target icon thing //select the ship then return it to the player_target variable inside the gameloop object vector2d<int> t; t.X = receiver->mouseX(); t.Y = receiver->mouseY(); for(unsigned int i=0;i<ship_manager.size();i++) { //ensure player can see the targetting rectangle if(ship_manager[i]->getWithinRadarRange()==true) { vector2d<int> pos; pos = ship_manager[i]->getArrayPos(); const float x = t.X-pos.X; const float y = t.Y-pos.Y; float dist = sqrt(x*x + y*y); if(dist<SELECTDISTANCE) { return ship_manager[i]; } } } //Makes sure game doesn't crash return 0; } planet* gameManager::getTargetPlanet() { //similiar to getTarget() function but for planets vector2d<int> t; t.X = receiver->mouseX(); t.Y = receiver->mouseY(); for( unsigned int i = 0; i < planet_manager.size(); i++) { vector2d<int> pos; pos = planet_manager[i]->getArrayPos(); const float x = t.X - pos.X; const float y = t.Y - pos.Y; float dist = sqrt( x*x + y*y); if(dist<SELECTDISTANCE) { return planet_manager[i]; } } return 0; } //legacy //delete later CShip *gameManager::getClosestStation(Player *CPlayer) { for(unsigned int i=0;i<station_manager.size();i++) { int dist = station_manager[i]->getDistToPoint(CPlayer->getPos()); if(dist<1000) { return station_manager[i]; } } return 0; } //--------------------------------------------------------------------------------------------------------------------- //SAVE and LOAD FUNCTIONS START HERE //--------------------------------------------------------------------------------------------------------------------- //converts a float to a string stringw gameManager::floatToString(float num) { stringw t(L""); t+=num; return t; } //same as above but with int //so save files dont get cluttered with useless decimals //template blah blah blah shut up stringw gameManager::intToString(int num) { stringw t(L""); t+=num; return t; } //save all the ships into the xml file void gameManager::saveObjects(io::IXMLWriter *writer) { //save number of ships //for easier loading core::array<stringw> value; value.push_back(L"num"); core::array<stringw> num; num.push_back(intToString(ship_manager.size())); writer->writeElement(L"shipStats",true,value,num); //create a different element //for each ship //each element is simply labelled with a number for (unsigned int i = 0; i < ship_manager.size(); i++) { core::array<stringw> attributes; core::array<stringw> values; attributes.push_back(L"faction"); values.push_back(intToString(ship_manager[i]->getShipFaction())); attributes.push_back(L"name"); values.push_back(ship_manager[i]->getName()); attributes.push_back(L"ship"); values.push_back(intToString(ship_manager[i]->getShipClass()->index)); attributes.push_back(L"hullPoints"); values.push_back(floatToString(ship_manager[i]->getHullPoints())); attributes.push_back(L"shieldPoints"); values.push_back(floatToString(ship_manager[i]->getShieldPoints())); attributes.push_back(L"armorPoints"); values.push_back(floatToString(ship_manager[i]->getArmorPoints())); attributes.push_back(L"posX"); values.push_back(floatToString(ship_manager[i]->getPos().X)); attributes.push_back(L"posY"); values.push_back(floatToString(ship_manager[i]->getPos().Y)); attributes.push_back(L"posZ"); values.push_back(floatToString(ship_manager[i]->getPos().Z)); attributes.push_back(L"rotX"); values.push_back(floatToString(ship_manager[i]->getRot().X)); attributes.push_back(L"rotY"); values.push_back(floatToString(ship_manager[i]->getRot().Y)); attributes.push_back(L"rotZ"); values.push_back(floatToString(ship_manager[i]->getRot().Z)); attributes.push_back(L"velocity"); values.push_back(floatToString(ship_manager[i]->getVelocity())); attributes.push_back(L"id"); values.push_back(ship_manager[i]->getID()); attributes.push_back(L"numFighters"); values.push_back(intToString(ship_manager[i]->getNumFighters())); attributes.push_back(L"shipCreationTime"); values.push_back(intToString(ship_manager[i]->getStarshipCreationTime())); //write into element shipStats writer->writeElement(intToString(i).c_str(),true,attributes,values); } writer->writeClosingTag(L"shipStats"); //now save fighters core::array<stringw> fvalue; fvalue.push_back(L"num"); core::array<stringw> fnum; fnum.push_back(intToString(fighter_manager.size())); writer->writeElement(L"fighterStats",true,fvalue,fnum); for(unsigned int i=0; i<fighter_manager.size();i++) { core::array<stringw> attributes; core::array<stringw> values; attributes.push_back(L"faction"); values.push_back(intToString(fighter_manager[i]->getFighterFaction())); //attributes.push_back(L"name"); //values.push_back(fighter_manager[i]->getName()); attributes.push_back(L"fighter"); values.push_back(intToString(fighter_manager[i]->getFighterClass()->index)); attributes.push_back(L"hullPoints"); values.push_back(floatToString(fighter_manager[i]->getHullPoints())); attributes.push_back(L"posX"); values.push_back(floatToString(fighter_manager[i]->getPos().X)); attributes.push_back(L"posY"); values.push_back(floatToString(fighter_manager[i]->getPos().Y)); attributes.push_back(L"posZ"); values.push_back(floatToString(fighter_manager[i]->getPos().Z)); attributes.push_back(L"rotX"); values.push_back(floatToString(fighter_manager[i]->getRot().X)); attributes.push_back(L"rotY"); values.push_back(floatToString(fighter_manager[i]->getRot().Y)); attributes.push_back(L"rotZ"); values.push_back(floatToString(fighter_manager[i]->getRot().Z)); attributes.push_back(L"velocity"); values.push_back(floatToString(fighter_manager[i]->getVelocity())); //homebase attributes.push_back(L"homebase"); for(int n=0; n<ship_manager.size(); n++) { if(ship_manager[n]->ship == fighter_manager[i]->getHomeBase()) { values.push_back(ship_manager[n]->getID()); } } //write into element shipStats writer->writeElement(intToString(i).c_str(),true,attributes,values); } writer->writeClosingTag(L"fighterStats"); //save loot core::array<stringw> cvalue; cvalue.push_back(L"num"); core::array<stringw> cnum; cnum.push_back(intToString(cargo_manager.size())); writer->writeElement(L"cargoStats",true,cvalue,cnum); for(int i=0; i<cargo_manager.size();i++) { core::array<stringw> attributes; core::array<stringw> values; attributes.push_back(L"posX"); values.push_back(floatToString(cargo_manager[i]->getPos().X)); attributes.push_back(L"posY"); values.push_back(floatToString(cargo_manager[i]->getPos().Y)); attributes.push_back(L"posZ"); values.push_back(floatToString(cargo_manager[i]->getPos().Z)); } } //load attributes from xml file void gameManager::loadShips(io::IXMLReader *reader, int numobjects, ShaderCallBack *callback) { //for num of ships inside of file for(u32 i = 0;i<numobjects;i++) { if(core::stringw(intToString(i)).equals_ignore_case(reader->getNodeName())) { //create ship //and set ship stats ship_faction faction; ship_base *sclass; int t = reader->getAttributeValueAsInt(L"faction"); if(t==0) { faction = FACTION_TERRAN_FEDERATION; } if(t==1) { faction = FACTION_PROVIAN_CONSORTIUM; } if(t==2) { faction = FACTION_PIRATE; } if(t==3) { faction = FACTION_NEUTRAL; } int s = reader->getAttributeValueAsInt(L"ship"); for(unsigned int l=0; l<ships().ship_list.size();l++) { if(ships().ship_list[l]->index==s) { sclass = ships().ship_list[l]; } } //set the position and rotation vector3df pos; vector3df rot; pos.X = reader->getAttributeValueAsFloat(L"posX"); pos.Y = reader->getAttributeValueAsFloat(L"posY"); pos.Z = reader->getAttributeValueAsFloat(L"posZ"); rot.X = reader->getAttributeValueAsFloat(L"rotX"); rot.Y = reader->getAttributeValueAsFloat(L"rotY"); rot.Z = reader->getAttributeValueAsFloat(L"rotZ"); //ship creation time int ship_creation = reader->getAttributeValueAsInt(L"shipCreationTime"); //load name stringw str(L""); str += reader->getAttributeValue(L"name"); int size =str.size(); wchar_t *buffer; buffer = new wchar_t[size+1]; //re encode the string onto the new space for(int n=0;n<size;n++) { buffer[n]=str[n]; } //termination character buffer[size]='\0'; //load id stringw id(L""); id += reader->getAttributeValue(L"id"); int size_id =id.size(); wchar_t *buffer_id; buffer_id = new wchar_t[size_id+1]; //re encode the string onto the new space for(int n=0;n<size_id;n++) { buffer_id[n]=id[n]; } //termination character buffer_id[size_id]='\0'; CShip *newship = new CShip(graphics,sound,pos,rot,sclass,faction,buffer,callback); newship->setStarshipCreationTime(ship_creation); newship->setID(buffer_id); newship->setHullPoints(reader->getAttributeValueAsInt(L"hullPoints")); newship->setShieldPoints(reader->getAttributeValueAsInt(L"shieldPoints")); newship->setArmorPoints(reader->getAttributeValueAsInt(L"armorPoints")); int fighters = reader->getAttributeValueAsInt(L"numFighters"); newship->setNumFighters(fighters); addShip(newship); //newship->setVelocity(reader->getAttributeValueAsFloat(L"velocity")); } } } void gameManager::loadFighters(io::IXMLReader *reader, int numobjects) { for(u32 i=0; i<numobjects; i++) { if(core::stringw(intToString(i)).equals_ignore_case(reader->getNodeName())) { ship_faction faction; fighter_base *fclass; int t = reader->getAttributeValueAsInt(L"faction"); if(t==0) { faction = FACTION_TERRAN_FEDERATION; } if(t==1) { faction = FACTION_PROVIAN_CONSORTIUM; } if(t==2) { faction = FACTION_PIRATE; } if(t==3) { faction = FACTION_NEUTRAL; } int s = reader->getAttributeValueAsInt(L"fighter"); for(u32 l=0; l<fighters().fighter_list.size(); l++) { if(fighters().fighter_list[l]->index==s) { fclass = fighters().fighter_list[l]; } } //set the position and rotation vector3df pos; vector3df rot; pos.X = reader->getAttributeValueAsFloat(L"posX"); pos.Y = reader->getAttributeValueAsFloat(L"posY"); pos.Z = reader->getAttributeValueAsFloat(L"posZ"); rot.X = reader->getAttributeValueAsFloat(L"rotX"); rot.Y = reader->getAttributeValueAsFloat(L"rotY"); rot.Z = reader->getAttributeValueAsFloat(L"rotZ"); //load name stringw str(L""); str += reader->getAttributeValue(L"name"); int size =str.size(); wchar_t *buffer; buffer = new wchar_t[size+1]; //re encode the string onto the new space for(int n=0;n<size;n++) { buffer[n]=str[n]; } //termination character buffer[size]='\0'; fighter *f = new fighter(graphics,sound,pos,rot,fclass,faction,0,buffer); //load homebase stringw id(L""); id += reader->getAttributeValue(L"homebase"); int size_id =id.size(); wchar_t *buffer_id; buffer_id = new wchar_t[size_id+1]; //re encode the string onto the new space for(int n=0;n<size_id;n++) { buffer_id[n]=id[n]; } //termination character buffer_id[size_id]='\0'; if(buffer_id==L"Player") { //f->setHomeBase(CPlayer->ship); } for(int n = 0; n<ship_manager.size(); n++) { if(ship_manager[n]->getID()==buffer_id) { f->setHomeBase(ship_manager[n]->ship); } } } } }
#ifndef CTICKTIMER_H #define CTICKTIMER_H #include <Windows.h> #include <QtGlobal> #include <QDebug> class CTickTimer { public: CTickTimer() { QueryPerformanceFrequency(&_perfFreq); } void Start() { QueryPerformanceCounter(&_perfStart); } bool Timeout(qint64 ms) { LARGE_INTEGER perfNow; QueryPerformanceCounter(&perfNow); return ((((perfNow.QuadPart - _perfStart.QuadPart) * 1000) / _perfFreq.QuadPart) > ms); } bool TimeoutMicro(qint64 us) { LARGE_INTEGER perfNow; QueryPerformanceCounter(&perfNow); return ((((perfNow.QuadPart - _perfStart.QuadPart) * 1000000) / _perfFreq.QuadPart) > us); } private: LARGE_INTEGER _perfFreq; LARGE_INTEGER _perfStart; }; #endif // CTICKTIMER_H
#ifndef CALGROUPSMODEL_H #define CALGROUPSMODEL_H #include "VnaModel.h" #include <QAbstractListModel> namespace RsaToolbox { class CalGroupsModel; typedef QSharedPointer<CalGroupsModel> SharedCalGroupsModel; class CalGroupsModel : public QAbstractListModel { Q_OBJECT public: explicit CalGroupsModel(QObject *parent = 0); static const int COLUMNS = 1; void setVnaModel(VnaModel *model); VnaModel *vnaModel() const; int rowCount(const QModelIndex &parent) const; int columnCount(const QModelIndex &parent) const; Qt::ItemFlags flags(const QModelIndex &index) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; QModelIndex index(int row, int column, const QModelIndex &parent) const; QModelIndex parent(const QModelIndex &child) const; QVariant data(const QModelIndex &index, int role) const; signals: public slots: void reset(); private slots: void vnaDataChanged(QModelIndex topLeft, QModelIndex bottomRight); void vnaModelReset(); private: uint _calGroups; bool isMissingRef() const; bool isVnaConnected() const; RsaToolbox::Vna *_vna; VnaModel *_vnaModel; }; } // RsaToolbox #endif // CALGROUPSMODEL_H
/********************************************************************************************************************** * @file rambler/Connection/TCPStream_Winsock2.hpp * @date 2014-07-18 * @brief <# Brief Description #> * @details <# Detailed Description #> **********************************************************************************************************************/ #pragma once #include "rambler/Stream/TCPStream.hpp" #include <thread> #include <winsock2.h> #include <ws2tcpip.h> #define SECURITY_WIN32 #include <security.h> #include <schnlsp.h> namespace rambler { namespace Stream { /** * A Winsock2 based implementation of TCP connection * @author Omar Stefan Evans * @date 2014-07-18 */ class TCPStream_Winsock2 : public TCPStream { public: /** * Constructs an object representing a TCP connection to a host at the given domain for a particular service. * @author Omar Stefan Evans * @date 2014-07-18 * @param domainName the domain name * @param serviceName either a service name for a SRV lookup or a port number */ TCPStream_Winsock2(String domainName, String serviceName); /** * Destructor * @author Omar Stefan Evans * @date 2014-07-18 * @details closes this connection if it is not already closed */ virtual ~TCPStream_Winsock2(); virtual State getState() override; /** * Opens this connection. * @author Omar Stefan Evans * @date 2014-07-18 * @return true on success, false on failure */ virtual void open() override; /** * Secures this connection. * @author Omar Stefan Evans * @date 2014-07-18 * @return true on success, false on failure */ virtual void secure() override; /** * Closes this connection. * @author Omar Stefan Evans * @date 2014-07-18 */ virtual void close() override; /** * Sends data over this connection * @author Omar Stefan Evans * @date 2014-07-18 * @param data the data to send */ virtual void sendData(std::vector<UInt8> const & data) override; /** * Gets the domain name used to initialize this TCP stream. * @author Omar Stefan Evans * @date 2015-01-27 */ virtual String getDomainName() const override; /** * Gets the service name used to initialize this TCP stream. * @author Omar Stefan Evans * @date 2015-01-27 */ virtual String getServiceName() const override; /** * The remote host's actual name. This may be the same as the domain name if this TCP stream * was initialized with a port number instead of a service name. * @author Omar Stefan Evans * @date 2015-01-27 */ virtual String getRemoteHostName() const override; /** * The port number on the remote host for this TCP stream. * @author Omar Stefan Evans * @date 2015-01-27 */ virtual UInt16 getRemotePortNumber() const override; private: String domainName; String serviceName; String remoteHostName; UInt16 remotePortNumber; void readLoopFunction(); WSADATA wsaData; SOCKET theSocket { INVALID_SOCKET }; PSecurityFunctionTable securityFunctionTable; CtxtHandle securityContextHandle; std::thread readLoopThread; }; }}
//#include "stdafx.h" #include <iostream> #include "cuda_runtime.h" #include "device_launch_parameters.h" #include"mat.h" #include <stdio.h> #include<stdlib.h> #include<cmath> #include "mclmcr.h" #include"matrix.h" //#include <opencv2/core/core.hpp> //#include<opencv2/highgui/highgui.hpp> //#include<complex.h> #include<complex> using namespace std; //using namespace cv; static int TOTAL_ELEMENTS = (3534 * 16384); static MATFile *pMF = NULL; static mxArray *pA = NULL; static MATFile *pMF_out = NULL; static mxArray *pA_out = NULL; static MATFile *beamF_out = NULL; static mxArray *beamM_out = NULL; #define N_elements 128 int M_elements; int emit_aperture; int emit_pitch; int emit_start; int Trans_elements; int zerolength = 1000; int fs = 40000000; //double A[3534][16384]; double x_begin = (-3.0 / 1000); double z_begin = 27.5 / 1000; double d_x = 0.05 / 1000; double d_z = 0.05 / 1000; double pitch = (3.08e-4); double t1 = (3.895e-5); double a_begin = -double((N_elements - 1)) / 2 * pitch; int c = 1540; int xsize = 501; int ysize = 121; double *init_imaginary; double *init_real; unsigned char Result[501][121]; int main() { int i; double index_finished = 0; int index_1; int row_v2; int column_v2; int temp; int temp_1; int temp_2; /*******************************************数据预处理部分---将v2的complex数据读进来**************************************/ complex<double> * init_M1 = new complex<double>[3534 * 16384]; //complex<double> *init_M1; pMF = matOpen("D:\\WenshuaiZhao\\ProjectFiles\\VisualStudioFiles\\Ultrasound_GPU\\GPU_Data\\v2.mat", "r");//打开MAT文件,返回文件指针 pA = matGetVariable(pMF, "v2");//获取v2.mat文件里的变量 init_real = (double*)mxGetPr(pA); init_imaginary = (double*)mxGetPi(pA); //init_M1 = (complex<double>*)mxGetData(pA); for (i = 0; i < TOTAL_ELEMENTS; i++) { complex<double> temp(init_real[i], init_imaginary[i]); init_M1[i] = temp; }//将从v2读出的实部和虚部重新组合在一起,放入init_M1. for (i = 0; i < 10; i++) { cout << "init_M1" << i << "=" << init_M1[i] << endl; }//验证init_M1的数据同v2的原始数据是一致的,复数。 /*******************************************数据预处理部分结束*********************************************************/ int M = mxGetM(pA); int N = mxGetN(pA); int a, b; double xp, zp; double xr[N_elements]; double t_delay[N_elements]; double theta_ctrb[N_elements]; double theta_threshold; int theta_start; int theta_end; int k; complex<double> *beamDASDAS = new complex<double>[xsize*ysize]; memset(beamDASDAS, 0, sizeof(beamDASDAS)); int verify[501 * 121]; //***************************************主循环开始*************************************// for (a = 1; a < (ysize + 1); a++) { for (b = 1; b < (xsize + 1); b++) { theta_threshold = 2.8; theta_start = 0; theta_end = 0; xp = x_begin + d_x*(a - 1); zp = z_begin + d_z*(b - 1); /********************************计算子孔径的大小,以及,对应像素点,各个阵元的延时***************************/ for (i = 0; i < (N_elements); i++) { xr[i] = a_begin + pitch*i; t_delay[i] = sqrt(pow((xp - xr[i]), 2) + pow(zp, 2)) / c; theta_ctrb[i] = zp / (abs(xp - xr[i])); } /*for (i = 0; i < (N_elements); i++) { cout << "theta_ctrb "<<i<<"is " << theta_ctrb[i] << endl; }*/ k = 1; while ((k <= N_elements) && (theta_ctrb[k - 1] < theta_threshold)) { k = k + 1; }//求出theta_start的值 if (k == N_elements + 1) NULL; //开始求theta_end的值 else { theta_start = k; // cout << "k or theta_start is" << k << endl; while ((k <= N_elements) && (theta_ctrb[k - 1] >= theta_threshold)) { k = k + 1; } if (k == N_elements + 1) theta_end = k - 1; else { theta_end = k; } // cout << "k or theta_end is" << k << endl; } //求出theta_end的值 //验证theta_start的值 /*if ((a < 2) && (b < 9)) cout << "theta_start is:" << theta_start << endl;*/ //验证计算出的theta_start和theta_end正确与否 /*cout << "theta_start=" << theta_start << endl; cout << "theta_end=" << theta_end << endl;*/ //verify[(a - 1)*ysize + b - 1] = theta_start; /*******************************计算出了theta_start和theta_end******************************/ /*******************************为计算正确延时和回波矩阵做准备******************************/ M_elements = theta_end - theta_start + 1; emit_aperture = M_elements; emit_pitch = 1; emit_start = theta_start; complex<double> * x_pointer = new complex<double>[emit_aperture*M_elements];//为x数组分配动态内存,记得用完delete,x二维数组,是经过正取延时,并且取正确孔径的,回波矩阵。维度为M_elements*M_elements double * delay_pointer = new double[M_elements * 1];//为delay数组分配动态内存,记得用完delete int *delay_int = new int[M_elements * 1];//为取整后的delay值分配内存。 //为刚分配内存的三个数组初始化 memset(delay_pointer, 0, sizeof(delay_pointer)); memset(delay_int, 0, sizeof(delay_pointer)); memset(x_pointer, 0, sizeof(x_pointer)); //*************接下来计算正确延时和回波矩阵x【M_elements*M_elements】*******************************************// for (Trans_elements = emit_start; Trans_elements <= (emit_start + emit_pitch*(emit_aperture - 1)); Trans_elements++) { for (i = theta_start; i <= theta_end; i++) { temp = i - theta_start; delay_pointer[temp] = t_delay[Trans_elements - 1] + t_delay[i - 1]; delay_pointer[temp] = delay_pointer[temp] - t1; delay_pointer[temp] = ((delay_pointer[temp] * fs) + 25.5) + zerolength; delay_int[temp] = (round)(delay_pointer[temp]); // int abc = delay_int[temp]; } for (i = theta_start; i <= theta_end; i++) { index_1 = (i - theta_start); row_v2 = delay_int[index_1];//此处计算有误! column_v2 = (Trans_elements - 1)*N_elements + i - 1; temp_1 = ((Trans_elements - emit_start) / emit_pitch)*M_elements + i - theta_start; //x_pointer[temp_1] = init_M1[row_v2*M + (Trans_elements - 1)*N_elements + i-1];//M为v2矩阵的行数 temp_2 = column_v2*M + row_v2 - 1; x_pointer[temp_1] = init_M1[temp_2];//M为v2矩阵的行数 //((Trans_elements - 1)*N_elements + i - 1)*M+row_v2 } } //*************计算延时和回波矩阵完毕*********************************************************************// //*************接下来计算本像素点的beamDASDAS*******************************************// for (i = 0; i < M_elements; i++) { int j; for (j = 0; j < M_elements; j++) { complex<double> temp_1 = 0; temp_1 = x_pointer[i*M_elements + j] + beamDASDAS[(b - 1)*ysize + (a - 1)]; beamDASDAS[(b - 1)*ysize + (a - 1)] = temp_1; } } beamDASDAS[(b - 1)*ysize + (a - 1)] = beamDASDAS[(b - 1)*ysize + (a - 1)] / ((double)(M_elements*M_elements)); //*****************计算出了beamDASDAS*************************************************// //删除所用的动态内存 delete[]x_pointer; delete[]delay_pointer; delete[]delay_int; } index_finished = 100.0 * a / ysize; printf("%.6lf\n", index_finished); } //************************************************主循环结束*********************************************************// /***********************打印结果**********************************************/ //printf("The beamDASDAS matrix 501*121 is: \n"); for (i = 0; i < 8; i++) { cout << "beamDASDAS[" << i << "] is: "; cout << beamDASDAS[i]; /*cout << "verify is"; cout << verify[i];*/ cout << endl; } //*******************将beamDASDAS的结果保存到MAT文件,便于MATLAB进行图像生成***************************************// //pMF_out = matOpen("E:\\Project_files\\visual studio projects\\Ultrasound_GPU\\GPU_Data\\out_beamDASDAS.mat", "w"); //cout << "已完成打开文件" << endl; ////mwArray matrixComplex(row, column, mxDOUBLE_CLASS, mxCOMPLEX);//定义数组,行,列,double类型复数矩阵 ////pA = mxCreateStructMatrix(row, column, complex<double>);. //pA_out = mxCreateDoubleMatrix(xsize, ysize, mxCOMPLEX);//pA_out是mxArray类型的指针 //cout << "已完成创建矩阵" << endl; ////mxSetData(pA_out, out_beam); ///*在早前版本的matlab自带的版本中使用的是mxSetData函数进行数值输入, // 但是在比较新的版本中,这个函数使用会出现错误,笔者也不知道为什么。 // 所以在不确定的情况下,你可以使用memcpy;*/ //memcpy((void*)mxGetData((pA_out)), beamDASDAS, sizeof(complex<double>) * xsize*ysize); ////memcpy((complex<double>*)mxGetData((pA_out)), beamDASDAS, sizeof(complex<double>) * xsize*ysize); ////使用mxGetData函数获取数据阵列中的数据;返回时需要使用强制类型转换。 ///*for (i = 0; i < 10; i++) //{ // cout << "pA_out is:" // << mxGetData(pA_out) << endl; //}*/ //cout << "已完成copy数据" << endl; //matPutVariable(pMF_out, "beamDASDAS_GPU", pA_out);//如果matlab正在读该变量,则运行至此时会报错,只需在matlab里clear一下就OK了! //cout << "已完成放入变量" << endl; ////matClose(pMF_out); /***************************************已得到正确beamDASDAS矩阵,接下来进行对数压缩************************/ ////先求beamDASDAS的绝对值 //double *beam2 = new double[xsize*ysize]; //double *beamshow = new double[xsize*ysize]; //double peakall=0; //double peakall_2 = 0; //for (i = 0; i < xsize*ysize; i++) //{ // beam2[i] = abs(beamDASDAS[i]); // if (beam2[i] >= peakall) // peakall = beam2[i]; //} //for (i = 0; i < xsize*ysize; i++) //{ // beamshow[i] = 20 * log10(beam2[i] / peakall); // if (beamshow[i] < -60) // beamshow[i] = -60; //} //for (i = 0; i < xsize*ysize; i++) //{ // beamshow[i] = 60 + beamshow[i]; //} //for (i = 0; i < xsize*ysize; i++) //{ // if(peakall_2<=beamshow[i]) // peakall_2=beamshow[i]; //} // //for (i = 0; i < xsize*ysize; i++) //{ // beamshow[i] = 255*(beamshow[i] / peakall_2); // //} //for (i = 0; i < 8; i++) //{ // cout << "beamshow[" << i << "] is: "; // cout << beamshow[i]; // /*cout << "verify is"; // cout << verify[i];*/ // cout << endl; //} //for (i = 0; i < xsize; i++) //{ // for (int j = 0; j < ysize; j++) // { // Result[i][j] = unsigned char((floor(beamshow[i * 121 + j]))); // } //} //Mat MM=Mat(501, 121, CV_8UC1); //memcpy(MM.data, Result, sizeof(unsigned char)*xsize*ysize); ////Mat MM= Mat(501, 121, CV_32SC3, Result).clone(); ////namedWindow("Ultrasound_Image"); //imshow("Ultrasound_Image", MM); ////imshow("Ultrasound_Image", Result); delete[]beamDASDAS; delete[]init_M1; //printf("One Element is %e\n",init_M1[M*3]); //printf("One Element is %lf\n", init_M1[M * 3]); //printf("The no. of rows of Matrix M1 is %d\n", M); //printf("The no. of column of Matrix M1 is %d\n", N); getchar(); getchar(); return 0; }
#ifndef ENTERPRISE_MANAGEMENT_SYSTEM_OPERATORSTAFF_H #define ENTERPRISE_MANAGEMENT_SYSTEM_OPERATORSTAFF_H #endif //ENTERPRISE_MANAGEMENT_SYSTEM_OPERATORSTAFF_H #pragma once #include "BaseStaff.h" class OperatorStaff : public BaseStaff { public: int resolveFailureRate; //故障解决率 int workEfficiency; //工作效率 int projectCompletion; //公司操作项目完成数 OperatorStaff(); ~OperatorStaff(); void showInfos(); void setResolveFailureRate(); int getResolveFailureRate() const; void setWorkEfficiency(); int getWorkEfficiency() const; void setProjectCompletion(); int getProjectCompletion() const; };
#include "predict_true.h" #include "pi_to_pi.h" #include <math.h> /***************************************************************************** * OPTIMIZATION STATUS * Done: Base implementation, unit test * ToDo: Start optimizing ****************************************************************************/ void predict_true(const double V,const double G,const double WB, const double dt, Vector3d xv) { predict_true_base(V, G, WB, dt, xv); } /***************************************************************************** * PERFORMANCE STATUS * Work, best: 3 sin/cos + 9 mults + 3 adds + 1 neg + 4 fl-comp +1 div = 20 flops * Work, worst: 3 sin/cos + 12 mults + 5 adds + 2 neg + 4 fl-comp +2 div +1 floor = 29 flops * Memory moved: 3 doubles * Cycles: ~ 400 cyc [170-800] * Performance: 0.05 * Optimal: TBD * Status: TBD ****************************************************************************/ void predict_true_base(const double V,const double G,const double WB, const double dt, Vector3d xv) { xv[0] = xv[0] + V*dt*cos(G+xv[2]); xv[1] = xv[1] + V*dt*sin(G+xv[2]); xv[2] = pi_to_pi_base(xv[2] + V*dt*sin(G)/WB); } double predict_true_base_flops(const double V,const double G,const double WB, const double dt, Vector3d xv) { return 6*tp.mul + tp.div +5*tp.add + pi_to_pi_base_flops(xv[2] + V*dt*sin(G)/WB) + tp.cos + 2*tp.sin; } double predict_true_base_memory(const double V,const double G,const double WB, const double dt, Vector3d xv) { return 2 * 3; }
// Copyright 2011 Yandex #ifndef LTR_SCORERS_DECISION_TREE_SCORER_H_ #define LTR_SCORERS_DECISION_TREE_SCORER_H_ #include <string> #include "ltr/scorers/scorer.h" #include "ltr/learners/decision_tree/decision_tree.h" using std::string; namespace ltr { namespace decision_tree { class DecisionTreeScorer : public Scorer { private: DecisionTree<double> tree_; double scoreImpl(const Object& obj) const { return tree_.value(obj); } string generateCppCodeImpl(const string& function_name) const { return tree_.generateCppCode(function_name); } virtual string getDefaultAlias() const {return "DecisionTreeScorer";} public: typedef ltr::utility::shared_ptr< DecisionTreeScorer > Ptr; DecisionTreeScorer() {} void setTree(const DecisionTree<double>& tree) { tree_ = tree; } void setTreeRoot(Vertex<double>::Ptr root) { tree_.setRoot(root); } string toString() const { return "Decision of the tree"; } }; } } #endif // LTR_SCORERS_DECISION_TREE_SCORER_H_
#ifndef DECK57_HPP #define DECK57_HPP #include "Deck56.hpp" class Deck57: public Deck56{ public : Deck57(); }; #endif
#ifndef CLASSIFIER_H #define CLASSIFIER_H #include <iostream> #include <sstream> #include <fstream> #include <math.h> #include <vector> #include <map> #include <algorithm> using namespace std; class GNB { public: //vector<string> possible_labels = {"left","keep","right"}; vector<string> possible_labels; map<string, vector<double> > means; map<string, vector<double> > stddevs; map<string, double> counts; double total_count; /** * Constructor */ GNB(); /** * Destructor */ virtual ~GNB(); void train(vector<vector<double> > data, vector<string> labels); string predict(vector<double>); void printMap(map<string, vector<double> > mp); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef DESKTOP_WINDOW_MODEL_ITEM_H #define DESKTOP_WINDOW_MODEL_ITEM_H #include "adjunct/quick/models/DesktopWindowCollectionItem.h" /** * @brief Represents a desktop window */ class DesktopWindowModelItem : public DesktopWindowCollectionItem { public: explicit DesktopWindowModelItem(DesktopWindow* desktop_window) : m_desktop_window(desktop_window) {} // From DesktopWindowCollectionItem virtual DesktopWindow* GetDesktopWindow() { return m_desktop_window; } virtual bool AcceptsInsertInto(); virtual bool IsContainer() { return GetType() == WINDOW_TYPE_BROWSER; } virtual const char* GetContextMenu() { return "Windows Item Popup Menu"; } // From TreeModelItem virtual INT32 GetID(); virtual Type GetType(); virtual OP_STATUS GetItemData(ItemData* item_data); virtual void OnAdded(); DesktopWindow* m_desktop_window; }; #endif // DESKTOP_WINDOW_MODEL_ITEM_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2009-2010 * * WebGL GLSL compiler -- validating the shaders. * */ #include "core/pch.h" #ifdef CANVAS3D_SUPPORT #include "modules/webgl/src/wgl_base.h" #include "modules/webgl/src/wgl_ast.h" #include "modules/webgl/src/wgl_context.h" #include "modules/webgl/src/wgl_string.h" #include "modules/webgl/src/wgl_error.h" #include "modules/webgl/src/wgl_validate.h" #include "modules/webgl/src/wgl_builder.h" /* static */ void WGL_ValidateShader::MakeL(WGL_ValidateShader *&validator, WGL_Context *context, WGL_Printer *printer) { validator = OP_NEWGRO_L(WGL_ValidateShader, (), context->Arena()); validator->printer = printer; validator->context = context; } BOOL WGL_ValidateShader::ValidateL(WGL_DeclList *decls, WGL_Validator::Configuration &config) { context->ResetL(config.for_vertex); context->Initialise(&config); this->for_vertex = config.for_vertex; VisitDeclList(decls); BOOL have_main = FALSE; for (WGL_FunctionData *fun = context->GetValidationState().GetFirstFunction(); fun; fun = fun->Suc()) { if (fun->name->Equals(UNI_L("main"))) { have_main = TRUE; break; } } if (!have_main) context->AddError(WGL_Error::MISSING_MAIN_FUNCTION, UNI_L("")); if (!config.for_vertex) { /* Perform 'compile-time' checks of the fragment shader: * - did it have a precision declaration/specifier. * - exceeded uniform / varying usage by limits that cannot * be supported by later stages. */ /* There is no requirement for there to be a defaulting 'precision' declaration (but often unavoidable.) */ #if 0 WGL_BindingScope<WGL_Precision> *global_prec = context->GetValidationState().GetPrecisionScope(); BOOL prec_ok = global_prec && global_prec->list && !global_prec->list->Empty(); if (prec_ok) { prec_ok = FALSE; for (WGL_Precision *p = global_prec->list->First(); p; p = p->Suc()) if (WGL_Type::HasBasicType(p->type, WGL_BasicType::Float)) { prec_ok = TRUE; break; } } if (!prec_ok) context->AddError(WGL_Error::MISSING_PRECISION_DECL, UNI_L("")); #endif } return !HaveErrors(); } WGL_VarName * WGL_ValidateShader::ValidateIdentifier(WGL_VarName *i, BOOL is_use, BOOL force_alias, BOOL is_program_global_id) { const uni_char *name = i->value; if (uni_strncmp(name, "webgl_", 6) == 0 && !context->IsUnique(i)) context->AddError(WGL_Error::ILLEGAL_NAME, Storage(context, i)); else if (uni_strncmp(name, "_webgl_", 7) == 0) context->AddError(WGL_Error::ILLEGAL_NAME, Storage(context, i)); /* A GLSL restriction; inherited. Attempts to read gl_XYZ will be caught as out-of-scope accesses. */ if (!is_use && uni_strncmp(name, "gl_", 3) == 0) context->AddError(WGL_Error::ILLEGAL_NAME, Storage(context, i)); if (!is_use && context->GetConfiguration() && !WGL_Validator::IsGL(context->GetConfiguration()->output_format) && WGL_HLSLBuiltins::IsHLSLKeyword(name)) force_alias = TRUE; unsigned len = WGL_String::Length(i); if (len > WGL_MAX_IDENTIFIER_LENGTH) context->AddError(WGL_Error::OVERLONG_IDENTIFIER, Storage(context, i)); /* Potentially troublesome for the underlying compiler to handle; replace with our own unique. */ else if (force_alias || len > 100) { WGL_VarName *unique = is_program_global_id ? context->NewUniqueHashVar(i) : context->NewUniqueVar(FALSE); if (unique) { context->GetValidationState().AddAlias(i, unique); return unique; } } return i; } WGL_VarName * WGL_ValidateShader::ValidateVar(WGL_VarName *var, BOOL is_local_only) { WGL_VarName *alias_var = var; WGL_Type *type = context->GetValidationState().LookupVarType(var, &alias_var, is_local_only); WGL_FunctionData *fun = NULL; if (!type) fun = context->GetValidationState().LookupFunction(var); if (!type && !fun && !context->GetValidationState().LookupBuiltin(var)) context->AddError(WGL_Error::UNKNOWN_VAR, Storage(context, var)); if (is_local_only && type) context->AddError(WGL_Error::DUPLICATE_NAME, Storage(context, alias_var)); /* Record use of a uniform. Not relevant to 'local only', simply avoid. */ if (!is_local_only) { context->GetValidationState().LookupAttribute(alias_var, TRUE); context->GetValidationState().LookupUniform(alias_var, TRUE); if (!IsVertexShader()) context->GetValidationState().LookupVarying(alias_var, TRUE); } return alias_var; } WGL_VarBinding * WGL_ValidateShader::ValidateVarDefn(WGL_VarName *var, WGL_Type *var_type, BOOL is_read_only) { WGL_VarName *alias_var = var; if (context->GetValidationState().LookupVarType(var, &alias_var, TRUE)) { context->AddError(WGL_Error::DUPLICATE_NAME, Storage(context, var)); return NULL; } BOOL is_uniform_varying = FALSE; if (var_type && var_type->type_qualifier && (var_type->type_qualifier->storage == WGL_TypeQualifier::Uniform || var_type->type_qualifier->storage == WGL_TypeQualifier::Varying)) is_uniform_varying = TRUE; alias_var = ValidateIdentifier(var, FALSE, FALSE, is_uniform_varying); if (var_type) { unsigned type_mask = WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float; BOOL is_basic = WGL_Type::HasBasicType(var_type, type_mask); BOOL is_vector = !is_basic && WGL_Type::IsVectorType(var_type, type_mask); BOOL is_matrix = !is_basic && !is_vector && WGL_Type::IsMatrixType(var_type, type_mask); if (var_type->precision == WGL_Type::NoPrecision && (var_type->GetType() == WGL_Type::Sampler || is_basic || is_vector || is_matrix)) { WGL_Type *prec_type = var_type; if (is_vector) prec_type = context->GetASTBuilder()->BuildBasicType(WGL_VectorType::GetElementType(static_cast<WGL_VectorType *>(var_type))); else if (is_matrix) prec_type = context->GetASTBuilder()->BuildBasicType(WGL_MatrixType::GetElementType(static_cast<WGL_MatrixType *>(var_type))); WGL_Type::Precision found_prec = context->GetValidationState().LookupPrecision(prec_type); if (!IsVertexShader() && found_prec == WGL_Type::NoPrecision && (var_type->GetType() != WGL_Type::Sampler && WGL_Type::HasBasicType(prec_type, WGL_BasicType::Float))) context->AddError(WGL_Error::MISSING_PRECISION_DECL, Storage(context, var)); var_type->precision = found_prec; var_type->implicit_precision = TRUE; } } return context->GetValidationState().AddVariable(var_type, alias_var, is_read_only); } WGL_VarName * WGL_ValidateShader::ValidateTypeName(WGL_VarName *var, BOOL is_use) { WGL_Type *type = context->GetValidationState().LookupTypeName(var); if (type && !is_use) { context->AddError(WGL_Error::DUPLICATE_NAME, Storage(context, var)); return NULL; } else if (!type && is_use) { context->AddError(WGL_Error::UNKNOWN_VAR, Storage(context, var)); return NULL; } else return ValidateIdentifier(var, TRUE); } BOOL WGL_ValidateShader::HaveErrors() { return (context->GetFirstError() != NULL); } void WGL_ValidateShader::Reset() { context->ClearErrors(); } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_LiteralExpr *e) { switch (e->literal->type) { case WGL_Literal::Double: return e; case WGL_Literal::Int: return e; case WGL_Literal::UInt: return e; case WGL_Literal::Bool: return e; case WGL_Literal::String: return e; case WGL_Literal::Vector: return e; case WGL_Literal::Matrix: return e; case WGL_Literal::Array: return e; default: OP_ASSERT(!"Unexpected literal"); return e; } } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_VarExpr *e) { e->name = ValidateVar(e->name); context->GetValidationState().GetExpressionType(e); return e; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_TypeConstructorExpr *e) { e->constructor = e->constructor->VisitType(this); return e; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_UnaryExpr *e) { /* Return the node if the expression is empty/NULL. */ if (!e->arg) return e; e->arg = e->arg->VisitExpr(this); WGL_Type *t1 = context->GetValidationState().GetExpressionType(e->arg); if (!t1) return e; switch (e->op) { case WGL_Expr::OpNot: if (!WGL_Type::HasBasicType(t1, WGL_BasicType::Bool)) context->AddError(WGL_Error::ILLEGAL_ARGUMENT_TYPE, UNI_L("")); break; case WGL_Expr::OpAdd: case WGL_Expr::OpNegate: case WGL_Expr::OpPreDec: case WGL_Expr::OpPreInc: if (!(WGL_Type::HasBasicType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float) || WGL_Type::IsVectorType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float) || WGL_Type::IsVectorType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float))) context->AddError(WGL_Error::ILLEGAL_ARGUMENT_TYPE, UNI_L("")); break; default: OP_ASSERT(!"Unexpected unary operator"); break; } context->GetValidationState().GetExpressionType(e); return e; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_PostExpr *e) { e->arg = e->arg->VisitExpr(this); WGL_Type *t1 = context->GetValidationState().GetExpressionType(e->arg); if (!t1) return e; switch (e->op) { case WGL_Expr::OpPostInc: case WGL_Expr::OpPostDec: if (!WGL_Type::HasBasicType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float) && !WGL_Type::IsVectorType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float) && !WGL_Type::IsVectorType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float)) context->AddError(WGL_Error::ILLEGAL_ARGUMENT_TYPE, UNI_L("")); break; default: OP_ASSERT(!"Unexpected 'post' expression operator"); break; } context->GetValidationState().GetExpressionType(e); return e; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_SeqExpr *e) { e->arg1 = e->arg1->VisitExpr(this); e->arg2 = e->arg2->VisitExpr(this); context->GetValidationState().GetExpressionType(e); return e; } void WGL_ValidationState::ValidateEqualityOperation(WGL_Type *t) { /* Know that types to (==) and (!=) are equal, check that no arrays or sampler types are used. */ switch (t->GetType()) { case WGL_Type::Array: context->AddError(WGL_Error::ILLEGAL_TYPE_USE, UNI_L("array")); return; case WGL_Type::Sampler: context->AddError(WGL_Error::ILLEGAL_TYPE_USE, UNI_L("sampler")); return; case WGL_Type::Name: { WGL_Type *nt = LookupTypeName(static_cast<WGL_NameType *>(t)->name); if (nt) return ValidateEqualityOperation(nt); break; } case WGL_Type::Struct: { WGL_StructType *struct_type = static_cast<WGL_StructType *>(t); if (struct_type->fields) for (WGL_Field *f = struct_type->fields->list.First(); f; f = f->Suc()) ValidateEqualityOperation(f->type); break; } } } void WGL_ValidateShader::CheckBinaryExpr(WGL_Expr::Operator op, WGL_Type *t1, WGL_Type *t2) { switch (op) { case WGL_Expr::OpOr: case WGL_Expr::OpXor: case WGL_Expr::OpAnd: if (!WGL_Type::HasBasicType(t1, WGL_BasicType::Bool) || !WGL_Type::HasBasicType(t2, WGL_BasicType::Bool)) context->AddError(WGL_Error::ILLEGAL_TYPE, UNI_L("")); break; case WGL_Expr::OpEq: case WGL_Expr::OpNEq: if (!context->GetValidationState().IsSameType(t1, t2, TRUE)) context->AddError(WGL_Error::TYPE_MISMATCH, UNI_L("")); else context->GetValidationState().ValidateEqualityOperation(t1); break; case WGL_Expr::OpLt: case WGL_Expr::OpGt: case WGL_Expr::OpLe: case WGL_Expr::OpGe: if (!context->GetValidationState().IsSameType(t1, t2, TRUE)) context->AddError(WGL_Error::TYPE_MISMATCH, UNI_L("")); else if (!WGL_Type::HasBasicType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float)) context->AddError(WGL_Error::ILLEGAL_TYPE, UNI_L("")); break; case WGL_Expr::OpAdd: case WGL_Expr::OpSub: case WGL_Expr::OpMul: case WGL_Expr::OpDiv: if (!context->GetValidationState().IsSameType(t1, t2, TRUE)) { if (WGL_Type::HasBasicType(t1, WGL_BasicType::Float) && (WGL_Type::IsVectorType(t2, WGL_BasicType::Float) || WGL_Type::IsMatrixType(t2, WGL_BasicType::Float))) break; if (WGL_Type::HasBasicType(t2, WGL_BasicType::Float) && (WGL_Type::IsVectorType(t1, WGL_BasicType::Float) || WGL_Type::IsMatrixType(t1, WGL_BasicType::Float))) break; if (WGL_Type::HasBasicType(t1, WGL_BasicType::Int | WGL_BasicType::UInt) && (WGL_Type::IsVectorType(t2, WGL_BasicType::Int | WGL_BasicType::UInt) || WGL_Type::IsMatrixType(t2, WGL_BasicType::Int | WGL_BasicType::UInt))) break; if (WGL_Type::HasBasicType(t2, WGL_BasicType::Int | WGL_BasicType::UInt) && (WGL_Type::IsVectorType(t1, WGL_BasicType::Int | WGL_BasicType::UInt) || WGL_Type::IsMatrixType(t1, WGL_BasicType::Int | WGL_BasicType::UInt))) break; if (op == WGL_Expr::OpMul && WGL_Type::IsVectorType(t1) && WGL_Type::IsMatrixType(t2) && WGL_VectorType::GetMagnitude(static_cast<WGL_VectorType *>(t1)) == WGL_MatrixType::GetRows(static_cast<WGL_MatrixType *>(t2))) break; if (op == WGL_Expr::OpMul && WGL_Type::IsVectorType(t2) && WGL_Type::IsMatrixType(t1) && WGL_VectorType::GetMagnitude(static_cast<WGL_VectorType *>(t2)) == WGL_MatrixType::GetColumns(static_cast<WGL_MatrixType *>(t1))) break; context->AddError(WGL_Error::UNSUPPORTED_ARGUMENT_COMBINATION, UNI_L("")); } else if (!(WGL_Type::HasBasicType(t1) || WGL_Type::IsVectorType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float) || WGL_Type::IsMatrixType(t1, WGL_BasicType::Int | WGL_BasicType::UInt | WGL_BasicType::Float))) context->AddError(WGL_Error::ILLEGAL_TYPE, UNI_L("")); break; default: OP_ASSERT(!"Unhandled binary operator"); break; } } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_BinaryExpr *e) { e->arg1 = e->arg1->VisitExpr(this); e->arg2 = e->arg2->VisitExpr(this); WGL_Type *t1 = context->GetValidationState().GetExpressionType(e->arg1); WGL_Type *t2 = context->GetValidationState().GetExpressionType(e->arg2); if (!t1 || !t2) return e; CheckBinaryExpr(e->op, t1, t2); context->GetValidationState().GetExpressionType(e); return e; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_CondExpr *e) { /* This should have been caught in the parser. */ OP_ASSERT(e->arg1 && e->arg2 && e->arg3); e->arg1 = e->arg1->VisitExpr(this); WGL_Type *cond_type = context->GetValidationState().GetExpressionType(e->arg1); if (cond_type && !WGL_Type::HasBasicType(cond_type, WGL_BasicType::Bool)) context->AddError(WGL_Error::INVALID_COND_EXPR, UNI_L("")); e->arg2 = e->arg2->VisitExpr(this); WGL_Type *t2 = context->GetValidationState().GetExpressionType(e->arg2); e->arg3 = e->arg3->VisitExpr(this); WGL_Type *t3 = context->GetValidationState().GetExpressionType(e->arg3); if (t2 && t3 && !context->GetValidationState().IsSameType(t2, t3, TRUE)) context->AddError(WGL_Error::INVALID_COND_MISMATCH, UNI_L("")); context->GetValidationState().GetExpressionType(e); return e; } BOOL WGL_ValidationState::GetTypeForSwizzle(WGL_VectorType *vec_type, WGL_SelectExpr *sel_expr, WGL_Type *&result) { unsigned sel_len = WGL_String::Length(sel_expr->field); if (sel_len == 0 || sel_len > 4) { OP_ASSERT(!"Unexpected vector expression"); return FALSE; } WGL_BasicType::Type basic_type = WGL_VectorType::GetElementType(vec_type); if (basic_type == WGL_BasicType::Void) { OP_ASSERT(!"Unexpected vector type"); return FALSE; } if (sel_len == 1) result = context->GetASTBuilder()->BuildBasicType(basic_type); else { WGL_VectorType::Type vtype = WGL_VectorType::Vec2; switch (basic_type) { case WGL_BasicType::Bool: vtype = WGL_VectorType::BVec2; break; case WGL_BasicType::UInt: vtype = WGL_VectorType::UVec2; break; case WGL_BasicType::Int: vtype = WGL_VectorType::IVec2; break; } /* This depends on Vec<m> + <n> = Vec<m + n>, and similarly for BVec, etc., in the WGL_VectorType::Type enum */ result = context->GetASTBuilder()->BuildVectorType(static_cast<WGL_VectorType::Type>(vtype + sel_len - 2)); } return TRUE; } WGL_Type * WGL_ValidationState::GetExpressionType(WGL_Expr *e) { if (!e) return NULL; if (e->cached_type) return e->cached_type; switch (e->GetType()) { case WGL_Expr::Lit: e->cached_type = context->GetASTBuilder()->BuildBasicType(WGL_LiteralExpr::GetBasicType(static_cast<WGL_LiteralExpr *>(e))); return e->cached_type; case WGL_Expr::Var: e->cached_type = context->GetValidationState().LookupVarType(static_cast<WGL_VarExpr *>(e)->name, NULL); return e->cached_type; case WGL_Expr::TypeConstructor: /* TypeConstructor will only appear as the function in a CallExpr. */ return NULL; case WGL_Expr::Unary: { WGL_UnaryExpr *un_expr = static_cast<WGL_UnaryExpr *>(e); switch (un_expr->op) { case WGL_Expr::OpNot: e->cached_type = context->GetASTBuilder()->BuildBasicType(WGL_BasicType::Bool); return e->cached_type; case WGL_Expr::OpAdd: case WGL_Expr::OpNegate: case WGL_Expr::OpPreDec: case WGL_Expr::OpPreInc: e->cached_type = GetExpressionType(un_expr->arg); return e->cached_type; default: OP_ASSERT(!"unexpected unary operation"); return NULL; } } case WGL_Expr::PostOp: { WGL_PostExpr *post_expr = static_cast<WGL_PostExpr *>(e); e->cached_type = GetExpressionType(post_expr->arg); return e->cached_type; } case WGL_Expr::Seq: { WGL_SeqExpr *seq_expr = static_cast<WGL_SeqExpr *>(e); e->cached_type = GetExpressionType(seq_expr->arg2); return e->cached_type; } case WGL_Expr::Binary: { WGL_BinaryExpr *bin_expr = static_cast<WGL_BinaryExpr *>(e); switch (bin_expr->op) { case WGL_Expr::OpAdd: case WGL_Expr::OpSub: case WGL_Expr::OpMul: case WGL_Expr::OpDiv: { WGL_Type *type_lhs = GetExpressionType(bin_expr->arg1); WGL_Type *type_rhs = GetExpressionType(bin_expr->arg2); if (!type_lhs || !type_rhs) return NULL; WGL_BasicType::Type t1 = WGL_BasicType::GetBasicType(type_lhs); WGL_BasicType::Type t2 = WGL_BasicType::GetBasicType(type_rhs); if (t1 == WGL_BasicType::Void || t2 == WGL_BasicType::Void) { if (t1 == WGL_BasicType::Void && t2 == WGL_BasicType::Void) { /* (V,V) or (M,M) */ if (IsSameType(type_lhs, type_rhs, TRUE) && (type_lhs->GetType() == WGL_Type::Vector || type_lhs->GetType() == WGL_Type::Matrix)) e->cached_type = type_lhs; else if (type_lhs->GetType() == WGL_Type::Matrix && type_rhs->GetType() == WGL_Type::Vector) e->cached_type = type_rhs; else if (type_lhs->GetType() == WGL_Type::Vector && type_rhs->GetType() == WGL_Type::Matrix) e->cached_type = type_lhs; else return NULL; } else if (t1 != WGL_BasicType::Void) e->cached_type = type_rhs; else e->cached_type = type_lhs; return e->cached_type; } if (t1 == WGL_BasicType::Float) e->cached_type = type_lhs; else if (t2 == WGL_BasicType::Float) e->cached_type = type_rhs; else if (t1 == WGL_BasicType::Int) e->cached_type = type_lhs; else e->cached_type = type_rhs; return e->cached_type; } case WGL_Expr::OpEq: case WGL_Expr::OpNEq: case WGL_Expr::OpLt: case WGL_Expr::OpLe: case WGL_Expr::OpGe: case WGL_Expr::OpGt: case WGL_Expr::OpOr: case WGL_Expr::OpXor: case WGL_Expr::OpAnd: e->cached_type = context->GetASTBuilder()->BuildBasicType(WGL_BasicType::Bool); return e->cached_type; default: OP_ASSERT(!"unexpected binary operation"); return NULL; } } case WGL_Expr::Cond: { WGL_CondExpr *cond_expr = static_cast<WGL_CondExpr *>(e); e->cached_type = GetExpressionType(cond_expr->arg2); return e->cached_type; } case WGL_Expr::Call: { WGL_CallExpr *call_expr = static_cast<WGL_CallExpr *>(e); if (call_expr->fun->GetType() == WGL_Expr::TypeConstructor) { e->cached_type = static_cast<WGL_TypeConstructorExpr *>(call_expr->fun)->constructor; return e->cached_type; } else { OP_ASSERT(call_expr->fun->GetType() == WGL_Expr::Var); WGL_VarExpr *fun = static_cast<WGL_VarExpr *>(call_expr->fun); if (WGL_FunctionData *data = context->GetValidationState().LookupFunction(fun->name)) { for (WGL_FunctionDecl *fun_decl = data->decls.First(); fun_decl; fun_decl = fun_decl->Suc()) { if (!call_expr->args && fun_decl->parameters->list.Empty()) { e->cached_type = fun_decl->return_type; return e->cached_type; } else if (call_expr->args->list.Cardinal() == fun_decl->parameters->list.Cardinal()) { WGL_Expr *arg = call_expr->args->list.First(); BOOL decl_match = TRUE; for (WGL_Param *p = fun_decl->parameters->list.First(); p; p = p->Suc()) { if (!context->GetValidationState().HasExpressionType(p->type, arg, TRUE)) { decl_match = FALSE; break; } arg = arg->Suc(); } if (decl_match) { e->cached_type = fun_decl->return_type; return e->cached_type; } } } return NULL; } else if (List<WGL_Builtin> *builtin_decls = context->GetValidationState().LookupBuiltin(fun->name)) { for (WGL_Builtin *builtin = builtin_decls->First(); builtin; builtin = builtin->Suc()) { if (builtin->IsBuiltinVar() || !call_expr->args) continue; WGL_BuiltinFun *fun = static_cast<WGL_BuiltinFun *>(builtin); if (call_expr->args->list.Cardinal() == fun->parameters.Cardinal()) { WGL_Expr *arg = call_expr->args->list.First(); BOOL decl_match = TRUE; WGL_Type *generic_type = NULL; for (WGL_BuiltinType *p = fun->parameters.First(); p; p = p->Suc()) { WGL_Type *arg_type = context->GetValidationState().GetExpressionType(arg); if (!arg_type || !context->GetValidationState().MatchesBuiltinType(p, arg_type) || generic_type && p->type > WGL_BuiltinType::Sampler && !IsSameType(arg_type, generic_type, TRUE)) { decl_match = FALSE; break; } else if (p->type > WGL_BuiltinType::Sampler && !generic_type) generic_type = arg_type; arg = arg->Suc(); } if (decl_match) { e->cached_type = ResolveBuiltinReturnType(fun, call_expr->args, generic_type); return e->cached_type; } } } return NULL; } else return NULL; } } case WGL_Expr::Index: { WGL_IndexExpr *index_expr = static_cast<WGL_IndexExpr *>(e); if (!index_expr->array) return NULL; WGL_Type *array_type = GetExpressionType(index_expr->array); if (!array_type) return NULL; if (array_type->GetType() == WGL_Type::Array) e->cached_type = static_cast<WGL_ArrayType *>(array_type)->element_type; else if (array_type->GetType() == WGL_Type::Vector) e->cached_type = context->GetASTBuilder()->BuildBasicType(WGL_VectorType::GetElementType(static_cast<WGL_VectorType *>(array_type))); else if (array_type->GetType() == WGL_Type::Matrix) e->cached_type = context->GetASTBuilder()->BuildVectorType(WGL_VectorType::ToVectorType(WGL_MatrixType::GetElementType(static_cast<WGL_MatrixType *>(array_type)), WGL_MatrixType::GetRows(static_cast<WGL_MatrixType *>(array_type)))); else { OP_ASSERT(!"Unexpected indexing expression"); return NULL; } return e->cached_type; } case WGL_Expr::Select: { WGL_SelectExpr *sel_expr = static_cast<WGL_SelectExpr *>(e); if (!sel_expr->value) return NULL; WGL_Type *struct_type = GetExpressionType(sel_expr->value); if (!struct_type) return NULL; if (struct_type->GetType() == WGL_Type::Name) { WGL_NameType *name_type = static_cast<WGL_NameType *>(struct_type); struct_type = context->GetValidationState().LookupTypeName(name_type->name); } if (struct_type->GetType() == WGL_Type::Struct) { if (WGL_Field *f = context->GetValidationState().LookupField(static_cast<WGL_StructType *>(struct_type)->fields, sel_expr->field)) { e->cached_type = f->type; return e->cached_type; } return NULL; } else if (struct_type->GetType() == WGL_Type::Vector) { if (!GetTypeForSwizzle(static_cast<WGL_VectorType *>(struct_type), sel_expr, e->cached_type)) return NULL; return e->cached_type; } else { OP_ASSERT(!"Unexpected value to select field from."); return NULL; } } case WGL_Expr::Assign: e->cached_type = GetExpressionType(static_cast<WGL_AssignExpr *>(e)->rhs); return e->cached_type; default: OP_ASSERT(!"Unexpected expression type"); return NULL; } } BOOL WGL_ValidateShader::IsConstructorArgType(WGL_Type *t) { /* NOTE: we are not permitting multi-dim arrays; doesn't appear legal. */ switch (t->GetType()) { case WGL_Type::Basic: if (static_cast<WGL_BasicType *>(t)->type == WGL_BasicType::Void) return FALSE; break; case WGL_Type::Vector: case WGL_Type::Matrix: break; default: return FALSE; } return TRUE; } BOOL WGL_ValidateShader::IsConstructorArgType(WGL_BuiltinType *t) { return t->type == WGL_BuiltinType::Sampler ? FALSE : TRUE; } /** Check well-formedness of constructor applications -- TY(arg1,arg2,..,argN). * where TY can be a basic type, vector, matrix or array type (struct names handled elsewhere.) * The argX have to be basic types or vector/matrix applications too (i.e., don't * see nested applications of the array constructors.) */ BOOL WGL_ValidateShader::IsScalarOrVecMat(WGL_Expr *e, BOOL is_nested) { /* Not doing type checking/inference of arbitrary expressions.. merely imposing * the syntactic restriction that a constructor may only be passed basic types * or (possibly nested) applications of vector/matrix constructors. */ switch (e->GetType()) { case WGL_Expr::Lit: return TRUE; case WGL_Expr::Var: { WGL_VarExpr *var_expr = static_cast<WGL_VarExpr *>(e); if (WGL_Type *t = context->GetValidationState().LookupVarType(var_expr->name, NULL)) return IsConstructorArgType(t); return FALSE; } case WGL_Expr::Call: { WGL_CallExpr *call_expr = static_cast<WGL_CallExpr *>(e); switch (call_expr->fun->GetType()) { case WGL_Expr::TypeConstructor: { WGL_TypeConstructorExpr *ctor_expr = static_cast<WGL_TypeConstructorExpr *>(call_expr->fun); switch (ctor_expr->constructor->GetType()) { case WGL_Type::Basic: { WGL_BasicType *basic_type = static_cast<WGL_BasicType *>(ctor_expr->constructor); if (basic_type->type != WGL_BasicType::Float && basic_type->type != WGL_BasicType::Int) return FALSE; for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) if (!IsScalarOrVecMat(arg, TRUE)) return FALSE; return TRUE; } case WGL_Type::Vector: { // We need type information for the arguments to be available // when running the CG generator. (Proper validation would need // this information anyway.) for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) (void)context->GetValidationState().GetExpressionType(arg); WGL_VectorType *vector_type = static_cast<WGL_VectorType *>(ctor_expr->constructor); unsigned bound = 1; switch (vector_type->type) { case WGL_VectorType::Vec2: case WGL_VectorType::BVec2: case WGL_VectorType::IVec2: case WGL_VectorType::UVec2: bound = 2; break; case WGL_VectorType::Vec3: case WGL_VectorType::BVec3: case WGL_VectorType::IVec3: case WGL_VectorType::UVec3: bound = 3; break; case WGL_VectorType::Vec4: case WGL_VectorType::BVec4: case WGL_VectorType::IVec4: case WGL_VectorType::UVec4: bound = 4; break; } /* GLSL flattens the arguments..that is, vecX(a,b), is interpreted as flatten(a) ++ flatten (b) (where * 'a' and 'b' can be vectors or base types. Or variables bound to such.) */ if (!call_expr->args || call_expr->args->list.Empty() || call_expr->args->list.Cardinal() > bound) return FALSE; for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) if (!IsScalarOrVecMat(arg, TRUE)) return FALSE; return TRUE; } case WGL_Type::Matrix: { // We need type information for the arguments to be available // when running the CG generator. (Proper validation would need // this information anyway.) for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) (void)context->GetValidationState().GetExpressionType(arg); WGL_MatrixType *mat_type = static_cast<WGL_MatrixType *>(ctor_expr->constructor); unsigned bound = 1; switch (mat_type->type) { case WGL_MatrixType::Mat2: case WGL_MatrixType::Mat2x2: bound = 4; break; case WGL_MatrixType::Mat2x3: case WGL_MatrixType::Mat3x2: bound = 6; break; case WGL_MatrixType::Mat4x2: case WGL_MatrixType::Mat2x4: bound = 8; break; case WGL_MatrixType::Mat3: case WGL_MatrixType::Mat3x3: bound = 9; break; case WGL_MatrixType::Mat4x3: case WGL_MatrixType::Mat3x4: bound = 12; break; case WGL_MatrixType::Mat4: case WGL_MatrixType::Mat4x4: bound = 16; break; } if (!call_expr->args || call_expr->args->list.Empty() || call_expr->args->list.Cardinal() > bound) return FALSE; else { for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) if (!IsScalarOrVecMat(arg, TRUE)) return FALSE; return TRUE; } } case WGL_Type::Array: { if (is_nested) return FALSE; WGL_ArrayType *arr_type = static_cast<WGL_ArrayType *>(ctor_expr->constructor); if (!IsConstructorArgType(arr_type->element_type)) return FALSE; for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) if (!IsScalarOrVecMat(arg, TRUE)) return FALSE; return TRUE; } default: return FALSE; } } case WGL_Expr::Var: { WGL_VarExpr *fun = static_cast<WGL_VarExpr *>(call_expr->fun); if (WGL_FunctionData *fun_info = context->GetValidationState().LookupFunction(fun->name)) { /* TODO: perform overload resolution to precisely determine return type of application. */ if (fun_info->decls.First()) return IsConstructorArgType(fun_info->decls.First()->return_type); } else if (List<WGL_Builtin> *list = context->GetValidationState().LookupBuiltin(fun->name)) { if (!list->First()->IsBuiltinVar()) return IsConstructorArgType(static_cast<WGL_BuiltinFun *>(list->First())->return_type); } return FALSE; } default: return FALSE; } } case WGL_Expr::Index: { WGL_IndexExpr *index_expr = static_cast<WGL_IndexExpr *>(e); WGL_Type *t = context->GetValidationState().GetExpressionType(index_expr->array); if (t && t->GetType() == WGL_Type::Array) return IsConstructorArgType(static_cast<WGL_ArrayType *>(t)->element_type); else if (t && t->GetType() == WGL_Type::Vector) return TRUE; else if (t && t->GetType() == WGL_Type::Matrix) return TRUE; else return FALSE; } case WGL_Expr::Select: { WGL_SelectExpr *sel_expr = static_cast<WGL_SelectExpr *>(e); WGL_Type *sel_type = context->GetValidationState().GetExpressionType(sel_expr->value); if (sel_type && sel_type->GetType() == WGL_Type::Vector) return TRUE; else if (sel_type && sel_type->GetType() != WGL_Type::Struct ) return FALSE; else if (WGL_Field *f = sel_type ? context->GetValidationState().LookupField(static_cast<WGL_StructType *>(sel_type)->fields, sel_expr->field) : NULL) return IsConstructorArgType(f->type); else return FALSE; } case WGL_Expr::Unary: case WGL_Expr::Binary: return TRUE; case WGL_Expr::Cond: { WGL_CondExpr *cond_expr = static_cast<WGL_CondExpr *>(e); return IsScalarOrVecMat(cond_expr->arg2, FALSE); } default: return FALSE; } } /* static */ BOOL WGL_ValidateShader::IsRecursivelyCalling(WGL_Context *context, List<WGL_VariableUse> &visited, WGL_VarName *f, WGL_VarName *call) { if (!WGL_VariableUse::IsIn(visited, call)) if (WGL_FunctionData *fun_data = context->GetValidationState().LookupFunction(call)) for (WGL_FunctionDecl *decl = fun_data->decls.First(); decl; decl = decl->Suc()) if (decl->callers && WGL_VariableUse::IsIn(*decl->callers, f)) return TRUE; else if (decl->callers) { WGL_VariableUse *call_use = OP_NEWGRO_L(WGL_VariableUse, (call), context->Arena()); call_use->Into(&visited); for (WGL_VariableUse *g = (*decl->callers).First(); g; g = g->Suc()) if (IsRecursivelyCalling(context, visited, f, g->var)) return TRUE; else if (!WGL_VariableUse::IsIn(visited, g->var)) { WGL_VariableUse *g_use = OP_NEWGRO_L(WGL_VariableUse, (g->var), context->Arena()); g_use->Into(&visited); } } return FALSE; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_CallExpr *e) { switch (e->fun->GetType()) { case WGL_Expr::TypeConstructor: { WGL_Type *ctor_type = static_cast<WGL_TypeConstructorExpr *>(e->fun)->constructor; switch (ctor_type->GetType()) { case WGL_Type::Basic: { WGL_BasicType *basic_type = static_cast<WGL_BasicType *>(ctor_type); switch (basic_type->type) { case WGL_BasicType::Int: case WGL_BasicType::Float: case WGL_BasicType::Bool: if (!e->args || e->args->list.Cardinal() != 1 || !IsScalarOrVecMat(e->args->list.First(), FALSE)) context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); break; default: context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); break; } break; } case WGL_Type::Array: { if (!e->args || !IsScalarOrVecMat(e, FALSE)) context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); /* Check and update with array size. */ WGL_ArrayType *arr_type = static_cast<WGL_ArrayType *>(ctor_type); if (arr_type->length) { int val; BOOL success = context->GetValidationState(). LiteralToInt(context->GetValidationState().EvalConstExpression(arr_type->length), val); if (success) if (e->args->list.Cardinal() != static_cast<unsigned>(val)) context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); /* Other errors are not of interest right here. */ } else arr_type->length = context->GetASTBuilder()->BuildIntLit(e->args->list.Cardinal()); break; } case WGL_Type::Vector: if (!e->args || !IsScalarOrVecMat(e, FALSE)) context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); break; case WGL_Type::Matrix: if (!e->args || !IsScalarOrVecMat(e, FALSE)) context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); break; case WGL_Type::Name: { WGL_NameType *const name_type = static_cast<WGL_NameType *>(ctor_type); WGL_Type *const type = context->GetValidationState().LookupTypeName(name_type->name); if (!type) { context->AddError(WGL_Error::UNKNOWN_TYPE, Storage(context, name_type->name)); break; } if (type->GetType() != WGL_Type::Struct) { context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); break; } WGL_StructType *struct_type = static_cast<WGL_StructType *>(type); if (!(struct_type->fields && e->args && struct_type->fields->list.Cardinal() == e->args->list.Cardinal())) { context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); break; } /* Matching number of arguments and fields */ WGL_Expr *arg = e->args->list.First(); for (WGL_Field *f = struct_type->fields->list.First(); f; f = f->Suc(), arg = arg->Suc()) if (!context->GetValidationState().HasExpressionType(f->type, arg, TRUE)) context->AddError(WGL_Error::INVALID_CONSTRUCTOR_ARG, UNI_L("")); break; } default: /* Sampler, Struct and Array. */ context->AddError(WGL_Error::INVALID_TYPE_CONSTRUCTOR, UNI_L("")); break; } break; } case WGL_Expr::Var: { WGL_VarExpr *fun = static_cast<WGL_VarExpr *>(e->fun); if (context->GetValidationState().CurrentFunction() != NULL) if (context->GetValidationState().CurrentFunction()->Equals(fun->name)) context->AddError(WGL_Error::ILLEGAL_RECURSIVE_CALL, Storage(context, fun->name)); else { /* Check if CurrentFunction() is called by 'fun'. */ List<WGL_VariableUse> visited; WGL_VarName *current_function = context->GetValidationState().CurrentFunction(); if (IsRecursivelyCalling(context, visited, current_function, fun->name)) context->AddError(WGL_Error::ILLEGAL_RECURSIVE_CALL, Storage(context, fun->name)); /* Avoid triggering an assert in Head::~Head() - see CORE-43794. */ #ifdef _DEBUG visited.RemoveAll(); #endif // _DEBUG } BOOL matches = FALSE; BOOL seen_match_cand = FALSE; if (WGL_FunctionData *fun_data = context->GetValidationState().LookupFunction(fun->name)) { context->GetValidationState().AddFunctionCall(fun->name); seen_match_cand = TRUE; for (WGL_FunctionDecl *fun_decl = fun_data->decls.First(); fun_decl; fun_decl = fun_decl->Suc()) { if ((!e->args || e->args->list.Empty()) && fun_decl->parameters->list.Empty()) { matches = TRUE; break; } else if (e->args->list.Cardinal() == fun_decl->parameters->list.Cardinal()) { WGL_Expr *arg = e->args->list.First(); BOOL decl_match = TRUE; for (WGL_Param *p = fun_decl->parameters->list.First(); p; p = p->Suc()) { WGL_Type *param_type = p->type; if (param_type && param_type->GetType() == WGL_Type::Name) { WGL_NameType *name_type = static_cast<WGL_NameType *>(param_type); if (WGL_Type *t = context->GetValidationState().LookupTypeName(name_type->name)) param_type = t; } if (!context->GetValidationState().HasExpressionType(param_type, arg, TRUE)) { decl_match = FALSE; break; } arg = arg->Suc(); } if (decl_match) { matches = TRUE; WGL_Expr *arg = e->args->list.First(); for (WGL_Param *p = fun_decl->parameters->list.First(); p; p = p->Suc()) { if (p->direction >= WGL_Param::Out && !context->GetValidationState().IsLegalReferenceArg(arg)) context->AddError(WGL_Error::ILLEGAL_REFERENCE_ARGUMENT, Storage(context, p->name)); arg = arg->Suc(); } break; } } } } if (!matches) { if (List<WGL_Builtin> *builtin_decls = context->GetValidationState().LookupBuiltin(fun->name)) { if (WGL_BuiltinFun *f = context->GetValidationState().ResolveBuiltinFunction(builtin_decls, e->args)) { fun->intrinsic = f->intrinsic; matches = TRUE; } else context->AddError(WGL_Error::MISMATCHED_FUNCTION_APPLICATION, Storage(context, fun->name)); } else if (!seen_match_cand) context->AddError(WGL_Error::UNKNOWN_VAR, Storage(context, fun->name)); } if (!matches && seen_match_cand) context->AddError(WGL_Error::MISMATCHED_FUNCTION_APPLICATION, UNI_L("")); break; } default: context->AddError(WGL_Error::INVALID_CALL_EXPR, UNI_L("")); break; } if (e->args && e->fun) { e->fun = e->fun->VisitExpr(this); e->args = e->args->VisitExprList(this); context->GetValidationState().GetExpressionType(e); } return e; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_IndexExpr *e) { e->array = e->array->VisitExpr(this); WGL_Type *type = context->GetValidationState().GetExpressionType(e->array); if (!e->index || !type) { context->AddError(WGL_Error::ILLEGAL_INDEX_EXPR, UNI_L("")); return e; } e->index = e->index->VisitExpr(this); BOOL is_constant = context->GetValidationState().IsConstantExpression(e->index); if (is_constant) { if (type->GetType() == WGL_Type::Array) { WGL_ArrayType *array_type = static_cast<WGL_ArrayType *>(type); int size_array = 0; int index_val = 0; BOOL success = context->GetValidationState().LiteralToInt(context->GetValidationState().EvalConstExpression(array_type->length), size_array); success = success && context->GetValidationState().LiteralToInt(context->GetValidationState().EvalConstExpression(e->index), index_val); is_constant = success; if (success && index_val >= size_array) context->AddError(WGL_Error::INDEX_OUT_OF_BOUNDS_ARRAY, UNI_L("")); } else if (type->GetType() == WGL_Type::Vector) { unsigned size_vector = WGL_VectorType::GetMagnitude(static_cast<WGL_VectorType *>(type)); int index_val = 0; if (context->GetValidationState().LiteralToInt(context->GetValidationState().EvalConstExpression(e->index), index_val)) { if (static_cast<unsigned>(index_val) >= size_vector) context->AddError(WGL_Error::INDEX_OUT_OF_BOUNDS_VECTOR, UNI_L("")); } else is_constant = FALSE; } } if (!is_constant && !IsVertexShader() && context->GetConfiguration() && context->GetConfiguration()->fragment_shader_constant_uniform_array_indexing) { if (type->type_qualifier && type->type_qualifier->storage == WGL_TypeQualifier::Uniform) context->AddError(WGL_Error::INDEX_NON_CONSTANT_FRAGMENT, UNI_L("")); } if (!is_constant && context->GetConfiguration() && context->GetConfiguration()->clamp_out_of_bound_uniform_array_indexing) { if ((type->GetType() == WGL_Type::Array || type->GetType() == WGL_Type::Vector) && type->type_qualifier && type->type_qualifier->storage == WGL_TypeQualifier::Uniform) { unsigned mag = 0; if (type->GetType() == WGL_Type::Array) { type = context->GetValidationState().NormaliseType(type); if (type->GetType() == WGL_Type::Array) { WGL_ArrayType *array_type = static_cast<WGL_ArrayType *>(type); if (array_type->is_constant_value) mag = array_type->length_value; } } else if (type->GetType() == WGL_Type::Vector) mag = WGL_VectorType::GetMagnitude(static_cast<WGL_VectorType *>(type)); if (mag > 0) { WGL_Expr *fun = context->GetASTBuilder()->BuildIdentifier(WGL_String::Make(context, UNI_L("webgl_op_clamp"))); WGL_Expr *lit_max = context->GetASTBuilder()->BuildIntLit(mag - 1); WGL_ExprList *args = context->GetASTBuilder()->NewExprList(); e->index->Into(&args->list); lit_max->Into(&args->list); WGL_Expr *clamp = context->GetASTBuilder()->BuildCallExpression(fun, args); e->index = clamp; context->SetUsedClamp(); } } } context->GetValidationState().GetExpressionType(e); return e; } static int GetVectorSelectorKind(uni_char ch) { if (ch == 'r' || ch == 'g' || ch == 'b' || ch == 'a') return 1; else if (ch == 'x' || ch == 'y' || ch == 'z' || ch == 'w') return 2; else if (ch == 's' || ch == 't' || ch == 'p' || ch == 'q') return 3; else return 0; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_SelectExpr *e) { e->value = e->value->VisitExpr(this); WGL_Type *t = context->GetValidationState().GetExpressionType(e->value); if (!t) { context->AddError(WGL_Error::ILLEGAL_SELECT_EXPR, UNI_L("")); return e; } switch (t->GetType()) { case WGL_Type::Struct: { WGL_StructType *struct_type = static_cast<WGL_StructType *>(t); if (!context->GetValidationState().LookupField(struct_type->fields, e->field)) context->AddError(WGL_Error::UNKNOWN_FIELD, Storage(context, e->field)); return e; } case WGL_Type::Vector: { WGL_VectorType *vec_type = static_cast<WGL_VectorType *>(t); if (e->field->Equals(UNI_L("x")) || e->field->Equals(UNI_L("r")) || e->field->Equals(UNI_L("s"))) break; switch (vec_type->type) { case WGL_VectorType::Vec4: case WGL_VectorType::BVec4: case WGL_VectorType::IVec4: case WGL_VectorType::UVec4: if (e->field->Equals(UNI_L("w")) || e->field->Equals(UNI_L("a")) || e->field->Equals(UNI_L("q"))) break; case WGL_VectorType::Vec3: case WGL_VectorType::BVec3: case WGL_VectorType::IVec3: case WGL_VectorType::UVec3: if (e->field->Equals(UNI_L("z")) || e->field->Equals(UNI_L("b")) || e->field->Equals(UNI_L("p"))) break; case WGL_VectorType::Vec2: case WGL_VectorType::BVec2: case WGL_VectorType::IVec2: case WGL_VectorType::UVec2: if (e->field->Equals(UNI_L("y")) || e->field->Equals(UNI_L("g")) || e->field->Equals(UNI_L("t"))) break; else { const uni_char *str = Storage(context, e->field); unsigned len = static_cast<unsigned>(uni_strlen(str)); if (len <= 1 || len > 4) { context->AddError(WGL_Error::UNKNOWN_VAR, str); return e; } int sel_kind_1 = GetVectorSelectorKind(str[0]); int sel_kind_2 = GetVectorSelectorKind(str[1]); int sel_kind_3 = len >= 3 ? GetVectorSelectorKind(str[2]) : -1; int sel_kind_4 = len >= 4 ? GetVectorSelectorKind(str[3]) : -1; if (sel_kind_1 == 0 || sel_kind_1 != sel_kind_2 || sel_kind_3 != -1 && sel_kind_3 != sel_kind_1 || sel_kind_4 != -1 && sel_kind_4 != sel_kind_1) { if (sel_kind_1 == 0 || sel_kind_2 == 0 || sel_kind_3 == 0 || sel_kind_4 == 0) context->AddError(WGL_Error::UNKNOWN_VECTOR_SELECTOR, str); else context->AddError(WGL_Error::ILLEGAL_VECTOR_SELECTOR, str); } break; } default: context->AddError(WGL_Error::UNKNOWN_VAR, Storage(context, e->field)); return NULL; } } } context->GetValidationState().GetExpressionType(e); return e; } /* virtual */ WGL_Expr * WGL_ValidateShader::VisitExpr(WGL_AssignExpr *e) { /* An lhs expression is required. */ if (!e->lhs) { context->AddError(WGL_Error::INVALID_LVALUE, UNI_L("")); return e; } e->lhs = e->lhs->VisitExpr(this); if (e->rhs) e->rhs = e->rhs->VisitExpr(this); if (e->lhs->GetType() == WGL_Expr::Var) { WGL_VarExpr *var_expr = static_cast<WGL_VarExpr *>(e->lhs); if (WGL_VarBinding *binding = context->GetValidationState().LookupVarBinding(var_expr->name)) { if (binding->is_read_only || binding->type->type_qualifier && (binding->type->type_qualifier->storage == WGL_TypeQualifier::Const || binding->type->type_qualifier->storage == WGL_TypeQualifier::Uniform)) context->AddError(WGL_Error::ILLEGAL_VAR_NOT_WRITEABLE, Storage(context, var_expr->name)); } else if (List <WGL_Builtin> *builtin = context->GetValidationState().LookupBuiltin(var_expr->name)) { WGL_BuiltinVar *bvar = builtin->First()->IsBuiltinVar() ? static_cast<WGL_BuiltinVar *>(builtin->First()) : NULL; if (!bvar || bvar->is_read_only || bvar->is_const) context->AddError(WGL_Error::ILLEGAL_VAR_NOT_WRITEABLE, Storage(context, var_expr->name)); } else if (context->GetValidationState().LookupUniform(var_expr->name)) context->AddError(WGL_Error::ILLEGAL_VAR_NOT_WRITEABLE, Storage(context, var_expr->name)); else if (!IsVertexShader() && context->GetValidationState().LookupVarying(var_expr->name)) context->AddError(WGL_Error::ILLEGAL_VARYING_VAR_NOT_WRITEABLE, Storage(context, var_expr->name)); WGL_Type *t1 = context->GetValidationState().GetExpressionType(e->lhs); WGL_Type *t2 = context->GetValidationState().GetExpressionType(e->rhs); if (t1 && t2) { if (e->op != WGL_Expr::OpAssign) CheckBinaryExpr(e->op, t1, t2); else if (!context->GetValidationState().IsSameType(t1, t2, TRUE)) context->AddError(WGL_Error::TYPE_MISMATCH, UNI_L("")); } } context->GetValidationState().GetExpressionType(e); return e; } /** -- Stmt visitors -- */ /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_SwitchStmt *s) { context->SetLineNumber(s->line_number); s->scrutinee = s->scrutinee->VisitExpr(this); s->cases = s->cases->VisitStmtList(this); /* Static checking / validation */ for (WGL_Stmt *c = s->cases->list.First(); c; c = c->Suc()) if (c->GetType() == WGL_Stmt::Simple) switch ((static_cast<WGL_SimpleStmt *>(c))->type) { case WGL_SimpleStmt::Continue: case WGL_SimpleStmt::Discard: context->AddError(WGL_Error::INVALID_STMT, UNI_L("expected 'case' or 'default'")); break; } else context->AddError(WGL_Error::INVALID_STMT, UNI_L("expected 'case' or 'default'")); return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_SimpleStmt *s) { context->SetLineNumber(s->line_number); switch (s->type) { case WGL_SimpleStmt::Empty: case WGL_SimpleStmt::Default: case WGL_SimpleStmt::Break: case WGL_SimpleStmt::Continue: /* TODO: eventually track if we are in an appropriate context for these and issue warnings if not. */ break; case WGL_SimpleStmt::Discard: if (IsVertexShader()) context->AddError(WGL_Error::ILLEGAL_DISCARD_STMT, UNI_L("")); break; default: OP_ASSERT(!"Unhandled simple statement"); break; } return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_BodyStmt *s) { context->SetLineNumber(s->line_number); context->EnterLocalScope(NULL); s->body = s->body->VisitStmtList(this); context->LeaveLocalScope(); return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_WhileStmt *s) { context->SetLineNumber(s->line_number); s->condition = s->condition->VisitExpr(this); WGL_Type *cond_type = context->GetValidationState().GetExpressionType(s->condition); if (cond_type && !WGL_Type::HasBasicType(cond_type, WGL_BasicType::Bool)) context->AddError(WGL_Error::INVALID_PREDICATE_TYPE, UNI_L("")); s->body = s->body->VisitStmt(this); return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_DoStmt *s) { context->SetLineNumber(s->line_number); s->body = s->body->VisitStmt(this); s->condition = s->condition->VisitExpr(this); WGL_Type *cond_type = context->GetValidationState().GetExpressionType(s->condition); if (cond_type && !WGL_Type::HasBasicType(cond_type, WGL_BasicType::Bool)) context->AddError(WGL_Error::INVALID_PREDICATE_TYPE, UNI_L("")); return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_IfStmt *s) { context->SetLineNumber(s->line_number); s->predicate = s->predicate->VisitExpr(this); WGL_Type *pred_type = context->GetValidationState().GetExpressionType(s->predicate); if (pred_type && !WGL_Type::HasBasicType(pred_type, WGL_BasicType::Bool)) context->AddError(WGL_Error::INVALID_IF_PRED, UNI_L("")); s->then_part = s->then_part->VisitStmt(this); if (s->else_part) s->else_part = s->else_part->VisitStmt(this); return s; } static WGL_Expr::Operator ReverseOperator(WGL_Expr::Operator op) { switch (op) { case WGL_Expr::OpLt: return WGL_Expr::OpGt; case WGL_Expr::OpLe: return WGL_Expr::OpGe; case WGL_Expr::OpEq: return WGL_Expr::OpEq; case WGL_Expr::OpNEq: return WGL_Expr::OpNEq; case WGL_Expr::OpGe: return WGL_Expr::OpLe; case WGL_Expr::OpGt: return WGL_Expr::OpLt; default: OP_ASSERT(!"Unexpected relational operator"); return WGL_Expr::OpEq; } } static BOOL IsLoopVariableType(WGL_Type *type) { return WGL_Type::HasBasicType(type, WGL_BasicType::Int | WGL_BasicType::Float | WGL_BasicType::UInt); } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_ForStmt *s) { context->SetLineNumber(s->line_number); context->EnterLocalScope(NULL); s->head = s->head->VisitStmt(this); /* GLSL, Appendix A (4 Control flow) */ WGL_VarName *loop_index = NULL; BOOL invalid_loop_declaration = TRUE; WGL_Literal *loop_initialiser = NULL; switch (s->head->GetType()) { case WGL_Stmt::StmtDecl: { WGL_DeclStmt *decl = static_cast<WGL_DeclStmt *>(s->head); if (WGL_VarDecl *var_decl = decl->decls.First()->GetType() == WGL_Decl::Var ? static_cast<WGL_VarDecl *>(decl->decls.First()) : NULL) if (IsLoopVariableType(var_decl->type) && context->GetValidationState().IsConstantExpression(var_decl->initialiser)) { loop_index = var_decl->identifier; loop_initialiser = context->GetValidationState().EvalConstExpression(var_decl->initialiser); invalid_loop_declaration = decl->decls.First()->Suc() != NULL || loop_initialiser == NULL; } break; } case WGL_Stmt::StmtExpr: { WGL_ExprStmt *expr_stmt = static_cast<WGL_ExprStmt *>(s->head); if (expr_stmt->expr->GetType() == WGL_Expr::Assign) { WGL_AssignExpr *assign_expr = static_cast<WGL_AssignExpr *>(expr_stmt->expr); if (assign_expr->op == WGL_Expr::OpAssign && assign_expr->lhs->GetType() == WGL_Expr::Var) { WGL_VarExpr *var_expr = static_cast<WGL_VarExpr *>(assign_expr->lhs); if (WGL_Type *type = context->GetValidationState().LookupLocalVar(var_expr->name)) if (IsLoopVariableType(type) && context->GetValidationState().IsConstantExpression(assign_expr->rhs)) { loop_index = var_expr->name; loop_initialiser = context->GetValidationState().EvalConstExpression(assign_expr->rhs); invalid_loop_declaration = loop_initialiser == NULL; } } } break; } default: break; } if (invalid_loop_declaration) context->AddError(WGL_Error::INVALID_LOOP_HEADER, loop_index ? Storage(context, loop_index) : UNI_L("for")); s->predicate = s->predicate->VisitExpr(this); if (s->update) s->update = s->update->VisitExpr(this); if (WGL_VarBinding *bind = loop_index ? context->GetValidationState().LookupVarBinding(loop_index) : NULL) { bind->is_read_only = TRUE; bind->value = NULL; } s->body = s->body->VisitStmt(this); context->LeaveLocalScope(); BOOL invalid_loop_condition = TRUE; WGL_Expr::Operator boundary_op = WGL_Expr::OpBase; WGL_Literal *loop_limit = NULL; if (WGL_BinaryExpr *condition = s->predicate->GetType() == WGL_Expr::Binary ? static_cast<WGL_BinaryExpr *>(s->predicate) : NULL) if (condition->op >= WGL_Expr::OpEq && condition->op <= WGL_Expr::OpGe) if (WGL_VarExpr *var_expr = condition->arg1->GetType() == WGL_Expr::Var ? static_cast<WGL_VarExpr *>(condition->arg1) : NULL) { if (loop_index && uni_strcmp(Storage(context, var_expr->name), Storage(context, loop_index)) == 0) { if (context->GetValidationState().IsConstantExpression(condition->arg2)) { boundary_op = condition->op; loop_limit = context->GetValidationState().EvalConstExpression(condition->arg2); invalid_loop_condition = FALSE; } } } else if (WGL_VarExpr *var_expr = condition->arg2->GetType() == WGL_Expr::Var ? static_cast<WGL_VarExpr *>(condition->arg2) : NULL) if (loop_index && uni_strcmp(Storage(context, var_expr->name), Storage(context, loop_index)) == 0) if (context->GetValidationState().IsConstantExpression(condition->arg1)) { boundary_op = ReverseOperator(condition->op); loop_limit = context->GetValidationState().EvalConstExpression(condition->arg1); invalid_loop_condition = FALSE; } if (invalid_loop_condition) context->AddError(WGL_Error::INVALID_LOOP_CONDITION, loop_index ? Storage(context, loop_index) : UNI_L("")); if (!s->update) { context->AddError(WGL_Error::MISSING_LOOP_UPDATE, loop_index ? Storage(context, loop_index) : UNI_L("")); return s; } BOOL invalid_update = TRUE; double update_delta = 0; WGL_Error::Type update_error = WGL_Error::INVALID_LOOP_UPDATE; if (WGL_PostExpr *e = s->update->GetType() == WGL_Expr::PostOp ? static_cast<WGL_PostExpr *>(s->update) : NULL) { if (e->op == WGL_Expr::OpPostInc || e->op == WGL_Expr::OpPostDec) if (WGL_VarExpr *var_expr = e->arg->GetType() == WGL_Expr::Var ? static_cast<WGL_VarExpr *>(e->arg) : NULL) if (loop_index && uni_strcmp(Storage(context, loop_index), Storage(context, var_expr->name)) == 0) { update_delta = e->op == WGL_Expr::OpPostInc ? 1.0 : (-1.0); invalid_update = FALSE; } } else if (WGL_UnaryExpr *e = s->update->GetType() == WGL_Expr::Unary ? static_cast<WGL_UnaryExpr *>(s->update) : NULL) { if (e->op == WGL_Expr::OpPreInc || e->op == WGL_Expr::OpPreDec) if (WGL_VarExpr *var_expr = e->arg->GetType() == WGL_Expr::Var ? static_cast<WGL_VarExpr *>(e->arg) : NULL) if (loop_index && uni_strcmp(Storage(context, loop_index), Storage(context, var_expr->name)) == 0) { update_delta = e->op == WGL_Expr::OpPreInc ? 1.0 : (-1.0); invalid_update = FALSE; } } else if (WGL_AssignExpr *assign_expr = s->update->GetType() == WGL_Expr::Assign ? static_cast<WGL_AssignExpr *>(s->update) : NULL) { if (assign_expr->op == WGL_Expr::OpAdd || assign_expr->op == WGL_Expr::OpSub) if (WGL_VarExpr *var_expr = assign_expr->lhs->GetType() == WGL_Expr::Var ? static_cast<WGL_VarExpr *>(assign_expr->lhs) : NULL) if (loop_index && uni_str_eq(Storage(context, loop_index), Storage(context, var_expr->name))) if (context->GetValidationState().IsConstantExpression(assign_expr->rhs)) { if (WGL_Literal *l = context->GetValidationState().EvalConstExpression(assign_expr->rhs)) { if (WGL_Type::HasBasicType(assign_expr->lhs->GetExprType(), WGL_BasicType::Float)) { WGL_Literal::Value lv = WGL_Literal::ToDouble(l->type, l->value); update_delta = assign_expr->op == WGL_Expr::OpAdd ? lv.d.value : (-lv.d.value); } else { WGL_Literal::Value lv = WGL_Literal::ToInt(l->type, l->value); update_delta = assign_expr->op == WGL_Expr::OpAdd ? lv.i : (-lv.i); } if (update_delta != 0) invalid_update = FALSE; else update_error = WGL_Error::INVALID_LOOP_NONTERMINATION; } } } if (invalid_update) { context->AddError(update_error, loop_index ? Storage(context, loop_index) : UNI_L("")); return s; } if (loop_limit && loop_initialiser) { WGL_Literal::Value c1 = WGL_Literal::ToDouble(loop_initialiser->type, loop_initialiser->value); WGL_Literal::Value c2 = WGL_Literal::ToDouble(loop_limit->type, loop_limit->value); BOOL is_illegal = TRUE; if (c1.d.value < c2.d.value) { switch (boundary_op) { case WGL_Expr::OpLt: case WGL_Expr::OpLe: case WGL_Expr::OpNEq: is_illegal = update_delta <= 0; break; case WGL_Expr::OpEq: case WGL_Expr::OpGe: case WGL_Expr::OpGt: is_illegal = FALSE; break; default: /* Unknown operator, treat as illegal. */ break; } } else if (c1.d.value == c2.d.value) { switch (boundary_op) { case WGL_Expr::OpLt: case WGL_Expr::OpGt: case WGL_Expr::OpNEq: is_illegal = FALSE; break; case WGL_Expr::OpLe: case WGL_Expr::OpEq: case WGL_Expr::OpGe: is_illegal = update_delta == 0; break; default: /* Unknown operator, treat as illegal. */ break; } } else /* c1.d.value > c2.d.value */ { switch (boundary_op) { case WGL_Expr::OpLt: case WGL_Expr::OpLe: case WGL_Expr::OpEq: is_illegal = FALSE; break; case WGL_Expr::OpGe: case WGL_Expr::OpGt: case WGL_Expr::OpNEq: is_illegal = update_delta >= 0; default: /* Unknown operator, treat as illegal. */ break; } } if (is_illegal) context->AddError(WGL_Error::INVALID_LOOP_NONTERMINATION, loop_index ? Storage(context, loop_index) : UNI_L("")); } return s; } WGL_Literal * WGL_ValidationState::EvalConstExpression(WGL_Expr::Operator op, WGL_Literal::Type t1, WGL_Literal::Value v1, WGL_Literal::Type t2, WGL_Literal::Value v2) { if (t1 == t2) { switch (t1) { case WGL_Literal::Double: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Double); switch (op) { case WGL_Expr::OpMul: n->value.d.value = v1.d.value * v2.d.value; break; case WGL_Expr::OpDiv: n->value.d.value = v1.d.value / v2.d.value; break; case WGL_Expr::OpAdd: n->value.d.value = v1.d.value + v2.d.value; break; case WGL_Expr::OpSub: n->value.d.value = v1.d.value - v2.d.value; break; case WGL_Expr::OpLt: n->type = WGL_Literal::Bool; n->value.b = v1.d.value < v2.d.value; break; case WGL_Expr::OpLe: n->type = WGL_Literal::Bool; n->value.b = v1.d.value <= v2.d.value; break; case WGL_Expr::OpEq: n->type = WGL_Literal::Bool; n->value.b = v1.d.value == v2.d.value; break; case WGL_Expr::OpNEq: n->type = WGL_Literal::Bool; n->value.b = v1.d.value != v2.d.value; break; case WGL_Expr::OpGe: n->type = WGL_Literal::Bool; n->value.b = v1.d.value >= v2.d.value; break; case WGL_Expr::OpGt: n->type = WGL_Literal::Bool; n->value.b = v1.d.value > v2.d.value; break; case WGL_Expr::OpAnd: n->type = WGL_Literal::Bool; n->value.b = static_cast<unsigned>(v1.d.value) && static_cast<unsigned>(v2.d.value); break; case WGL_Expr::OpXor: n->type = WGL_Literal::Bool; n->value.b = (static_cast<unsigned>(v1.d.value) || static_cast<unsigned>(v2.d.value)) && !(static_cast<unsigned>(v1.d.value) && static_cast<unsigned>(v2.d.value)); break; case WGL_Expr::OpOr: n->type = WGL_Literal::Bool; n->value.b = static_cast<unsigned>(v1.d.value) || static_cast<unsigned>(v2.d.value); break; } return n; } case WGL_Literal::Int: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Int); switch (op) { case WGL_Expr::OpMul: n->value.i = v1.i * v2.i; break; case WGL_Expr::OpDiv: n->value.i = (v2.i != 0) ? (v1.i / v2.i) : 0; break; case WGL_Expr::OpAdd: n->value.i = v1.i + v2.i; break; case WGL_Expr::OpSub: n->value.i = v1.i - v2.i; break; case WGL_Expr::OpLt: n->type = WGL_Literal::Bool; n->value.b = v1.i < v2.i; break; case WGL_Expr::OpLe: n->type = WGL_Literal::Bool; n->value.b = v1.i <= v2.i; break; case WGL_Expr::OpEq: n->type = WGL_Literal::Bool; n->value.b = v1.i == v2.i; break; case WGL_Expr::OpNEq: n->type = WGL_Literal::Bool; n->value.b = v1.i != v2.i; break; case WGL_Expr::OpGe: n->type = WGL_Literal::Bool; n->value.b = v1.i >= v2.i; break; case WGL_Expr::OpGt: n->type = WGL_Literal::Bool; n->value.b = v1.i > v2.i; break; case WGL_Expr::OpAnd: n->type = WGL_Literal::Bool; n->value.b = v1.i && v2.i; break; case WGL_Expr::OpXor: n->type = WGL_Literal::Bool; n->value.b = (v1.i || v2.i) && !(v1.i && v2.i); break; case WGL_Expr::OpOr: n->type = WGL_Literal::Bool; n->value.b = v1.i || v2.i; break; } return n; } case WGL_Literal::UInt: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::UInt); switch (op) { case WGL_Expr::OpMul: n->value.u_int = v1.u_int * v2.u_int; break; case WGL_Expr::OpDiv: n->value.u_int = v2.u_int != 0 ? (v1.u_int / v2.u_int) : 0; break; case WGL_Expr::OpAdd: n->value.u_int = v1.u_int + v2.u_int; break; case WGL_Expr::OpSub: n->value.u_int = v1.u_int - v2.u_int; break; case WGL_Expr::OpLt: n->type = WGL_Literal::Bool; n->value.b = v1.u_int < v2.u_int; break; case WGL_Expr::OpLe: n->type = WGL_Literal::Bool; n->value.b = v1.u_int <= v2.u_int; break; case WGL_Expr::OpEq: n->type = WGL_Literal::Bool; n->value.b = v1.u_int == v2.u_int; break; case WGL_Expr::OpNEq: n->type = WGL_Literal::Bool; n->value.b = v1.u_int != v2.u_int; break; case WGL_Expr::OpGe: n->type = WGL_Literal::Bool; n->value.b = v1.u_int >= v2.u_int; break; case WGL_Expr::OpGt: n->type = WGL_Literal::Bool; n->value.b = v1.u_int > v2.u_int; break; case WGL_Expr::OpAnd: n->type = WGL_Literal::Bool; n->value.b = v1.u_int && v2.u_int; break; case WGL_Expr::OpXor: n->type = WGL_Literal::Bool; n->value.b = (v1.u_int || v2.u_int) && !(v1.u_int && v2.u_int); break; case WGL_Expr::OpOr: n->type = WGL_Literal::Bool; n->value.b = v1.u_int || v2.u_int; break; } return n; } case WGL_Literal::Bool: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Bool); switch (op) { case WGL_Expr::OpMul: n->value.b = v1.b && v2.b; break; case WGL_Expr::OpDiv: n->value.b = v1.b && v2.b; break; case WGL_Expr::OpAdd: n->value.b = v1.b || v2.b; break; case WGL_Expr::OpSub: n->value.b = v1.b || v2.b; break; case WGL_Expr::OpLt: n->value.b = v1.b < v2.b; break; case WGL_Expr::OpLe: n->value.b = v1.b <= v2.b; break; case WGL_Expr::OpEq: n->value.b = v1.b == v2.b; break; case WGL_Expr::OpNEq: n->value.b = v1.b != v2.b; break; case WGL_Expr::OpGe: n->value.b = v1.b >= v2.b; break; case WGL_Expr::OpGt: n->value.b = v1.b > v2.b; break; case WGL_Expr::OpAnd: n->value.b = v1.b && v2.b; break; case WGL_Expr::OpXor: n->value.b = (v1.b || v2.b) && !(v1.b && v2.b); break; case WGL_Expr::OpOr: n->value.b = v1.b || v2.b; break; } return n; } default: OP_ASSERT(0); case WGL_Literal::String: /* The language does not support them, so little point padding this out.. */ return NULL; } } else if (t1 == WGL_Literal::Double || t2 == WGL_Literal::Double) return EvalConstExpression(op, WGL_Literal::Double, WGL_Literal::ToDouble(t1, v1), WGL_Literal::Double, WGL_Literal::ToDouble(t2, v2)); else if (t1 == WGL_Literal::UInt || t2 == WGL_Literal::UInt) return EvalConstExpression(op, WGL_Literal::UInt, WGL_Literal::ToUnsignedInt(t1, v1), WGL_Literal::UInt, WGL_Literal::ToUnsignedInt(t2, v2)); else if (t1 == WGL_Literal::Int || t2 == WGL_Literal::Int) return EvalConstExpression(op, WGL_Literal::Int, WGL_Literal::ToInt(t1, v1), WGL_Literal::Int, WGL_Literal::ToInt(t2, v2)); else if (t1 == WGL_Literal::Bool || t2 == WGL_Literal::Bool) return EvalConstExpression(op, WGL_Literal::Bool, WGL_Literal::ToBool(t1, v1), WGL_Literal::Bool, WGL_Literal::ToBool(t2, v2)); else return NULL; } WGL_BuiltinFun * WGL_ValidationState::ResolveBuiltinFunction(List<WGL_Builtin> *builtins, WGL_ExprList *args) { for (WGL_Builtin *builtin = builtins->First(); builtin; builtin = builtin->Suc()) { if (builtin->IsBuiltinVar()) continue; WGL_BuiltinFun *fun = static_cast<WGL_BuiltinFun *>(builtin); if ((!args || args->list.Empty()) && fun->parameters.Empty()) return fun; else if (args->list.Cardinal() == fun->parameters.Cardinal()) { WGL_Expr *arg = args->list.First(); BOOL decl_match = TRUE; for (WGL_BuiltinType *p = fun->parameters.First(); p; p = p->Suc()) { WGL_Type *arg_type = GetExpressionType(arg); if (!arg_type) return NULL; if (arg_type && !MatchesBuiltinType(p, arg_type)) { decl_match = FALSE; break; } arg = arg->Suc(); } if (decl_match) return fun; } } return NULL; } WGL_Type * WGL_ValidationState::ResolveBuiltinReturnType(WGL_BuiltinFun *fun, WGL_ExprList *args, WGL_Type *arg1_type) { /* Concrete type; return type is derivable without considering argument types. */ if (fun->return_type->type <= WGL_BuiltinType::Sampler) return FromBuiltinType(fun->return_type); /* Resolve the instance type of a generic builtin return type. Generically-typed builtins are mostly regular in that the return type is equal to that of the argument type(s). The relational intrinsics over vectors requires special treatment; all having bool vector types (of magnitude equal to the argument vectors.) */ switch (fun->intrinsic) { case WGL_GLSL::LessThan: case WGL_GLSL::LessThanEqual: case WGL_GLSL::GreaterThan: case WGL_GLSL::GreaterThanEqual: case WGL_GLSL::Equal: case WGL_GLSL::NotEqual: case WGL_GLSL::Any: case WGL_GLSL::All: case WGL_GLSL::Not: { OP_ASSERT(arg1_type->GetType() == WGL_Type::Vector); unsigned magnitude = WGL_VectorType::GetMagnitude(static_cast<WGL_VectorType *>(arg1_type)); WGL_VectorType::Type return_vector; if (magnitude == 2) return_vector = WGL_VectorType::BVec2; else if (magnitude == 3) return_vector = WGL_VectorType::BVec3; else { OP_ASSERT(magnitude == 4); return_vector = WGL_VectorType::BVec4; } return context->GetASTBuilder()->BuildVectorType(return_vector); } default: return arg1_type; } } #define GLSL_ABS(x) ((x) >= 0.0 ? (x) : (-(x))) #define GLSL_SIGN(x) ((x) > 0 ? 1.0 : (x) == 0 ? 0 : (-1.0)) WGL_Literal * WGL_ValidationState::EvalBuiltinFunction(WGL_VarExpr *fun, List<WGL_Builtin> *builtins, WGL_ExprList *args) { if (WGL_BuiltinFun *builtin = ResolveBuiltinFunction(builtins, args)) { WGL_BuiltinType *arg1 = builtin->parameters.First(); WGL_BuiltinType *arg2 = arg1 ? arg1->Suc() : NULL; WGL_Literal *l = EvalConstExpression(args->list.First()); if (!l) return NULL; if (builtin->arity == 1 && builtin->return_type->type == WGL_BuiltinType::Gen && arg1->type == WGL_BuiltinType::Gen) { switch (builtin->intrinsic) { case WGL_GLSL::Sign: case WGL_GLSL::Abs: break; default: return NULL; } switch (l->type) { case WGL_Literal::Double: { WGL_Literal *result = context->BuildLiteral(l->type); switch (builtin->intrinsic) { case WGL_GLSL::Sign: result->value.d.value = GLSL_SIGN(l->value.d.value); break; case WGL_GLSL::Abs: result->value.d.value = GLSL_ABS(l->value.d.value); break; default: return NULL; } return result; } case WGL_Literal::Vector: { WGL_LiteralVector *lvec = static_cast<WGL_LiteralVector *>(l); WGL_LiteralVector *lit_vector = OP_NEWGRO_L(WGL_LiteralVector, (WGL_BasicType::Float), context->Arena()); lit_vector->size = lvec->size; lit_vector->value.doubles = OP_NEWGROA_L(double, lit_vector->size, context->Arena()); for (unsigned i = 0; i < lit_vector->size ; i++) { switch (builtin->intrinsic) { case WGL_GLSL::Sign: lit_vector->value.doubles[i] = GLSL_SIGN(lvec->value.doubles[i]); break; case WGL_GLSL::Abs: lit_vector->value.doubles[i] = GLSL_ABS(lvec->value.doubles[i]); break; default: return NULL; } } return lit_vector; } default: OP_ASSERT(!"A curious builtin application"); return NULL; } } else if (builtin->arity == 2 && builtin->return_type->type == WGL_BuiltinType::Gen && arg1->type == WGL_BuiltinType::Gen && (arg2->type == WGL_BuiltinType::Gen || arg2->type == WGL_BuiltinType::Basic && arg2->value.basic_type == WGL_BasicType::Float)) { switch (builtin->intrinsic) { case WGL_GLSL::Max: case WGL_GLSL::Min: break; default: return NULL; } switch (l->type) { case WGL_Literal::Double: { /* Know that at least one argument is constant. */ WGL_Literal *l1 = EvalConstExpression(args->list.First()); WGL_Literal *l2 = EvalConstExpression(args->list.First()->Suc()); double d1 = (-1); double d2 = (-1); BOOL success1 = LiteralToDouble(l1, d1); BOOL success2 = LiteralToDouble(l2, d2); WGL_Literal *result = context->BuildLiteral(l->type); switch (builtin->intrinsic) { case WGL_GLSL::Max: if (success1 && success2) result->value.d.value = MAX(d1, d2); else if (success1) result->value.d.value = d1; else result->value.d.value = d2; return result; case WGL_GLSL::Min: if (success1 && success2) result->value.d.value = MIN(d1, d2); else if (success1) result->value.d.value = d1; else result->value.d.value = d2; return result; default: return NULL; } } default: return NULL; } } else return NULL; } else return NULL; } WGL_Literal * WGL_ValidationState::EvalConstExpression(WGL_Expr *e) { switch (e->GetType()) { case WGL_Expr::Lit: return static_cast<WGL_LiteralExpr *>(e)->literal; case WGL_Expr::TypeConstructor: OP_ASSERT(!"Unexpected occurrence of a type constructor"); return NULL; case WGL_Expr::Var: if (WGL_VarBinding *binder = LookupVarBinding(static_cast<WGL_VarExpr *>(e)->name)) { if (binder->value) return EvalConstExpression(binder->value); } return NULL; case WGL_Expr::Call: { WGL_CallExpr *fun_call = static_cast<WGL_CallExpr *>(e); #if 0 for (WGL_Expr *arg = fun_call->args ? fun_call->args->list.First() : NULL; arg; arg = arg->Suc()) if (!IsConstantExpression(arg)) return NULL; #endif if (fun_call->fun->GetType() == WGL_Expr::Var && fun_call->args && fun_call->args->list.Cardinal() > 0) { WGL_VarExpr *f = static_cast<WGL_VarExpr *>(fun_call->fun); if (List <WGL_Builtin> *builtins = LookupBuiltin(f->name)) return EvalBuiltinFunction(f, builtins, fun_call->args); else /* This implementation does not support inlining & evaluation of local (const) functions. */ return NULL; } else if (fun_call->fun->GetType() == WGL_Expr::TypeConstructor && fun_call->args && fun_call->args->list.Cardinal() > 0) { WGL_TypeConstructorExpr *tycon_expr = static_cast<WGL_TypeConstructorExpr *>(fun_call->fun); switch (tycon_expr->constructor->GetType()) { case WGL_Type::Basic: { WGL_BasicType *basic_type = static_cast<WGL_BasicType *>(tycon_expr->constructor); WGL_Literal *l = EvalConstExpression(fun_call->args->list.First()); WGL_Literal *result = context->BuildLiteral(WGL_BasicType::ToLiteralType(basic_type->type)); switch (basic_type->type) { case WGL_BasicType::Float: { double val; if (result && LiteralToDouble(l, val)) { result->value.d.value = val; return result; } break; } case WGL_BasicType::Int: case WGL_BasicType::UInt: case WGL_BasicType::Bool: { int val; if (result && LiteralToInt(l, val)) { switch (basic_type->type) { case WGL_BasicType::UInt: result->value.u_int = static_cast<unsigned>(val); return result; case WGL_BasicType::Bool: result->value.b = val != 0; case WGL_BasicType::Int: default: result->value.i = val; return result; } } break; } } return NULL; } case WGL_Type::Vector: { WGL_VectorType *vec_type = static_cast<WGL_VectorType *>(tycon_expr->constructor); WGL_BasicType::Type element_type = WGL_VectorType::GetElementType(vec_type); WGL_LiteralVector *lit_vector = OP_NEWGRO_L(WGL_LiteralVector, (element_type), context->Arena()); lit_vector->size = fun_call->args->list.Cardinal(); switch (element_type) { case WGL_BasicType::Float: lit_vector->value.doubles = OP_NEWGROA_L(double, lit_vector->size, context->Arena()); break; case WGL_BasicType::Int: lit_vector->value.ints = OP_NEWGROA_L(int, lit_vector->size, context->Arena()); break; case WGL_BasicType::UInt: lit_vector->value.u_ints = OP_NEWGROA_L(unsigned, lit_vector->size, context->Arena()); break; case WGL_BasicType::Bool: lit_vector->value.bools = OP_NEWGROA_L(bool, lit_vector->size, context->Arena()); break; } WGL_Expr *arg = fun_call->args->list.First(); WGL_Literal *arg_lit = EvalConstExpression(arg); unsigned arg_idx = 0; for (unsigned i = 0; i < lit_vector->size; i++) { if (arg_lit->type == WGL_Literal::Vector) { WGL_LiteralVector *lit_vec = static_cast<WGL_LiteralVector *>(arg_lit); if (arg_idx < lit_vec->size) { switch (element_type) { case WGL_BasicType::Float: lit_vector->value.doubles[i] = lit_vec->value.doubles[arg_idx++]; break; case WGL_BasicType::Int: lit_vector->value.ints[i] = lit_vec->value.ints[arg_idx++]; break; case WGL_BasicType::UInt: lit_vector->value.u_ints[i] = lit_vec->value.u_ints[arg_idx++]; break; case WGL_BasicType::Bool: lit_vector->value.bools[i] = lit_vec->value.bools[arg_idx++]; break; } } if (arg_idx >= lit_vec->size) { arg_idx = 0; if (arg) arg = arg->Suc(); if (arg) arg_lit = EvalConstExpression(arg); } } else if (element_type == WGL_BasicType::Float) { double d; if (LiteralToDouble(arg_lit, d)) lit_vector->value.doubles[i] = d; if (arg) arg = arg->Suc(); if (arg) arg_lit = EvalConstExpression(arg); } else { int i; if (LiteralToInt(arg_lit, i)) { switch (element_type) { case WGL_BasicType::Int: lit_vector->value.ints[i] = i; break; case WGL_BasicType::UInt: lit_vector->value.u_ints[i] = static_cast<unsigned>(i); break; case WGL_BasicType::Bool: lit_vector->value.bools[i] = i != 0; break; default: OP_ASSERT(!"The 'impossible' happened, unexpected element type."); return NULL; } } if (arg) arg = arg->Suc(); if (arg) arg_lit = EvalConstExpression(arg); } } } case WGL_Type::Matrix: OP_ASSERT(!"Support for (constant) matrix constructors not in place; a reminder.."); case WGL_Type::Array: /* Language will have to be extended first to support array literals.. */ default: return NULL; } } else return NULL; } case WGL_Expr::Select: /* TODO: track constant structures / fields with known values. */ return NULL; case WGL_Expr::Index: { WGL_IndexExpr *index_expr = static_cast<WGL_IndexExpr *>(e); if (index_expr->array->GetType() == WGL_Expr::Var) { WGL_VarExpr *array_var = static_cast<WGL_VarExpr *>(index_expr->array); if (WGL_VarBinding *binder = LookupVarBinding(array_var->name)) if (binder->value && IsConstantExpression(binder->value)) { WGL_Literal *idx = EvalConstExpression(index_expr->index); int idx_val = -1; if (LiteralToInt(idx, idx_val)) { switch (binder->type->GetType()) { case WGL_Type::Vector: { WGL_Literal *c_array = EvalConstExpression(binder->value); OP_ASSERT(c_array->type == WGL_Literal::Vector); WGL_LiteralVector *cvec = static_cast<WGL_LiteralVector *>(c_array); if (static_cast<unsigned>(idx_val) < cvec->size) { WGL_Literal *l = context->BuildLiteral(WGL_BasicType::ToLiteralType(cvec->element_type)); if (l) { switch (l->type) { case WGL_Literal::Double: l->value.d.value = cvec->value.doubles[idx_val]; return l; case WGL_Literal::Int: l->value.i = cvec->value.ints[idx_val]; return l; case WGL_Literal::UInt: l->value.u_int = cvec->value.u_ints[idx_val]; return l; case WGL_Literal::Bool: l->value.b = cvec->value.bools[idx_val]; return l; default: return NULL; } } } return NULL; } case WGL_Type::Array: { WGL_Literal *c_array = EvalConstExpression(binder->value); OP_ASSERT(c_array->type == WGL_Literal::Array); WGL_LiteralArray *carr = static_cast<WGL_LiteralArray *>(c_array); if (static_cast<unsigned>(idx_val) < carr->size) { WGL_Literal *l = context->BuildLiteral(WGL_BasicType::ToLiteralType(carr->element_type)); if (l) { switch (l->type) { case WGL_Literal::Double: l->value.d.value = carr->value.doubles[idx_val]; return l; case WGL_Literal::Int: l->value.i = carr->value.ints[idx_val]; return l; case WGL_Literal::UInt: l->value.u_int = carr->value.u_ints[idx_val]; return l; case WGL_Literal::Bool: l->value.b = carr->value.bools[idx_val]; return l; default: return NULL; } } } return NULL; } default: return NULL; } } } } return NULL; } case WGL_Expr::Assign: return NULL; case WGL_Expr::PostOp: { WGL_PostExpr *post_expr = static_cast<WGL_PostExpr *>(e); return EvalConstExpression(post_expr->arg); } case WGL_Expr::Seq: { WGL_SeqExpr *post_expr = static_cast<WGL_SeqExpr *>(e); return EvalConstExpression(post_expr->arg2); } case WGL_Expr::Cond: { WGL_CondExpr *cond_expr = static_cast<WGL_CondExpr *>(e); if (WGL_Literal *cond = EvalConstExpression(cond_expr->arg1)) { WGL_Literal::Value v = WGL_Literal::ToBool(cond->type, cond->value); return v.b ? EvalConstExpression(cond_expr->arg2) : EvalConstExpression(cond_expr->arg3); } else return NULL; } case WGL_Expr::Binary: { WGL_BinaryExpr *bin_expr = static_cast<WGL_BinaryExpr *>(e); if (WGL_Literal *l1 = EvalConstExpression(bin_expr->arg1)) if (WGL_Literal *l2 = EvalConstExpression(bin_expr->arg2)) return EvalConstExpression(bin_expr->op, l1->type, l1->value, l2->type, l2->value); return NULL; } case WGL_Expr::Unary: { WGL_UnaryExpr *un_expr = static_cast<WGL_UnaryExpr *>(e); WGL_Literal *l = EvalConstExpression(un_expr->arg); switch (un_expr->op) { case WGL_Expr::OpAdd: return l; case WGL_Expr::OpNot: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Bool); switch (l->type) { case WGL_Literal::Double: n->value.b = l->value.d.value == 0; break; case WGL_Literal::Int: n->value.b = l->value.i == 0; break; case WGL_Literal::UInt: n->value.b = l->value.u_int == 0; break; case WGL_Literal::Bool: n->value.b = l->value.b == FALSE; break; case WGL_Literal::String: n->value.b = l->value.s == NULL; break; } return n; } case WGL_Expr::OpNegate: switch (l->type) { case WGL_Literal::Double: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Double); n->value.d.value = -l->value.d.value; return n; } case WGL_Literal::Int: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Int); n->value.i = -l->value.i; return n; } case WGL_Literal::UInt: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Int); n->value.i = - static_cast<int>(l->value.u_int); return n; } case WGL_Literal::Bool: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Bool); n->value.b = l->value.b == FALSE; return n; } case WGL_Literal::String: return l; } case WGL_Expr::OpPreInc: switch (l->type) { case WGL_Literal::Double: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Double); n->value.d.value = l->value.d.value + 1; return n; } case WGL_Literal::Int: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Int); n->value.i = l->value.i + 1; return n; } case WGL_Literal::UInt: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::UInt); n->value.u_int = l->value.u_int + 1; return n; } case WGL_Literal::Bool: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Bool); n->value.b = !l->value.b; return n; } case WGL_Literal::String: return l; } case WGL_Expr::OpPreDec: switch (l->type) { case WGL_Literal::Double: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Double); n->value.d.value = l->value.d.value + 1; return n; } case WGL_Literal::Int: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Int); n->value.i = l->value.i + 1; return n; } case WGL_Literal::UInt: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::UInt); n->value.u_int = l->value.u_int + 1; return n; } case WGL_Literal::Bool: { WGL_Literal *n = context->BuildLiteral(WGL_Literal::Bool); n->value.b = !l->value.b; return n; } case WGL_Literal::String: return l; } } } default: OP_ASSERT(!"Unhandled expression type"); return NULL; } } BOOL WGL_ValidationState::LiteralToInt(WGL_Literal *lit, int &val) { if (!lit) return FALSE; switch (lit->type) { case WGL_Literal::Double: if (!op_isfinite(lit->value.d.value)) return FALSE; else if (lit->value.d.value >= INT_MIN && lit->value.d.value <= INT_MAX) { val = static_cast<int>(lit->value.d.value); return TRUE; } else return FALSE; case WGL_Literal::Int: case WGL_Literal::UInt: val = lit->value.i; return TRUE; case WGL_Literal::Bool: val = lit->value.b ? 1 : 0; return TRUE; default: return FALSE; } } BOOL WGL_ValidationState::LiteralToDouble(WGL_Literal *lit, double &val) { if (!lit) return FALSE; switch (lit->type) { case WGL_Literal::Double: val = lit->value.d.value; return TRUE; case WGL_Literal::Int: case WGL_Literal::UInt: val = lit->value.i; return TRUE; case WGL_Literal::Bool: val = lit->value.b ? 1 : 0; return TRUE; default: return FALSE; } } /* static */ BOOL WGL_ValidationState::IsSameType(WGL_Type *t1, WGL_Type *t2, BOOL type_equality) { if (t1 == t2) return TRUE; if (t1->GetType() != t2->GetType()) return FALSE; switch (t1->GetType()) { case WGL_Type::Basic: if (type_equality) return (static_cast<WGL_BasicType *>(t1)->type == static_cast<WGL_BasicType *>(t2)->type); else { WGL_BasicType *b1 = static_cast<WGL_BasicType *>(t1); WGL_BasicType *b2 = static_cast<WGL_BasicType *>(t2); if (b1->type == WGL_BasicType::Void || b2->type == WGL_BasicType::Void) return FALSE; else return TRUE; } case WGL_Type::Vector: { WGL_VectorType *v1 = static_cast<WGL_VectorType *>(t1); WGL_VectorType *v2 = static_cast<WGL_VectorType *>(t2); return v1->type == v2->type; } case WGL_Type::Matrix: { WGL_MatrixType *m1 = static_cast<WGL_MatrixType *>(t1); WGL_MatrixType *m2 = static_cast<WGL_MatrixType *>(t2); return m1->type == m2->type; } case WGL_Type::Sampler: { WGL_SamplerType *s1 = static_cast<WGL_SamplerType *>(t1); WGL_SamplerType *s2 = static_cast<WGL_SamplerType *>(t2); return s1->type == s2->type; } case WGL_Type::Name: { WGL_NameType *n1 = static_cast<WGL_NameType *>(t1); WGL_NameType *n2 = static_cast<WGL_NameType *>(t2); return n1->name->Equals(n2->name); } case WGL_Type::Struct: { WGL_StructType *s1 = static_cast<WGL_StructType *>(t1); WGL_StructType *s2 = static_cast<WGL_StructType *>(t2); if (!s1->tag->Equals(s2->tag)) return FALSE; if (s1->fields->list.Cardinal() != s2->fields->list.Cardinal()) return FALSE; /* Identical types if same tag..but just for the fun of it. */ WGL_Field *f1 = s1->fields->list.First(); for (WGL_Field *f2 = s2->fields->list.First(); f2; f2 = f2->Suc()) { if (!IsSameType(f1->type, f2->type, TRUE)) return FALSE; f1 = f1->Suc(); } return TRUE; } case WGL_Type::Array: { WGL_ArrayType *a1 = static_cast<WGL_ArrayType *>(t1); WGL_ArrayType *a2 = static_cast<WGL_ArrayType *>(t2); if (!IsSameType(a1->element_type, a2->element_type, TRUE)) return FALSE; /* An error if this predicate is called on non-normalised types. */ OP_ASSERT(a1->is_constant_value && a2->is_constant_value); if (a1->is_constant_value && a2->is_constant_value) return (a1->length_value == a2->length_value); else return FALSE; } default: OP_ASSERT(!"Unhandled type"); return FALSE; } } WGL_Type * WGL_ValidationState::NormaliseType(WGL_Type *t) { switch (t->GetType()) { case WGL_Type::Basic: case WGL_Type::Vector: case WGL_Type::Matrix: case WGL_Type::Sampler: return t; case WGL_Type::Name: { WGL_NameType *n = static_cast<WGL_NameType *>(t); if (WGL_Type *type = LookupTypeName(n->name)) return NormaliseType(type); else return t; } case WGL_Type::Struct: { WGL_StructType *s = static_cast<WGL_StructType *>(t); for (WGL_Field *f = s->fields ? s->fields->list.First() : NULL; f; f = f->Suc()) f->type = NormaliseType(f->type); return t; } case WGL_Type::Array: { WGL_ArrayType *a = static_cast<WGL_ArrayType *>(t); a->element_type = NormaliseType(a->element_type); if (!a->is_constant_value) { if (WGL_Literal *l = EvalConstExpression(a->length)) if (l->type == WGL_Literal::Int && l->value.i >= 0) { a->length_value = static_cast<unsigned>(l->value.i); a->is_constant_value = TRUE; } else if (l->type == WGL_Literal::UInt) { a->length_value = l->value.u_int; a->is_constant_value = TRUE; } } return t; } default: OP_ASSERT(!"Unhandled type"); return t; } } BOOL WGL_ValidationState::HasExpressionType(WGL_Type *t, WGL_Expr *e, BOOL type_equality) { switch (e->GetType()) { case WGL_Expr::Lit: { WGL_LiteralExpr *lit = static_cast<WGL_LiteralExpr *>(e); switch (lit->literal->type) { case WGL_Literal::Double: if (t->GetType() == WGL_Type::Basic) { WGL_BasicType *base_type = static_cast<WGL_BasicType *>(t); return (type_equality && base_type->type == WGL_BasicType::Float || (!type_equality && base_type->type != WGL_BasicType::Void)); } else return FALSE; case WGL_Literal::Int: case WGL_Literal::UInt: if (t->GetType() == WGL_Type::Basic) { WGL_BasicType *base_type = static_cast<WGL_BasicType *>(t); if (type_equality && base_type->type == WGL_BasicType::UInt) return (lit->literal->type == WGL_Literal::UInt || lit->literal->value.i >= 0); else return (type_equality && base_type->type == WGL_BasicType::Int || (!type_equality && base_type->type != WGL_BasicType::Void)); } else return FALSE; case WGL_Literal::Bool: if (t->GetType() == WGL_Type::Basic) { WGL_BasicType *base_type = static_cast<WGL_BasicType *>(t); return (type_equality && base_type->type == WGL_BasicType::Bool || (!type_equality && base_type->type != WGL_BasicType::Void)); } else return FALSE; default: return FALSE; } } case WGL_Expr::Var: { WGL_VarExpr *var_expr = static_cast<WGL_VarExpr *>(e); if (WGL_Type *var_type = LookupVarType(var_expr->name, NULL)) return IsSameType(var_type, t, type_equality); else return FALSE; } case WGL_Expr::TypeConstructor: { WGL_TypeConstructorExpr *type_expr = static_cast<WGL_TypeConstructorExpr *>(e); return IsSameType(type_expr->constructor, t, type_equality); } case WGL_Expr::Unary: return HasExpressionType(t, static_cast<WGL_UnaryExpr *>(e)->arg, type_equality); case WGL_Expr::Binary: if (WGL_Type *bin_type = GetExpressionType(e)) return IsSameType(t, bin_type, type_equality); else return FALSE; case WGL_Expr::Assign: return HasExpressionType(t, static_cast<WGL_AssignExpr *>(e)->rhs, type_equality); case WGL_Expr::Seq: return HasExpressionType(t, static_cast<WGL_SeqExpr *>(e)->arg2, type_equality); case WGL_Expr::Select: { WGL_SelectExpr *select_expr = static_cast<WGL_SelectExpr *>(e); if (WGL_Type *type_struct = GetExpressionType(select_expr->value)) { if (type_struct->GetType() == WGL_Type::Struct) { if (WGL_Field *f = LookupField(static_cast<WGL_StructType *>(type_struct)->fields, select_expr->field)) return IsSameType(t, f->type, type_equality); } else if (type_struct->GetType() == WGL_Type::Vector) { WGL_VectorType *vector_struct = static_cast<WGL_VectorType *>(type_struct); const uni_char *str = Storage(context, select_expr->field); unsigned len = static_cast<unsigned>(uni_strlen(str)); if (len <= 4 && len > 1 && t->GetType() == WGL_Type::Vector) { WGL_VectorType *vec = static_cast<WGL_VectorType *>(t); return (WGL_VectorType::GetMagnitude(vec) == len && WGL_VectorType::SameElementType(vec, vector_struct)); } else if (len == 1 && t->GetType() == WGL_Type::Basic) return WGL_VectorType::GetElementType(vector_struct) == static_cast<WGL_BasicType *>(t)->type; } } return FALSE; } case WGL_Expr::Index: { WGL_IndexExpr *index_expr = static_cast<WGL_IndexExpr *>(e); if (WGL_Type *type_array = GetExpressionType(index_expr->array)) if (type_array->GetType() == WGL_Type::Array) return IsSameType(t, static_cast<WGL_ArrayType *>(type_array)->element_type, type_equality); return FALSE; } case WGL_Expr::Call: if (WGL_Type *app_type = GetExpressionType(e)) return IsSameType(t, context->GetValidationState().NormaliseType(app_type), type_equality); else return FALSE; default: return FALSE; } } WGL_Type * WGL_ValidationState::FromBuiltinType(WGL_BuiltinType *t) { switch (t->type) { case WGL_BuiltinType::Basic: return context->GetASTBuilder()->BuildBasicType(t->value.basic_type); case WGL_BuiltinType::Vector: return context->GetASTBuilder()->BuildVectorType(t->value.vector_type); case WGL_BuiltinType::Matrix: return context->GetASTBuilder()->BuildMatrixType(t->value.matrix_type); case WGL_BuiltinType::Sampler: return context->GetASTBuilder()->BuildSamplerType(t->value.sampler_type); default: return NULL; } } BOOL WGL_ValidationState::MatchesBuiltinType(WGL_BuiltinType *t, WGL_Type *type) { switch (t->type) { case WGL_BuiltinType::Basic: if (type->GetType() == WGL_Type::Basic) return t->Matches(static_cast<WGL_BasicType *>(type)->type, FALSE); else return FALSE; case WGL_BuiltinType::Vector: case WGL_BuiltinType::Vec: case WGL_BuiltinType::IVec: case WGL_BuiltinType::BVec: if (type->GetType() == WGL_Type::Vector) return t->Matches(static_cast<WGL_VectorType *>(type)->type, TRUE); else return FALSE; case WGL_BuiltinType::Matrix: case WGL_BuiltinType::Mat: if (type->GetType() == WGL_Type::Matrix) return t->Matches(static_cast<WGL_MatrixType *>(type)->type, TRUE); else return FALSE; case WGL_BuiltinType::Sampler: if (type->GetType() == WGL_Type::Sampler) return t->Matches(static_cast<WGL_SamplerType *>(type)->type, TRUE); else return FALSE; case WGL_BuiltinType::Gen: if (type->GetType() == WGL_Type::Basic) return t->Matches(static_cast<WGL_BasicType *>(type)->type, FALSE); else if (type->GetType() == WGL_Type::Vector) return t->Matches(static_cast<WGL_VectorType *>(type)->type, TRUE); else return FALSE; default: OP_ASSERT(!"Unhandled type"); return FALSE; } } BOOL WGL_ValidationState::IsConstantBuiltin(const uni_char *str) { /* Everything goes except for the texture lookup functions; if they match the prefix "texture", that's all we need to know (since it is a builtin -- if the spec disallows other builtins, this will have to be updated.) */ unsigned len = static_cast<unsigned>(uni_strlen(str)); if (len > 6 && uni_strncmp("texture", str, 6) == 0) return FALSE; return TRUE; } BOOL WGL_ValidationState::IsConstantExpression(WGL_Expr *e) { if (!e) return FALSE; switch (e->GetType()) { case WGL_Expr::Lit: return TRUE; case WGL_Expr::Var: if (WGL_Type *type = LookupVarType(static_cast<WGL_VarExpr *>(e)->name, NULL)) /* NOTE: GLSL does not recognise 'uniform's as constant; not bound until run-time */ return type->GetType() != WGL_Type::Array && (!type->type_qualifier || type->type_qualifier->storage == WGL_TypeQualifier::Const); else return FALSE; case WGL_Expr::TypeConstructor: return FALSE; case WGL_Expr::Call: { WGL_CallExpr *call_expr = static_cast<WGL_CallExpr *>(e); if (!call_expr->args) return FALSE; if (call_expr->fun->GetType() == WGL_Expr::TypeConstructor) { for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) if (!IsConstantExpression(arg)) return FALSE; return TRUE; } else if (call_expr->fun->GetType() == WGL_Expr::Var) { WGL_VarExpr *fun = static_cast<WGL_VarExpr *>(call_expr->fun); if (List<WGL_Builtin> *builtins = LookupBuiltin(fun->name)) if (WGL_BuiltinFun *f = ResolveBuiltinFunction(builtins, call_expr->args)) if (IsConstantBuiltin(f->name)) { BOOL matched_one = FALSE; for (WGL_Expr *arg = call_expr->args->list.First(); arg; arg = arg->Suc()) if (!IsConstantExpression(arg)) { if (f->intrinsic != WGL_GLSL::Max && f->intrinsic != WGL_GLSL::Min) return FALSE; } else matched_one = TRUE; return matched_one; } } return FALSE; } case WGL_Expr::Assign: return FALSE; case WGL_Expr::Select: { WGL_SelectExpr *select_expr = static_cast<WGL_SelectExpr *>(e); /* NOTE: assume well-typed (and to a known field.) * If the 'record' is a constructor application (of a struct), * it's a constant expression if all fields are. */ if (select_expr->GetType() == WGL_Expr::Call) return IsConstantExpression(select_expr->value); else return FALSE; } case WGL_Expr::Index: { WGL_IndexExpr *index_expr = static_cast<WGL_IndexExpr *>(e); WGL_Type *type = GetExpressionType(index_expr->array); return type && type->GetType() != WGL_Type::Array && IsConstantExpression(index_expr->array) && IsConstantExpression(index_expr->index); } case WGL_Expr::Unary: { WGL_UnaryExpr *unary_expr = static_cast<WGL_UnaryExpr *>(e); if (unary_expr->op == WGL_Expr::OpPreDec || unary_expr->op == WGL_Expr::OpPreInc) return FALSE; else return IsConstantExpression(unary_expr->arg); } case WGL_Expr::PostOp: /* I don't think these can be considered 'constant expressions'..but the spec doesn't call them out as not. (GLSL ES2.0, Section 5.10). */ return FALSE; case WGL_Expr::Seq: { WGL_SeqExpr *seq_expr = static_cast<WGL_SeqExpr *>(e); return IsConstantExpression(seq_expr->arg1) && IsConstantExpression(seq_expr->arg2); } case WGL_Expr::Binary: { WGL_BinaryExpr *bin_expr = static_cast<WGL_BinaryExpr *>(e); return IsConstantExpression(bin_expr->arg1) && IsConstantExpression(bin_expr->arg2); } case WGL_Expr::Cond: { WGL_CondExpr *cond_expr = static_cast<WGL_CondExpr *>(e); return IsConstantExpression(cond_expr->arg1) && IsConstantExpression(cond_expr->arg2) && IsConstantExpression(cond_expr->arg3); } default: OP_ASSERT(!"Unhandled expression type"); return FALSE; } } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_ReturnStmt *s) { context->SetLineNumber(s->line_number); if (s->value) s->value = s->value->VisitExpr(this); return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_ExprStmt *s) { context->SetLineNumber(s->line_number); if (s->expr) s->expr = s->expr->VisitExpr(this); return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_DeclStmt *s) { context->SetLineNumber(s->line_number); for (WGL_Decl *decl = s->decls.First(); decl; decl = decl->Suc()) decl = decl->VisitDecl(this); return s; } /* virtual */ WGL_Stmt * WGL_ValidateShader::VisitStmt(WGL_CaseLabel *s) { context->SetLineNumber(s->line_number); s->condition = s->condition->VisitExpr(this); return s; } /* virtual */ WGL_Type * WGL_ValidateShader::VisitType(WGL_BasicType *t) { return t; } /* virtual */ WGL_Type * WGL_ValidateShader::VisitType(WGL_ArrayType *t) { t->element_type = t->element_type->VisitType(this); if (t->length) { t->length = t->length->VisitExpr(this); if (WGL_Literal *l = context->GetValidationState().EvalConstExpression(t->length)) { WGL_Literal::Value lv = WGL_Literal::ToInt(l->type, l->value); if (lv.i == 0) context->AddError(WGL_Error::ARRAY_SIZE_IS_ZERO, UNI_L("")); else { t->is_constant_value = TRUE; t->length_value = static_cast<unsigned>(lv.i); } } } return t; } /* virtual */ WGL_Type * WGL_ValidateShader::VisitType(WGL_VectorType *t) { return t; } /* virtual */ WGL_Type * WGL_ValidateShader::VisitType(WGL_MatrixType *t) { return t; } /* virtual */ WGL_Type * WGL_ValidateShader::VisitType(WGL_SamplerType *t) { return t; } /* virtual */ WGL_Type * WGL_ValidateShader::VisitType(WGL_NameType *t) { ValidateTypeName(t->name, TRUE); return t; } /* virtual */ WGL_Type * WGL_ValidateShader::VisitType(WGL_StructType *t) { ValidateTypeName(t->tag, FALSE); if (!t->fields) context->AddError(WGL_Error::EMPTY_STRUCT, Storage(context, t->tag)); else { context->EnterLocalScope(NULL); for (WGL_Field *f = t->fields->list.First(); f; f = f->Suc()) if (!f->name) context->AddError(WGL_Error::ANON_FIELD, Storage(context, t->tag)); else if (f->type && f->type->GetType() == WGL_Type::Struct) context->AddError(WGL_Error::ILLEGAL_NESTED_STRUCT, Storage(context, t->tag)); else f->VisitField(this); context->LeaveLocalScope(); } context->GetValidationState().AddStructType(t->tag, static_cast<WGL_Type *>(t)); return t; } /* virtual */ WGL_Decl * WGL_ValidateShader::VisitDecl(WGL_FunctionPrototype *proto) { context->SetLineNumber(proto->line_number); if (proto->return_type) proto->return_type = proto->return_type->VisitType(this); if (proto->name && proto->return_type) { BOOL overlaps = context->GetValidationState().ConflictsWithBuiltin(proto->name, proto->parameters, proto->return_type); if (overlaps) context->AddError(WGL_Error::ILLEGAL_BUILTIN_OVERRIDE, Storage(context, proto->name)); ValidateIdentifier(proto->name, FALSE); WGL_SourceLoc loc(context->GetSourceContext(), context->GetLineNumber()); context->GetValidationState().AddFunction(proto->name, proto->return_type, proto->parameters, TRUE, loc); } context->EnterLocalScope(NULL); if (proto->parameters) proto->parameters = VisitParamList(proto->parameters); context->LeaveLocalScope(); return proto; } /* virtual */ WGL_Decl * WGL_ValidateShader::VisitDecl(WGL_PrecisionDefn *d) { context->SetLineNumber(d->line_number); d->type = d->type->VisitType(this); BOOL precision_ok = FALSE; switch (d->type->GetType()) { case WGL_Type::Basic: { WGL_BasicType *basic_type = static_cast<WGL_BasicType *>(d->type); if (basic_type->type == WGL_BasicType::Int || basic_type->type == WGL_BasicType::Float) precision_ok = TRUE; else context->AddError(WGL_Error::ILLEGAL_PRECISION_DECL, UNI_L("unsupported basic type")); break; } case WGL_Type::Sampler: precision_ok = TRUE; break; default: context->AddError(WGL_Error::ILLEGAL_PRECISION_DECL, UNI_L("unsupported type")); break; } if (precision_ok) { OP_ASSERT(d->type); context->GetValidationState().AddPrecision(d->type, d->precision); } return d; } /* virtual */ WGL_Decl * WGL_ValidateShader::VisitDecl(WGL_ArrayDecl *d) { context->SetLineNumber(d->line_number); d->type = d->type->VisitType(this); WGL_Type *array_type = NULL; WGL_VarName *alias_name = d->identifier; if (context->GetValidationState().LookupVarType(d->identifier, &alias_name, TRUE) != NULL) context->AddError(WGL_Error::DUPLICATE_NAME, Storage(context, d->identifier)); else if (d->size) { array_type = context->GetASTBuilder()->BuildArrayType(d->type, d->size); WGL_VarBinding *binding = ValidateVarDefn(d->identifier, array_type); if (binding) d->identifier = binding->var; } if (d->size) { d->size = d->size->VisitExpr(this); if (!context->GetValidationState().IsConstantExpression(d->size)) context->AddError(WGL_Error::EXPRESSION_NOT_CONSTANT, Storage(context, d->identifier)); else if (array_type) { if (WGL_Literal *l = context->GetValidationState().EvalConstExpression(d->size)) { WGL_Literal::Value lv = WGL_Literal::ToInt(l->type, l->value); if (lv.i == 0) context->AddError(WGL_Error::ARRAY_SIZE_IS_ZERO, Storage(context, d->identifier)); else { WGL_ArrayType *array_ty = static_cast<WGL_ArrayType *>(array_type); array_ty->is_constant_value = TRUE; array_ty->length_value = static_cast<unsigned>(lv.i); } } } } else context->AddError(WGL_Error::ILLEGAL_UNSIZED_ARRAY_DECL, UNI_L("")); if (d->initialiser) d->initialiser = d->initialiser->VisitExpr(this); WGL_Type *resolved_t = array_type ? context->GetValidationState().NormaliseType(array_type) : NULL; if (d->type && d->type->type_qualifier && d->type->type_qualifier->storage == WGL_TypeQualifier::Attribute) context->AddError(WGL_Error::INVALID_ATTRIBUTE_DECL, Storage(context, d->identifier)); else if (d->type && d->type->type_qualifier && d->type->type_qualifier->storage == WGL_TypeQualifier::Varying) context->GetValidationState().AddVarying(resolved_t, d->identifier, WGL_Type::NoPrecision, context->GetLineNumber()); else if (d->type && d->type->type_qualifier && d->type->type_qualifier->storage == WGL_TypeQualifier::Uniform) context->GetValidationState().AddUniform(resolved_t, d->identifier, WGL_Type::NoPrecision, context->GetLineNumber()); return d; } /* virtual */ WGL_Decl * WGL_ValidateShader::VisitDecl(WGL_VarDecl *d) { context->SetLineNumber(d->line_number); d->type->VisitType(this); if (d->initialiser) d->initialiser->VisitExpr(this); if (context->GetValidationState().LookupVarType(d->identifier, NULL, TRUE)) context->AddError(WGL_Error::DUPLICATE_NAME, Storage(context, d->identifier)); else { WGL_VarBinding *binder = ValidateVarDefn(d->identifier, d->type); if (binder) d->identifier = binder->var; /* For the purposes of catching out-of-bounds errors and the like, track constant-valued bindings. */ if (binder && d->initialiser) { if (context->GetValidationState().IsConstantExpression(d->initialiser)) binder->value = d->initialiser; WGL_Type *t = context->GetValidationState().GetExpressionType(d->initialiser); WGL_Type *resolved_t = t ? context->GetValidationState().NormaliseType(t) : NULL; WGL_Type *resolved_type = context->GetValidationState().NormaliseType(binder->type); if (t && !context->GetValidationState().IsSameType(resolved_type, resolved_t, TRUE)) context->AddError(WGL_Error::TYPE_MISMATCH, UNI_L("")); } } if (WGL_TypeQualifier *type_qual = d->type->type_qualifier) { /* If a vertex shader, simply add them to the list..write and conflicting * definitions will be caught separately. For fragment shaders (run after vertex shaders..), * we check against the vertex shader uniforms to ensure consistency. */ if (type_qual->storage == WGL_TypeQualifier::Uniform) { /* This would be the place to default the current precision if 'NoPrecision'. */ WGL_Type::Precision precision = d->type->precision; if (WGL_VaryingOrUniform *uniform = context->GetValidationState().LookupUniform(d->identifier)) CheckUniform(uniform, d->type, d->identifier, precision); else if (context->GetValidationState().GetScopeLevel() > 0) context->AddError(WGL_Error::INVALID_LOCAL_UNIFORM_DECL, Storage(context, d->identifier)); else { WGL_Type *resolved_t = d->type ? context->GetValidationState().NormaliseType(d->type) : NULL; context->GetValidationState().AddUniform(resolved_t, d->identifier, precision, context->GetLineNumber()); } } else if (type_qual->storage == WGL_TypeQualifier::Attribute) { BOOL attribute_decl_ok = TRUE; /* Check and register attribute declaration */ if (!IsVertexShader() || context->GetValidationState().GetScopeLevel() > 0) { attribute_decl_ok = FALSE; context->AddError(!IsVertexShader() ? WGL_Error::INVALID_ATTRIBUTE_DECL : WGL_Error::INVALID_LOCAL_ATTRIBUTE_DECL, Storage(context, d->identifier)); } else { switch (d->type->GetType()) { case WGL_Type::Vector: { WGL_VectorType *vector_type = static_cast<WGL_VectorType *>(d->type); if (!(vector_type->type == WGL_VectorType::Vec2 || vector_type->type == WGL_VectorType::Vec3 || vector_type->type == WGL_VectorType::Vec4)) { attribute_decl_ok = FALSE; context->AddError(WGL_Error::INVALID_ATTRIBUTE_DECL_TYPE, Storage(context, d->identifier)); } break; } case WGL_Type::Matrix: { WGL_MatrixType *matrix_type = static_cast<WGL_MatrixType *>(d->type); if (!(matrix_type->type == WGL_MatrixType::Mat2 || matrix_type->type == WGL_MatrixType::Mat3 || matrix_type->type == WGL_MatrixType::Mat4)) { attribute_decl_ok = FALSE; context->AddError(WGL_Error::INVALID_ATTRIBUTE_DECL_TYPE, Storage(context, d->identifier)); } break; } case WGL_Type::Basic: { WGL_BasicType *base_type = static_cast<WGL_BasicType *>(d->type); if (base_type->type != WGL_BasicType::Float) { attribute_decl_ok = FALSE; context->AddError(WGL_Error::INVALID_ATTRIBUTE_DECL_TYPE, Storage(context, d->identifier)); } break; } default: attribute_decl_ok = FALSE; context->AddError(WGL_Error::INVALID_ATTRIBUTE_DECL, Storage(context, d->identifier)); break; } } if (attribute_decl_ok) { WGL_Type *resolved_t = d->type ? context->GetValidationState().NormaliseType(d->type) : NULL; context->GetValidationState().AddAttribute(resolved_t, d->identifier, context->GetLineNumber()); } } else if (type_qual->storage == WGL_TypeQualifier::Varying) { BOOL varying_decl_ok = TRUE; if (context->GetValidationState().GetScopeLevel() > 0) { varying_decl_ok = FALSE; context->AddError(WGL_Error::INVALID_LOCAL_VARYING_DECL, Storage(context, d->identifier)); } else if ((d->type->GetType() == WGL_Type::Array && !IsVaryingType(static_cast<WGL_ArrayType *>(d->type)->element_type)) || !IsVaryingType(d->type)) { varying_decl_ok = FALSE; context->AddError(WGL_Error::INVALID_VARYING_DECL_TYPE, Storage(context, d->identifier)); } if (varying_decl_ok) { WGL_Type::Precision precision = d->type->precision; if (WGL_VaryingOrUniform *varying = context->GetValidationState().LookupVarying(d->identifier)) CheckVarying(varying, d->type, d->identifier, precision); else { WGL_Type *resolved_t = d->type ? context->GetValidationState().NormaliseType(d->type) : NULL; context->GetValidationState().AddVarying(resolved_t, d->identifier, precision, context->GetLineNumber()); } } } } return d; } BOOL WGL_ValidateShader::IsVaryingType(WGL_Type *type) { switch (type->GetType()) { case WGL_Type::Vector: { WGL_VectorType *vector_type = static_cast<WGL_VectorType *>(type); return (vector_type->type == WGL_VectorType::Vec2 || vector_type->type == WGL_VectorType::Vec3 || vector_type->type == WGL_VectorType::Vec4); } case WGL_Type::Matrix: { WGL_MatrixType *matrix_type = static_cast<WGL_MatrixType *>(type); return (matrix_type->type == WGL_MatrixType::Mat2 || matrix_type->type == WGL_MatrixType::Mat3 || matrix_type->type == WGL_MatrixType::Mat4); } case WGL_Type::Basic: { WGL_BasicType *base_type = static_cast<WGL_BasicType *>(type); return (base_type->type == WGL_BasicType::Float); } default: return FALSE; } } /* virtual */ WGL_Decl * WGL_ValidateShader::VisitDecl(WGL_TypeDecl *d) { context->SetLineNumber(d->line_number); d->type = d->type->VisitType(this); if (d->var_name) { WGL_VarBinding *binding = ValidateVarDefn(d->var_name, d->type); if (binding) d->var_name = binding->var; } if (WGL_TypeQualifier *type_qual = d->type->type_qualifier) { BOOL is_attribute = type_qual->storage == WGL_TypeQualifier::Attribute; if (is_attribute || type_qual->storage == WGL_TypeQualifier::Uniform) { /* Check and register attribute declaration */ if (context->GetValidationState().GetScopeLevel() > 0) { /* Get the var_name if there is one or "". */ const uni_char *var_name = d->var_name ? Storage(context, d->var_name) : UNI_L(""); if (is_attribute) context->AddError(WGL_Error::INVALID_LOCAL_ATTRIBUTE_DECL, var_name); else context->AddError(WGL_Error::INVALID_LOCAL_UNIFORM_DECL, var_name); } } } return d; } /* virtual */ WGL_Decl * WGL_ValidateShader::VisitDecl(WGL_InvariantDecl *d) { context->SetLineNumber(d->line_number); /* Only permitted at global scope. */ if (context->GetValidationState().GetScopeLevel() > 0) { context->AddError(WGL_Error::ILLEGAL_INVARIANT_DECL, Storage(context, d->var_name)); return d; } WGL_InvariantDecl *it = d; while (it) { d->var_name = ValidateVar(d->var_name, FALSE); if (List <WGL_Builtin> *builtin = context->GetValidationState().LookupBuiltin(d->var_name)) { if (!builtin->First()->IsBuiltinVar()) context->AddError(WGL_Error::ILLEGAL_INVARIANT_DECL, Storage(context, d->var_name)); else { WGL_BuiltinVar *var = static_cast<WGL_BuiltinVar *>(builtin->First()); if (!var->is_output) context->AddError(WGL_Error::ILLEGAL_INVARIANT_DECL, Storage(context, d->var_name)); } } else if (WGL_Type *t = context->GetValidationState().LookupVarType(d->var_name, NULL)) if (!t->type_qualifier || t->type_qualifier->storage != WGL_TypeQualifier::Varying) context->AddError(WGL_Error::ILLEGAL_INVARIANT_DECL, Storage(context, d->var_name)); it = it->next; } return d; } /* virtual */ WGL_Decl * WGL_ValidateShader::VisitDecl(WGL_FunctionDefn *d) { context->SetLineNumber(d->line_number); if (d->head->GetType() != WGL_Decl::Proto) context->AddError(WGL_Error::INVALID_FUNCTION_DEFN, UNI_L("fun")); else { WGL_FunctionPrototype *proto = static_cast<WGL_FunctionPrototype *>(d->head); if (context->GetValidationState().CurrentFunction() != NULL) context->AddError(WGL_Error::ILLEGAL_NESTED_FUNCTION, Storage(context, proto->name)); proto->return_type = proto->return_type->VisitType(this); if (!IsValidReturnType(proto->return_type)) context->AddError(WGL_Error::ILLEGAL_RETURN_TYPE, Storage(context, proto->name)); BOOL overlaps = context->GetValidationState().ConflictsWithBuiltin(proto->name, proto->parameters, proto->return_type); if (overlaps) context->AddError(WGL_Error::ILLEGAL_BUILTIN_OVERRIDE, Storage(context, proto->name)); ValidateIdentifier(proto->name, FALSE); context->EnterLocalScope(proto->return_type); proto->parameters = VisitParamList(proto->parameters); WGL_SourceLoc loc(context->GetSourceContext(), context->GetLineNumber()); context->GetValidationState().AddFunction(proto->name, proto->return_type, proto->parameters, FALSE, loc); /* Nested functions aren't allowed, but track the current one for error handling purposes. */ List<WGL_VariableUse> *old_callers = NULL; WGL_VarName *old_fun_name = context->GetValidationState().SetFunction(proto->name, old_callers); d->body = d->body->VisitStmt(this); if (WGL_FunctionData *fun_data = context->GetValidationState().LookupFunction(proto->name)) fun_data->decls.Last()->callers = context->GetValidationState().GetFunctionCalls(); context->GetValidationState().SetFunction(old_fun_name, old_callers); context->LeaveLocalScope(); } return d; } /* virtual */ WGL_Field * WGL_ValidateShader::VisitField(WGL_Field *f) { if (context->GetValidationState().LookupVarType(f->name, NULL, TRUE)) context->AddError(WGL_Error::DUPLICATE_NAME, Storage(context, f->name)); else { WGL_VarBinding *binding = ValidateVarDefn(f->name, f->type); if (binding) f->name = binding->var; } if (f->type->GetType() == WGL_Type::Array) { WGL_ArrayType *array_type = static_cast<WGL_ArrayType *>(f->type); if (context->GetValidationState().IsConstantExpression(array_type->length)) { WGL_Type *t = context->GetValidationState().GetExpressionType(array_type->length); if (!t || t->GetType() == WGL_Type::Basic && static_cast<WGL_BasicType *>(t)->type != WGL_BasicType::Int) context->AddError(WGL_Error::ILLEGAL_NON_CONSTANT_ARRAY, UNI_L("")); else { int val = 0; BOOL success = context->GetValidationState().LiteralToInt(context->GetValidationState().EvalConstExpression(array_type->length), val); if (!success || val <= 0) context->AddError(WGL_Error::ILLEGAL_NON_CONSTANT_ARRAY, UNI_L("")); else { array_type->is_constant_value = TRUE; array_type->length_value = val; } } } else context->AddError(WGL_Error::ILLEGAL_NON_CONSTANT_ARRAY, UNI_L("")); } return f; } /* virtual */ WGL_Param * WGL_ValidateShader::VisitParam(WGL_Param *p) { p->type = p->type->VisitType(this); if (WGL_VarBinding *binding = ValidateVarDefn(p->name, p->type)) p->name = binding->var; if (p->type) p->type = context->GetValidationState().NormaliseType(p->type); return p; } /* virtual */ WGL_LayoutPair * WGL_ValidateShader::VisitLayout(WGL_LayoutPair *lp) { lp->identifier = ValidateVar(lp->identifier); return lp; } /* virtual */ WGL_LayoutList * WGL_ValidateShader::VisitLayoutList(WGL_LayoutList *ls) { for (WGL_LayoutPair *lp = ls->list.First(); lp; lp = lp->Suc()) lp = lp->VisitLayout(this); return ls; } /* virtual */ WGL_FieldList * WGL_ValidateShader::VisitFieldList(WGL_FieldList *ls) { for (WGL_Field *f = ls->list.First(); f; f = f->Suc()) f = f->VisitField(this); return ls; } /* virtual */ WGL_ParamList * WGL_ValidateShader::VisitParamList(WGL_ParamList *ls) { for (WGL_Param *p = ls->list.First(); p; p = p->Suc()) p = p->VisitParam(this); return ls; } /* virtual */ WGL_DeclList* WGL_ValidateShader::VisitDeclList(WGL_DeclList *ls) { for (WGL_Decl *d = ls->list.First(); d; d = d->Suc()) d = d->VisitDecl(this); return ls; } /* virtual */ WGL_StmtList * WGL_ValidateShader::VisitStmtList(WGL_StmtList *ls) { for (WGL_Stmt *s = ls->list.First(); s; s = s->Suc()) s = s->VisitStmt(this); return ls; } /* virtual */ WGL_ExprList * WGL_ValidateShader::VisitExprList(WGL_ExprList *ls) { for (WGL_Expr *e = ls->list.First(); e; e = e->Suc()) e = e->VisitExpr(this); return ls; } void WGL_ValidateShader::CheckUniform(WGL_VaryingOrUniform *uniform, WGL_Type *type, WGL_VarName *var, WGL_Type::Precision prec) { /* NOTE: perform the overall uniform check afterwards; dependent on usage. */ if (!context->GetValidationState().IsSameType(uniform->type, type, TRUE) || prec != uniform->precision) context->AddError(WGL_Error::INCOMPATIBLE_UNIFORM_DECL, Storage(context, var)); } void WGL_ValidateShader::CheckVarying(WGL_VaryingOrUniform *varying, WGL_Type *type, WGL_VarName *var, WGL_Type::Precision prec) { if (!context->GetValidationState().IsSameType(varying->type, type, TRUE) || prec != varying->precision) context->AddError(WGL_Error::INCOMPATIBLE_VARYING_DECL, Storage(context, var)); } BOOL WGL_ValidateShader::IsValidReturnType(WGL_Type *type) { switch (type->GetType()) { case WGL_Type::Array: return FALSE; case WGL_Type::Struct: { WGL_StructType *struct_type = static_cast<WGL_StructType *>(type); if (!struct_type->fields) return FALSE; else { for (WGL_Field *f = struct_type->fields->list.First(); f; f = f->Suc()) if (!IsValidReturnType(f->type)) return FALSE; return TRUE; } } default: return TRUE; } } /* static */ void WGL_ValidationState::CheckVariableConsistency(WGL_Context *context, WGL_ShaderVariable::Kind kind, List<WGL_ShaderVariable> &l1, List<WGL_ShaderVariable> &l2) { WGL_ShaderVariable *uni2 = l2.First(); for (WGL_ShaderVariable *uni1 = l1.First(); uni1 && uni2; uni1 = uni1->Suc()) { /* Adjust 'uni2' to refer to next match candidate. */ while (uni2 && uni1->name && uni2->name && uni_strcmp(uni2->name, uni1->name) < 0) uni2 = uni2->Suc(); if (uni2 && uni1->name && uni2->name && uni_strcmp(uni2->name, uni1->name) == 0) { if (!WGL_ValidationState::IsSameType(uni1->type, uni2->type, TRUE)) { WGL_Error::Type err = WGL_Error::INCOMPATIBLE_UNIFORM_DECL; switch (kind) { case WGL_ShaderVariable::Attribute: err = WGL_Error::INCOMPATIBLE_ATTRIBUTE_DECL; break; case WGL_ShaderVariable::Varying: err = WGL_Error::INCOMPATIBLE_VARYING_DECL; break; case WGL_ShaderVariable::Uniform: err = WGL_Error::INCOMPATIBLE_UNIFORM_DECL; break; default: OP_ASSERT(!"Unexpected variable kind"); break; } context->AddError(err, uni1->name); } uni2 = uni2->Suc(); } } } static BOOL IsSameAliasNotVar(const WGL_ShaderVariable *u, const WGL_ShaderVariable *v) { return u->alias_name && uni_str_eq(v->alias_name, u->alias_name) && !uni_str_eq(v->name, u->name); } /* static */ void WGL_ValidationState::CheckVariableAliases(WGL_Context *context, WGL_ShaderVariables *vs, const WGL_ShaderVariable *v, WGL_ShaderVariable::Kind kind) { if (v->alias_name) { for (WGL_ShaderVariable *u = vs->uniforms.First(); u; u = u->Suc()) if (IsSameAliasNotVar(u, v)) { OP_ASSERT(!"Alias names matched same hash-derived unique. Considered 'impossible'."); context->AddError(WGL_Error::INCOMPATIBLE_UNIFORM_DECL, v->name); } for (WGL_ShaderVariable *u = vs->varyings.First(); u; u = u->Suc()) if (IsSameAliasNotVar(u, v)) { OP_ASSERT(!"Alias names matched same hash-derived unique. Considered 'impossible'."); context->AddError(WGL_Error::INCOMPATIBLE_VARYING_DECL, v->name); } } } /* static */ void WGL_ValidationState::CheckVariableAliasOverlap(WGL_Context *context, WGL_ShaderVariables *v1, WGL_ShaderVariables *v2) { /* Verify that aliases don't accidentally overlap; we issue an error if this should accidentally happen. The practical likelihood should be close to zero. */ for (WGL_ShaderVariable *u = v1->uniforms.First(); u; u = u->Suc()) { CheckVariableAliases(context, v1, u, WGL_ShaderVariable::Uniform); CheckVariableAliases(context, v2, u, WGL_ShaderVariable::Uniform); } for (WGL_ShaderVariable *u = v1->varyings.First(); u; u = u->Suc()) { CheckVariableAliases(context, v1, u, WGL_ShaderVariable::Varying); CheckVariableAliases(context, v2, u, WGL_ShaderVariable::Varying); } } void WGL_ValidationState::CheckVariableConsistency(WGL_Context *context, WGL_ShaderVariables *v1, WGL_ShaderVariables *v2) { /* Given the sets of variables produced by two different programs, determine if they are consistent. */ CheckVariableConsistency(context, WGL_ShaderVariable::Uniform, v1->uniforms, v2->uniforms); CheckVariableConsistency(context, WGL_ShaderVariable::Varying, v1->varyings, v2->varyings); /* Attributes are only allowed in vertex shaders, but assuming more than one such shader might be linked together, checking consistency across these is required. */ CheckVariableConsistency(context, WGL_ShaderVariable::Attribute, v1->attributes, v2->attributes); CheckVariableAliasOverlap(context, v1, v2); CheckVariableAliasOverlap(context, v2, v1); } #endif // CANVAS3D_SUPPORT
// Project 17 - LCD message board #include <LiquidCrystal.h> //LiquidCrystal(rs, rw, enable, d4, d5, d6, d7) LiquidCrystal lcd(2, 3, 4, 9, 10, 11, 12); void setup() { Serial.begin(9600); lcd.begin(2, 20); lcd.clear(); lcd.setCursor(0,0); lcd.print("Evil Genius"); lcd.setCursor(0,1); lcd.print("Rules"); } void loop() { if (Serial.available()) { char ch = Serial.read(); if (ch == '#') { lcd.clear(); } else if (ch == '/') { lcd.setCursor(0,1); } else { lcd.write(ch); } } }
// Created by: Peter KURNEV // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BOPAlgo_BOP_HeaderFile #define _BOPAlgo_BOP_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <TopoDS_Shape.hxx> #include <BOPAlgo_ToolsProvider.hxx> #include <NCollection_BaseAllocator.hxx> #include <TopAbs_ShapeEnum.hxx> class BOPAlgo_PaveFiller; //! //! The class represents the Building part of the Boolean Operations //! algorithm.<br> //! The arguments of the algorithms are divided in two groups - *Objects* //! and *Tools*.<br> //! The algorithm builds the splits of the given arguments using the intersection //! results and combines the result of Boolean Operation of given type:<br> //! - *FUSE* - union of two groups of objects;<br> //! - *COMMON* - intersection of two groups of objects;<br> //! - *CUT* - subtraction of one group from the other.<br> //! //! The rules for the arguments and type of the operation are the following:<br> //! - For Boolean operation *FUSE* all arguments should have equal dimensions;<br> //! - For Boolean operation *CUT* the minimal dimension of *Tools* should not be //! less than the maximal dimension of *Objects*;<br> //! - For Boolean operation *COMMON* the arguments can have any dimension.<br> //! //! The class is a General Fuse based algorithm. Thus, all options //! of the General Fuse algorithm such as Fuzzy mode, safe processing mode, //! parallel processing mode, gluing mode and history support are also //! available in this algorithm.<br> //! //! Additionally to the Warnings of the parent class the algorithm returns //! the following warnings: //! - *BOPAlgo_AlertEmptyShape* - in case some of the input shapes are empty shapes. //! //! Additionally to Errors of the parent class the algorithm returns //! the following Error statuses: //! - *BOPAlgo_AlertBOPIsNotSet* - in case the type of Boolean operation is not set; //! - *BOPAlgo_AlertBOPNotAllowed* - in case the operation of given type is not allowed on //! given inputs; //! - *BOPAlgo_AlertSolidBuilderFailed* - in case the BuilderSolid algorithm failed to //! produce the Fused solid. //! class BOPAlgo_BOP : public BOPAlgo_ToolsProvider { public: DEFINE_STANDARD_ALLOC //! Empty constructor Standard_EXPORT BOPAlgo_BOP(); Standard_EXPORT virtual ~BOPAlgo_BOP(); Standard_EXPORT BOPAlgo_BOP(const Handle(NCollection_BaseAllocator)& theAllocator); //! Clears internal fields and arguments Standard_EXPORT virtual void Clear() Standard_OVERRIDE; Standard_EXPORT void SetOperation (const BOPAlgo_Operation theOperation); Standard_EXPORT BOPAlgo_Operation Operation() const; Standard_EXPORT virtual void Perform(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE; protected: Standard_EXPORT virtual void CheckData() Standard_OVERRIDE; //! Performs calculations using prepared Filler //! object <thePF> Standard_EXPORT virtual void PerformInternal1 (const BOPAlgo_PaveFiller& thePF, const Message_ProgressRange& theRange) Standard_OVERRIDE; Standard_EXPORT virtual void BuildResult (const TopAbs_ShapeEnum theType) Standard_OVERRIDE; Standard_EXPORT void BuildShape(const Message_ProgressRange& theRange); Standard_EXPORT void BuildRC(const Message_ProgressRange& theRange); Standard_EXPORT void BuildSolid(const Message_ProgressRange& theRange); //! Treatment of the cases with empty shapes.<br> //! It returns TRUE if there is nothing to do, i.e. //! all shapes in one of the groups are empty shapes. Standard_EXPORT Standard_Boolean TreatEmptyShape(); //! Checks if the arguments of Boolean Operation on solids //! contain any open solids, for which the building of the splits //! has failed. In case of positive check, run different procedure //! for building the result shape. Standard_EXPORT virtual Standard_Boolean CheckArgsForOpenSolid(); protected: //! Extend list of operations to be supported by the Progress Indicator enum BOPAlgo_PIOperation { PIOperation_BuildShape = BOPAlgo_ToolsProvider::PIOperation_Last, PIOperation_Last }; //! Fill PI steps Standard_EXPORT virtual void fillPIConstants(const Standard_Real theWhole, BOPAlgo_PISteps& theSteps) const Standard_OVERRIDE; protected: BOPAlgo_Operation myOperation; Standard_Integer myDims[2]; TopoDS_Shape myRC; }; #endif // _BOPAlgo_BOP_HeaderFile
#include <ionir/passes/pass.h> namespace ionir { BooleanType::BooleanType() : Type(ConstName::typeBool, TypeKind::Boolean) { // } void BooleanType::accept(Pass &pass) { pass.visitBooleanType(this->dynamicCast<BooleanType>()); } }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * 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/>. */ #ifndef XMRIG_OCLRXBASERUNNER_H #define XMRIG_OCLRXBASERUNNER_H #include "backend/opencl/runners/OclBaseRunner.h" #include "base/tools/Buffer.h" namespace xmrig { class Blake2bHashRegistersKernel; class Blake2bInitialHashKernel; class FillAesKernel; class FindSharesKernel; class HashAesKernel; class OclRxBaseRunner : public OclBaseRunner { public: XMRIG_DISABLE_COPY_MOVE_DEFAULT(OclRxBaseRunner) OclRxBaseRunner(size_t index, const OclLaunchData &data); ~OclRxBaseRunner() override; protected: size_t bufferSize() const override; void build() override; void init() override; void run(uint32_t nonce, uint32_t *hashOutput) override; void set(const Job &job, uint8_t *blob) override; protected: virtual void execute(uint32_t iteration) = 0; Blake2bHashRegistersKernel *m_blake2b_hash_registers_32 = nullptr; Blake2bHashRegistersKernel *m_blake2b_hash_registers_64 = nullptr; Blake2bInitialHashKernel *m_blake2b_initial_hash = nullptr; Buffer m_seed; cl_mem m_dataset = nullptr; cl_mem m_entropy = nullptr; cl_mem m_hashes = nullptr; cl_mem m_rounding = nullptr; cl_mem m_scratchpads = nullptr; FillAesKernel *m_fillAes1Rx4_scratchpad = nullptr; FillAesKernel *m_fillAes4Rx4_entropy = nullptr; FindSharesKernel *m_find_shares = nullptr; HashAesKernel *m_hashAes1Rx4 = nullptr; uint32_t m_gcn_version = 12; uint32_t m_worksize = 8; }; } /* namespace xmrig */ #endif // XMRIG_OCLRXBASERUNNER_H
#include<iostream> #include<cstdlib> #include<ctime> using namespace std; struct node { int data; node *left, *right; }*root; typedef node* nodeptr; void insert(int, nodeptr&); void inOrder(nodeptr); void deleteNode(nodeptr&, int); int main() { srand(time(NULL)); root = NULL; for(int i=0; i<10; i++) insert(rand()%100+1, root); int x = 50; inOrder(root); cout << endl; deleteNode(root, 50); return 0; } void insert(int x, nodeptr& p) { if(p == NULL) { p = new node; p->data = x; p->left = NULL; p->right = NULL; } else { if(x < p->data) { insert(x, p->left); } else if(x > p->data){ insert(x, p->right); } else { cout << "Duplicate!\n"; } } } void inOrder(nodeptr p) { if(p != NULL) { inOrder(p->left); cout << p->data << " "; inOrder(p->right); } } void deleteNode(nodeptr& p, int x) { bool found = false; if(root == NULL) { cout << "Empty tree" << endl; } nodeptr curr, parent; while(curr) { if(curr->data == x) { found = true; break; } else { parent = curr; if(x > curr->data) { curr = curr->right; } else { curr = curr->left; } } if(!found) { cout << "not Found!" << endl; return; } //3 Cases: //case 2 if( ( (curr->left != NULL) && (curr->right == NULL) ) || ( (curr->left == NULL) && (curr->right != NULL) ) ) { if( (curr->left != NULL) && (curr->right == NULL) ) { if(parent->left == curr) { parent->left = curr->right; delete curr; } else { parent->right = curr->right; delete curr; } } else { if(parent->left == curr) { parent->left = curr->left; delete curr; } else { parent->right = curr->left; delete curr; } } return; } // case 1: if( (curr->left == NULL) && (curr->right == NULL) ) { if(parent->left == curr) { parent->left = NULL; delete curr; } else { parent->left = NULL; delete curr; } } //case 3: if( (curr->left != NULL) && (curr->right != NULL) ) { nodeptr checker; checker = curr->right; if( (checker->left == NULL) && (checker->right == NULL) ) { curr = checker; delete checker; curr->right = NULL; } else { // Choose the smallest in RIGHT subtree! if( (curr->right)->left != NULL ) { nodeptr lcurr, lcurrp; lcurrp = curr->right; lcurr = (curr->right)->left; while(lcurr->left != NULL) { lcurrp = lcurr; lcurr = lcurr->left; } curr->data = lcurr->data; delete lcurr; lcurrp->left = NULL; } else { nodeptr tmp; tmp = curr->right; curr->data = tmp->data; curr->right = tmp->right; delete tmp; } } } return ; } }
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; using Graph = vector<vector<int>>; const double PI = 3.14159265358979323846; const ll MOD = 1000000007; const int INF = 1e9; const int dx[4] = {1,0,-1,0}; const int dy[4] = {0,1,0,-1}; int main(){ ll X,Y,A,B; cin >> X >> Y >> A >> B; ll exp = 0; //先に過去問に通う while(X < Y / A && X * A < X + B){ X *= A; exp++; } exp += (Y - X -1)/ B; cout << exp << endl; return 0; }
#pragma once #include <vector> #include <memory> #include <algorithm> #include "Utils/ArrayView.hpp" #include "Nodes/OperationNode.hpp" #include "Nodes/ConstNode.hpp" #include "Nodes/VariableNode.hpp" #include "ConstStorage.hpp" #include "VariableStorage.hpp" #include "NodeBuilders/NodeBuilder.hpp" //BNN_TYPE using OperationNodes = std::vector<std::unique_ptr<OperationNode<BNN_TYPE>>>; using ConstNodes = std::vector<std::unique_ptr<ConstNode<BNN_TYPE>>>; using VariableNodes = std::vector<std::unique_ptr<VariableNode<BNN_TYPE>>>; struct BackPropagationNetwork { BackPropagationNetwork( OperationNodes && operationNodes, ConstNodes && constNodes, VariableNodes && variableNodes, std::unique_ptr<ConstStorage<BNN_TYPE>> constStorage, std::unique_ptr<VariableStorage<BNN_TYPE>> variableStorage, std::unique_ptr<VariableDeltaStorage<BNN_TYPE>> variableDeltaStorage, BNN_TYPE learningRate); ArrayView<BNN_TYPE const> forwardPass(ArrayView<BNN_TYPE const> input); void backPropagate(ArrayView<BNN_TYPE const> errors); void setLearningRate(BNN_TYPE learningRate); void setVariables(ArrayView<BNN_TYPE const> values); void setVariables(std::function<BNN_TYPE()> generator); void applyDeltaOnVariables(); void applyDeltaOnVariables(ArrayView<BNN_TYPE const> delta); ArrayView<BNN_TYPE const> getVariables() const; ArrayView<BNN_TYPE const> getVariableDeltas() const; private: std::size_t m_numBackpropagationPasses = 0; OperationNodes m_operationNodes; ConstNodes m_constNodes; VariableNodes m_variableNodes; std::unique_ptr<ConstStorage<BNN_TYPE>> m_constStorage; std::unique_ptr<VariableStorage<BNN_TYPE>> m_variableStorage; // teoretically no need for unique_ptr std::unique_ptr<VariableDeltaStorage<BNN_TYPE>> m_variableDeltaStorage; BNN_TYPE m_learningRate = 1.0f; };
#include "Result.h" #include <algorithm> #include <assert.h> #include "Common.h" #include <math.h> //#include <mutex> //std::mutex g_result_mutex; CResult::CResult(): m_nNum(10) { m_oOrderList.push_back(std::make_pair(RO_FACTOR, MB_ASC)); m_oOrderList.push_back(std::make_pair(RO_CLOSE, MB_ASC)); m_oOrderList.push_back(std::make_pair(RO_SIZE, MB_DESC)); m_oOrderList.push_back(std::make_pair(RO_FEATURES, MB_ASC)); } CResult::~CResult() { } void CResult::add(CTeamPtr pTeam, double* dFeatures, double* dRequiredFeatures) { //g_result_mutex.lock(); CResultItem oNewItem; initItem(pTeam, dFeatures, dRequiredFeatures, oNewItem); auto itr = std::upper_bound(m_oTeamList.begin(), m_oTeamList.end(), oNewItem, [this](const CResultItem& pItem1, const CResultItem& pItem2) { for each (auto oOrder in m_oOrderList) { bool bResult = false; switch (oOrder.first) { case RO_CLOSE: if (compare(oOrder.second, pItem1.dTotalNeedFeature, pItem2.dTotalNeedFeature, bResult)) return bResult; else break; case RO_FEATURES: if (compare(oOrder.second, pItem1.dTotalFeature, pItem2.dTotalFeature, bResult)) return bResult; else break; case RO_CLOSE_FEATURE: if (compare(oOrder.second, pItem1.dClosedFeature, pItem2.dClosedFeature, bResult)) return bResult; else break; case RO_MAX_CLOSE_FEATURE: if (compare(oOrder.second, pItem1.dMaxClosedFeature, pItem2.dMaxClosedFeature, bResult)) return bResult; else break; case RO_FIT_FEATURE_COUNT: if (compare(oOrder.second, pItem1.nFitCount, pItem2.nFitCount, bResult)) return bResult; else break; case RO_SIZE: if (compare(oOrder.second, pItem1.pTeam->size(), pItem2.pTeam->size(), bResult)) return bResult; else break; case RO_FACTOR: if (compare(oOrder.second, pItem1.dFactor, pItem2.dFactor, bResult)) return bResult; else break; default: assert(false); } } // 可能有重复 //assert(false); return false; }); m_oTeamList.insert(itr, oNewItem); if ((int)m_oTeamList.size() > m_nNum) { m_oTeamList.pop_back(); } //g_result_mutex.unlock(); } void CResult::add(CTeamPtr pTeam, double * dFeatures) { CResultItem oNewItem; initItem(pTeam, dFeatures, nullptr, oNewItem); for (auto itr = m_oTeamList.begin(); itr != m_oTeamList.end(); ) { auto nResult = compare(*itr, oNewItem); if (nResult > 0) { // 已经有大的了,不用添加 return; } else if (nResult < 0) { itr = m_oTeamList.erase(itr); //返回下一个有效的迭代器,无需+1 } else { ++itr; } } m_oTeamList.push_back(oNewItem); } void CResult::changeOrder(EnResultOrderType nType, int nAscOrDesc, int nOffset) { removeOrder(nType); if (nOffset > (int)m_oOrderList.size()) m_oOrderList.push_back(std::make_pair(nType, nAscOrDesc)); else m_oOrderList.insert(m_oOrderList.begin() + nOffset, std::make_pair(nType, nAscOrDesc)); } void CResult::merge(const CResult & oResult) { for each (auto oItem in oResult.m_oTeamList) { this->add(oItem.pTeam, oItem.dFeatures); } } void CResult::merge(const CResult & oResult, double* dRequiredFeatures) { for each (auto oItem in oResult.m_oTeamList) { this->add(oItem.pTeam, oItem.dFeatures, dRequiredFeatures); } } void CResult::removeOrder(EnResultOrderType nType) { auto itr = std::find_if(m_oOrderList.begin(), m_oOrderList.end(), [nType](std::pair<EnResultOrderType, int>& oItem) { return oItem.first == nType; }); if (itr != m_oOrderList.end()) m_oOrderList.erase(itr); } void CResult::initItem(CTeamPtr pTeam, double * dFeatures, double* dRequiredFeatures, CResultItem & oItem) { oItem.dTotalFeature = 0; for (int i = 0; i < EF_ALL; i++) { oItem.dTotalFeature += dFeatures[i]; oItem.dFeatures[i] = dFeatures[i]; } oItem.nFitCount = 0; oItem.dTotalNeedFeature = 0; oItem.dClosedFeature = 0; oItem.dMaxClosedFeature = 0; for (int i = 0; i < EF_ALL; i++) { if (1 << i & m_nFeatureSet) { oItem.dTotalNeedFeature += dFeatures[i]; if (dRequiredFeatures) { if (!(roundEx(dFeatures[i]) + g_dEpsilon > dRequiredFeatures[i])) { oItem.dClosedFeature += dRequiredFeatures[i] - dFeatures[i]; oItem.dMaxClosedFeature = std::max(oItem.dMaxClosedFeature, dRequiredFeatures[i] - dFeatures[i]); } else ++oItem.nFitCount; } } } oItem.dFactor = pTeam->getFactor(); oItem.pTeam = pTeam; } bool CResult::compare(int nAscOrDesc, double dVal1, double dVal2, bool & bResult) { if (abs(dVal1 - dVal2) < g_dEpsilon) return false; bResult = nAscOrDesc == MB_ASC ? dVal1 < dVal2 : dVal1 > dVal2; return true; } int CResult::compare(const CResultItem & oItem1, const CResultItem & oItem2) { bool bBig = false; bool bSmall = false; for (int i = 0; i < EF_ALL; i++) { if (oItem1.dFeatures[i] > oItem2.dFeatures[i] + g_dEpsilon) bBig = true; else if (oItem1.dFeatures[i] < oItem2.dFeatures[i] - g_dEpsilon) bSmall = true; } return bBig == bSmall ? 0 : (bBig ? 1 : -1); }
/* common definition */ #ifndef H_COMMON_H #define H_COMMON_H namespace P_RVD { /* the type for manipulating indeces */ typedef unsigned int t_index; typedef int signed_t_index; /* for glut */ typedef unsigned int uint; /* find the min value */ template <class T> T inline geo_min(T& a, T& b) { return (a < b) ? a : b; } /* find the max value */ template <class T> T inline geo_max(T& a, T& b) { return (a < b) ? b : a; } /* swap function */ template <class T> inline void geo_swap(T& a, T& b) { T c = a; a = b; b = c; } /** * \brief Integer constants that represent the sign of a value */ enum Sign { /** Value is negative */ NEGATIVE = -1, /** Value is zero */ ZERO = 0, /** Value is positive */ POSITIVE = 1 }; /** * \brief Gets the sign of a value * \details Returns -1, 0, or 1 whether value \p x is resp. negative, zero * or positive. The function uses operator<() and operator>() to compare * the value agains to 0 (zero). The integer constant zero must make * senses for the type of the value, or T must be constructible from * integer constant zero. * \param[in] x the value to test * \tparam T the type of the value * \return the sign of the value * \see Sign */ template <class T> inline Sign geo_sgn(const T& x) { return (x > 0) ? POSITIVE : ( (x < 0) ? NEGATIVE : ZERO ); } } #endif /* H_COMMON_H */
#include "httpworker.h" QHttpWorker::QHttpWorker(QObject *parent) : QObject(parent), _isWorking(false), _isPaused(false), _namanager(nullptr), _found_pos(nullptr), _id(0) { } QHttpWorker::~QHttpWorker() { qDebug()<<_id<<" Destroyed"; } void QHttpWorker::start() { if (!_isWorking){ if (!_namanager){ _namanager = new QNetworkAccessManager(); qDebug()<<_id<<"NA created"; connect(_namanager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyRecived(QNetworkReply*))); } if (!_found_pos){ _found_pos = new QVector<QPoint>(); } qRegisterMetaType<QVector<QPoint> >("QVector<QPoint>"); //requestWork(); } } void QHttpWorker::startSearch(QUrl url, QString text) { if (!_isWorking){ //resume(); _isWorking = true; _text = text; _url = url; _found_pos->clear(); qDebug()<<_id<<"GET send"; _namanager->get(QNetworkRequest(url)); } } void QHttpWorker::pause() { QMutexLocker locker(&_pause_mutex); _isPaused = true; } void QHttpWorker::resume() { QMutexLocker locker(&_pause_mutex); if (_isPaused){ _pause_sem.release(); _isPaused = false; } } void QHttpWorker::stop() { qDebug()<<_id<<" Stopped"; delete _namanager; delete _found_pos; emit finished(); } void QHttpWorker::replyRecived(QNetworkReply *reply) { if (_isPaused) _pause_sem.acquire(); QByteArray content = reply->readAll(); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); _page = codec->toUnicode(content.data()); //.split("\n"); qDebug()<<"Reply recived"; findUrls(); findText(); setWorking (false); QString header = _url.toString() + " - " + QString::number(_found_pos->size()) + " matches";; if(reply->error() != QNetworkReply::NoError){ header += " "+reply->errorString(); } emit searchFinished(header, _page, *_found_pos); qDebug()<<"Requesting work"; requestWork(_id); } void QHttpWorker::findUrls() { QRegExp url_reqexp ("(http://[!#$&-;=?-\\[\\]_a-z~]+)"); int pos = 0; while ((pos = url_reqexp.indexIn(_page, pos)) != -1) { if (_isPaused) _pause_sem.acquire(); emit urlFound(QUrl(url_reqexp.cap(1))); pos += url_reqexp.matchedLength(); } } void QHttpWorker::findText() { int pos = 0; int ln = _text.length(); while ((pos = _page.indexOf(_text, pos, _case_sens)) != -1) { if (_isPaused) _pause_sem.acquire(); _found_pos->append(QPoint(pos, _text.length())); pos += ln; } }
#include "Utilities.h" #include "Mesh.h" #include "Sphere.h" #include "Plane.h" #include "Cuboid.h" #include "Camera.h" #include "Ray.h" #include "MatrixStack.h" #include "Image.h" #include <vector> #include <iomanip> #include <iostream> #include <time.h> #include <ctime> #include <math.h> int main() { Image imgTest(1920, 1080 ); Camera cam(glm::vec3(0.05f, 1.5f, 0.0f), glm::vec3(0.05f, 1.5f, - 1.0f)); std::vector<Mesh*>* scene = new std::vector<Mesh*>; scene->push_back(new Cuboid(0.0f, 1.5f, -2.0f, 0.2f, 0.2f, 0.2f)); scene->push_back(new Cuboid(1.0f, 1.0f, -2.0f, 0.2f, 0.2f, 0.2f)); scene->push_back(new Cuboid(-1.0f, 1.5f, -2.0f, 0.2f, 0.2f, 0.2f)); //scene->push_back(new Plane(0.0f, 0.0f, 0.0f, 2.0f, 2.0f)); std::cout << "Rendering started...\n"; std::cout << "Image Dimensions: " << imgTest.x << "x" << imgTest.y << std::endl; clock_t begin = clock(); Ray* rIt; float x = (float) imgTest.x / (float) imgTest.y; float y = 1.0f;//(float) imgTest.y / (float) imgTest.x; float xCo = -x; float yCo = -y; float xStep = (2* x) / imgTest.x; float yStep = (2* y) / imgTest.y; //yStep = xStep; for (int i = 0; i < imgTest.y; i++) { yCo += yStep; xCo = -x; for (int j = 0; j < imgTest.x; j++) { xCo += xStep; glm::vec3 rDirection = glm::mat3(cam.getCTransform()) * (glm::vec3(xCo, yCo, -1.0f)); glm::vec3 rPos = glm::vec3(cam.getCTransform() * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); rIt = new Ray(rPos, rDirection, nullptr, scene); imgTest.imgData[i][j] = glm::vec3(rIt->evaluate()); delete rIt; } } clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; std::cout << "Rendering done. Elapsed time: " << elapsed_secs << " seconds." << std::endl; imgTest.saveBMP(); while (true) { } return 0; }
#include "stdafx.h" #include "energyDoc.h" using namespace std; energyDoc::energyDoc() { init(); } energyDoc::~energyDoc() { } void energyDoc::updateRealtime() { } void energyDoc::draw(BOOL mode[10]) { if (bitSetSpace) { glColor3f(1, 0, 0); bitSetSpace->drawBoundingBox(); } if (mode[1] && surObj) { glColor3f(0.8, 0.8, 0.8); surObj->drawObject(); } if (!mode[2] && voxel_Obj) { voxel_Obj->drawVoxel(); glColor3f(0.6, 0.6, 0.6); voxel_Obj->drawVoxelLeaf(1); } if (!mode[3] && voxel_Obj) { glColor3f(0.7, 0.7, 0.7); bitSetSpace->drawSolidBit(voxel_Obj->meshBitSet); glColor3f(0, 0, 1); bitSetSpace->drawWireBit(voxel_Obj->meshBitSet); } if (mode[4] && objEnergy) { glColor3f(0, 1, 0); voxel_Obj->m_octree.drawBoundingBox(); objEnergy->draw(); } if (mode[5] && curEnergyObj) { curEnergyObj->draw(energyMnager::DRAW_ALL); } } void energyDoc::draw2(bool mode[10]) { if (mode[1] && curSkeleton) // Skeleton { curSkeleton->draw(); } if (mode[2] && energyObjsOrigin) // Sphere energy { energyObjsOrigin->drawSphere(); } if (mode[3] && energyObjsOrigin) // Connection between sphere in bone { glColor3f(0, 0, 1); energyObjsOrigin->drawFixConstraint(); } if (mode[4] && energyObjsOrigin) // Neighbor { glColor3f(1, 1, 0); energyObjsOrigin->drawNeighbor(); } } void energyDoc::receiveKey(char c) { } void energyDoc::updateIdx(int yIdx, int zIdx) { } void energyDoc::init() { // 1. Init skeleton char * skePath = "../../Data/skeleton.xml"; cout << "load skeleton: " << skePath << endl; curSkeleton = skeletonPtr(new skeleton); curSkeleton->loadFromFile(skePath); originSkeleton = skeletonPtr(new skeleton); originSkeleton->loadFromFile(skePath); // 2. Init energy ball from skeleton cout << "Construct sphere energy from skeleton" << endl; energyObjsOrigin = energyMngerPtr(new energyMnager); energyObjsOrigin->initFromSkeleton(curSkeleton); boneScale = 0.5; cout << "Clone bone with scale ratio: " << boneScale << endl; curEnergyObj = energyObjsOrigin->clone(); curEnergyObj->scale(boneScale); // Volume match // 3. Load surface object char * surPath = "../../Data/Fighter/fighter.stl"; cout << "Load surface object: " << surPath << endl; surObj = SurfaceObjPtr(new SurfaceObj); surObj->readObjDataSTL(surPath); cout << "Construct AABB tree of surface" << endl; surObj->constructAABBTree(); // 4. Construct voxel float scale = 1.0; int voxelRes = 5; cout << "Construct voxel hashing (" << scale << " scale; " << voxelRes << " resolution" << endl; voxel_Obj = voxelObjectPtr(new voxelObject); voxel_Obj->init(surObj.get(), voxelRes, scale); // 4.a. Bit set space cout << "Construct bitset space." << endl; bitSetSpace = bitSetMngrPtr(new bitSetMangr); bitSetSpace->init(voxel_Obj); // 5. Sphere energy of mesh object int sphereRes = 3; cout << "Construct mesh sphere object (Res: " << sphereRes << ")" << endl; objEnergy = meshSphereObjPtr(new meshSphereObj); objEnergy->initFromMesh(surObj, voxel_Obj, bitSetSpace, sphereRes); displayOtherInfo(); } bool energyDoc::receiveCmd(std::vector<std::string> args) { return false; } void energyDoc::displayOtherInfo() { cout << "-----------------------------" << endl; cout << "Information:" << endl; // Volume match float meshVol = voxel_Obj->volumef(); float skeVol = curSkeleton->getVolume()*pow(boneScale, 3); float ratioVol = meshVol / skeVol; cout << "Volume ratio mesh / bone = " << ratioVol << endl; } void energyDoc::compute() { // 1. Force between mesh and skeleton // 1.a. Update mesh - bone intersection voxel_Obj->updateSphereOccupy(curEnergyObj); }
#ifndef ATTACH_H #include "Attach.h" #endif // ! ATTACH_H void testing::example_1() { // implementation of the code needed to test operation of slot solver // example taken from paper "Guiding and confining light in void nanostructure", Opt. Lett., 29 (11), 2004 double ns, nh, wh, ws, wl; wl = 1550; // wavelength in units of nm ns = 1.44; // slot index nh = 3.48; // slab index //wh = (180.0 / 1000.0); // slab thickness in units of nm //ws = (25 / 1000.0); // slot thickness in units of nm wh = 180.0; // slab thickness in units of nm ws = 25; // slot thickness in units of nm slot_neff waveguide; waveguide.set_params(wl, ws, wh, ns, nh, ns); waveguide.neff_search(true); } void testing::example_2() { // implementation of the code needed to test operation of slot solver // example taken from paper "Guiding and confining light in void nanostructure", Opt. Lett., 29 (11), 2004 double ns, nh, ncl, wh, ws, wl; wl = 1550; // wavelength in units of nm ns = 1.44; // slot index ncl = 1.0; // slot index nh = 3.48; // slab index //wh = (180.0 / 1000.0); // slab thickness in units of nm //ws = (25 / 1000.0); // slot thickness in units of nm wh = 180.0; // slab thickness in units of nm ws = 75; // slot thickness in units of nm slot_mode waveguide; waveguide.set_params(wl, ws, wh, ns, nh, ncl); waveguide.print_eigenequation(); waveguide.neff_search(true); int nn = 501; double lx = 1000.0; // length of solution domain in units of nm std::string storage_dir = empty_str; waveguide.output_mode_profile(nn, lx, storage_dir); waveguide.output_statistics(storage_dir); }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double ld; typedef long long ll; typedef unsigned long long ull; typedef unsigned int uint; const double PI = 3.1415926535897932384626433832795; template<typename T> T sqr(T x) { return x * x; } using namespace std; int n; /* double a, b; // входные данные const int N = 1000*1000; // количество шагов (уже умноженное на 2) double s = 0; double h = (b - a) / N; for (int i=0; i<=N; ++i) { double x = a + h * i; s += f(x) * ((i==0 || i==N) ? 1 : ((i&1)==0) ? 2 : 4); } s *= h / 3 */ int r[5], l[5]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); cin >> n; for (int i= 0; i < n; ++i) { cin >> l[i] >> r[i]; } ld sum = 0; for (int x = 0; x <= 10000; ++x) { for (int i = 0; i < n; ++i) if (l[i] <= x && x <= r[i]) for (int j = 0; j < n; ++j) if(j != i) { int u; if (j < i) u = x;else u = x + 1; if (u > r[j]) continue; ld pr = 1.0 / (r[i] - l[i] + 1); pr *= ld(r[j] - max(l[j], u) + 1) / (r[j] - l[j] + 1); for (int k = 0; k < n; ++k) if (k != i && k != j) { int d; if (k < i) d = x - 1;else d = x; if (l[k] > d) { pr = 0; break; }else if (r[k] < d) { continue; } pr *= ld(d - l[k] + 1) / (r[k] - l[k] + 1); } sum += pr * x; } } cout.precision(12); cout << fixed; cout << double(sum) << endl; return 0; }
#include "SqlGrammer.h" map<int, string> GrammerParameter::typeMap; void GrammerNode::addInfo(string st) { infos.push_back(st); } void GrammerNode::showInfo() { cout << "type:" << GrammerParameter::getType(type) << endl; for (string s : infos) { cout << s << endl; } cout << endl; } PhyPlanNode* GrammerNode::transform2PlanNode(GrammerNode* father) { switch (type) { case GrammerParameter::FROM: return transFmFrom(father); case GrammerParameter::CONDITION: return transFmCondition(); case GrammerParameter::CONNECTOR: return transFmConnector(); case GrammerParameter::ORDERLIST: return transFmOrder(); case GrammerParameter::PROJECT: return transFmProject(); case GrammerParameter::INSERT: return transFmInsert(); case GrammerParameter::DELETE: return transFmDelete(); case GrammerParameter::UPDATE: return transFmUpdate(); default: return NULL; } } PhyPlanNode* GrammerNode::transFmFrom(GrammerNode* father) { PhyPlanNode* ppnode = new PhyPlanNode(); bool useIndex = false;//判断是否使用索引遍历 string tableName = infos.at(0);//获取表名 if (father != nullptr) { //说明父结点为condition节点 for (int m = 0;m < father->infos.size();m+=2) { //a.b = 20 a = 20 string info = father->infos.at(m);//单条指令 vector<string> tmsp; Translator::getTranslator()->split(info, tmsp, ' '); string pre = tmsp.at(0);//即属性名 int dotposition = pre.find('.');//判断是否存在. if (dotposition < pre.length()) { //说明为a.b形式 pre = pre.substr(dotposition+1); } if (SqlGlobal::getInstance()->hasIndex(tableName, pre)) { //存在索引 useIndex = true;//有一个使用索引则直接退出 break; } } } if (useIndex) ppnode->methodName = "INDEXSCAN";//索引遍历 else ppnode->methodName = "SEQSCAN";//顺序遍历 ppnode->addParameter(infos.at(0)); return ppnode; } PhyPlanNode* GrammerNode::transFmCondition() { PhyPlanNode* ppnode = new PhyPlanNode(); ppnode->methodName = "FILTER";//此处暂不考虑IndexScan,若考虑可增加节点 for (string condition : infos) { //每一个condition为一个类似:a=b的条件或and连接符 ppnode->addParameter(condition); } return ppnode; } PhyPlanNode* GrammerNode::transFmOrder() { PhyPlanNode* ppnode = new PhyPlanNode(); ppnode->methodName = "SORT";//对属性进行显式排序 for (string rule : infos) { //rule:a desc vector<string> ord; Translator::getTranslator()->split(rule, ord, ' '); ppnode->addParameter(ord.at(0)); ppnode->addParameter(ord.at(1)); } return ppnode; } PhyPlanNode* GrammerNode::transFmProject() { PhyPlanNode* ppnode = new PhyPlanNode(); ppnode->methodName = "SELECT"; for (string attr : infos) { //attr为每一个属性 ppnode->addParameter(attr); } return ppnode; } PhyPlanNode* GrammerNode::transFmConnector() { PhyPlanNode* ppnode = new PhyPlanNode(); GrammerNode* lrelation = left;//左关系表 GrammerNode* rrelation = right;//右关系表 for (string info : infos) { ppnode->addAddition(info); } ppnode->methodName = "JOIN";//此处默认选择一趟散列连接 if(lrelation->type == GrammerParameter::FROM)//若为连接符则左参数忽略 ppnode->addParameter(lrelation->infos.at(0));//参数1:左表名 if (rrelation->type == GrammerParameter::FROM) ppnode->addParameter(rrelation->infos.at(0));//参数2:右表名 //int cacheNum = 50;//应由左右表计算所需缓冲区大小,此处默认选为50 //ppnode->addParameter(to_string(cacheNum));//参数3:缓冲区块大小 return ppnode; } PhyPlanNode* GrammerNode::transFmDelete() { PhyPlanNode* pnode = new PhyPlanNode(); pnode->methodName = "DELETE"; return pnode; } PhyPlanNode* GrammerNode::transFmInsert() { PhyPlanNode* pnode = new PhyPlanNode(); pnode->methodName = "INSERT"; for (string info : infos) { pnode->addParameter(info); } return pnode; } PhyPlanNode* GrammerNode::transFmUpdate() { PhyPlanNode* pnode = new PhyPlanNode(); pnode->methodName = "UPDATE"; for (string attr_index : infos) { pnode->addParameter(attr_index); } return pnode; } void SqlGrammer::bacLoopTree(GrammerNode* node) { cout << endl; if (node->left == NULL && node->right == NULL) { node->showInfo(); return; } if (node->left != NULL) { bacLoopTree(node->left); } if (node->right != NULL) { bacLoopTree(node->right); } node->showInfo(); } void SqlGrammer::showInfo() { bacLoopTree(root); } PhyPlanNode* SqlGrammer::transform2PhysicPlan() { return copyFromGrammer(root); } void SqlGrammer::optimiza() { optimizeConnect();//优化connect optimizeSelect();//优化select cout << endl << "优化完毕:" << endl; showInfo(); } PhyPlanNode* SqlGrammer::copyFromGrammer(GrammerNode* gnode) { if (gnode == nullptr) return nullptr; GrammerNode* father = nullptr; if (gnode->type == GrammerParameter::FROM) { father = findFatherNode(gnode, root);//若此节点为FROM节点则获取其父节点 if (father && father->type != GrammerParameter::CONDITION) father = nullptr;//父节点需要为condition节点 } PhyPlanNode* newppnode = gnode->transform2PlanNode(father);//表达式节点转换为物理计划节点 newppnode->left = copyFromGrammer(gnode->left); newppnode->right = copyFromGrammer(gnode->right); return newppnode; } void SqlGrammer::optimizeSelect() { cout <<endl<< "查询优化----选择后移" << endl; queue<GrammerNode*> nodeQueue; nodeQueue.push(root); while (!nodeQueue.empty()) { //层次遍历 GrammerNode* target = nodeQueue.front(); nodeQueue.pop(); //处理target if (target->type == GrammerParameter::CONDITION) { //为查询条件结点 vector<string>*effectedTables = findTablesByAttr(target);//获取condition所作用的表名 if (effectedTables->size() == 1) { //说明仅一张表,则无需优化 continue; } int size = target->infos.size();//获取条件容器大小 bool hasOr = false; bool hasAnd = false; for (string con : target->infos) { if (con == "or" || con == "OR") { //若存在or则不进行处理 hasOr = true; } else if (con == "and" || con == "AND") { hasAnd = true; } } if (hasOr || !hasAnd) { //存在or则不进行处理 if(hasOr || target->infos.empty()) continue; else { //说明没有and则在此进行进一步判断 vector<string> cons; string condition = target->infos.at(0);//仅有一个语句 Translator::getTranslator()->split(condition, cons, ' '); //pre opt bac => a = 'c' string pre = cons[0]; string opt = cons[1]; string bac = cons[2]; if (bac[0] == '\'' || bac[0] >= '0' && bac[0] <= '9') { cons.clear(); string sourceTable = ""; if (pre.find('.') < pre.size()) { //为a.b格式 Translator::getTranslator()->split(pre, cons, '.'); sourceTable = cons[0];//获取表名 } else { //未显式说明则需要查找对应表 sourceTable = findAttrSource(pre, *effectedTables); } if (sourceTable == "") continue;//说明匹配表多于1张或为0张 else { //进行优化 GrammerNode* srcNode = findNodeByInfo(sourceTable, target);//找到表名对应的结点 GrammerNode* targetFather = findFatherNode(srcNode, target);//找到sourceTable对应的父结点 if (targetFather->type == GrammerParameter::CONDITION) { //已经为condition则不需要再创建节点 targetFather->addInfo(condition); } else { GrammerNode* newNode = new GrammerNode(); newNode->addInfo(condition);//插入新结点 newNode->type = GrammerParameter::CONDITION; newNode->left = srcNode; if (targetFather->left == srcNode) targetFather->left = newNode; else if (targetFather->right == srcNode) targetFather->right = newNode; } //此结点可取消 targetFather = findFatherNode(target, root); if (targetFather->left == target) { targetFather->left = target->left; } else if (targetFather->right == target) targetFather->right == target; nodeQueue.push(targetFather->left);//为后续遍历做准备 delete target; target = nullptr; } } else { continue; } } } else { //不存在or并且存在and则进行处理 int conditionLen = (size + 1) / 2;//除去and的condition数 vector<string>::iterator itr = target->infos.begin(); for (int m = 1;m <= (size-1)/2;m++) { target->infos.erase(itr + m); }//暂时清除and int eraseNum = 0;//记录移出condition的数目 for (int m = 0;m < conditionLen;m++) { int index = m; string condition = target->infos[index-eraseNum]; vector<string> cons; Translator::getTranslator()->split(condition, cons, ' '); //pre opt bac => a = 'c' string pre = cons[0]; string opt = cons[1]; string bac = cons[2]; if (bac[0] == '\'' || bac[0] >= '0' && bac[0] <= '9') { //说明为字符串或为数字,则可分离 cons.clear(); string sourceTable = ""; if (pre.find('.')<pre.size()) { //为a.b格式 Translator::getTranslator()->split(pre, cons, '.'); sourceTable = cons[0];//获取表名 } else { //未显式说明则需要查找对应表 sourceTable = findAttrSource(pre, *effectedTables); } if (sourceTable == "") continue;//说明匹配表多于1张或为0张 else { //进行优化 GrammerNode* srcNode = findNodeByInfo(sourceTable, target);//找到表名对应的结点 GrammerNode* targetFather = findFatherNode(srcNode, target);//找到sourceTable对应的父结点 if (targetFather->type == GrammerParameter::CONDITION) { //已为父结点则无需创建新节点 targetFather->addInfo("and"); targetFather->addInfo(condition); } else { GrammerNode* newNode = new GrammerNode(); newNode->addInfo(condition);//插入新结点 newNode->type = GrammerParameter::CONDITION; newNode->left = srcNode; if (targetFather->left == srcNode) targetFather->left = newNode; else if (targetFather->right == srcNode) targetFather->right = newNode; } target->infos.erase(target->infos.begin() + index-eraseNum);//移出condition eraseNum++;//移出数增加 } } } if (target->infos.empty()) { //若为空则此结点可取消 GrammerNode* targetFather = findFatherNode(target, root); if (targetFather->left == target) { targetFather->left = target->left; } else if (targetFather->right == target) targetFather->right == target; nodeQueue.push(targetFather->left);//为后续遍历做准备 delete target; target = nullptr; } else { //根据大小插入and int remainSize = target->infos.size(); int insertNum = remainSize - 1; for (int m = 1;m <= insertNum;m++) { int inum = m * 2 - 1; target->infos.insert(target->infos.begin() + inum, "and"); } } } } if (target == nullptr) { continue; } if (target->left) nodeQueue.push(target->left); if (target->right) nodeQueue.push(target->right); } } void SqlGrammer::optimizeConnect() { GrammerNode* conRoot = findConnect();//获取第一个connect结点 if (conRoot == nullptr) return; if (!isAllNatural(conRoot))//仅当全为自然连接时进行优化 return; vector<ConnectorNode*> cnodes; findConnectTable(conRoot, cnodes);//填充连接结点向量,即cnodes ConnectorOptimizer conOpt(cnodes);//连接优化器 conOpt.optimizer();//执行优化 vector<ConnectorNode*>* best = conOpt.best; queue<string>tableName; for (ConnectorNode* cnode : *best) { tableName.push(cnode->tableName); cout << cnode->tableName << " "; } updateConnectOrder(conRoot, tableName);//更新连接顺序 } void SqlGrammer::updateConnectOrder(GrammerNode* croot, queue<string>& order) { //采用后根遍历的顺序更新顺序 if (croot == nullptr) return; updateConnectOrder(croot->left, order); updateConnectOrder(croot->right, order); if (croot->type == GrammerParameter::FROM) { croot->infos[0] = order.front(); order.pop(); } } int SqlGrammer::isAllNatural(GrammerNode* croot) { stack<GrammerNode*> cstack; cstack.push(croot); while (croot->left && croot->left->type == GrammerParameter::CONNECTOR) { cstack.push(croot->left); croot = croot->left; } int isAllNatural = 1; while (!cstack.empty()) { if (cstack.top()->infos.empty()) { isAllNatural = 0; break; }else if (cstack.top()->infos[0] != "@natural@") { isAllNatural = 0; break; } cstack.pop(); } return isAllNatural; } vector<string>* SqlGrammer::findTablesByAttr(GrammerNode* condition) { while (condition->left && condition->left->type == GrammerParameter::CONDITION) { condition = condition->left; } vector<string>* tableNames = new vector<string>; if (condition->left == nullptr) return nullptr; if (condition->left->type == GrammerParameter::FROM) { tableNames->push_back(condition->left->infos[0]);//说明无表连接,则直接返回表名 return tableNames; } else if (condition->left->type == GrammerParameter::CONNECTOR) { //说明为表连接,则至少有两张表 queue<GrammerNode*> tmpQueue; tmpQueue.push(condition->left); //以condition为根结点进行层次遍历 while (!tmpQueue.empty()) { GrammerNode* tar = tmpQueue.front(); if (tar->type == GrammerParameter::FROM) { tableNames->push_back(tar->infos[0]);//若为from则取得名字 } tmpQueue.pop(); if (tar->left) { tmpQueue.push(tar->left); } if (tar->right) { tmpQueue.push(tar->right); } } return tableNames; } return nullptr; } //vector<string>* SqlGrammer::findConnectTables(GrammerNode* conRoot) //{ // vector<string>* tables = new vector<string>; // queue<GrammerNode*> gnodes; // gnodes.push(conRoot); // while (!gnodes.empty()) { // GrammerNode* target = gnodes.front(); // gnodes.pop(); // if (target->type == GrammerParameter::FROM) // tables->push_back(target->infos[0]); // // if (target->left) // gnodes.push(target->left); // if (target->right) // gnodes.push(target->right); // } // return tables; //} void SqlGrammer::findConnectTable(GrammerNode* conRoot, vector<ConnectorNode*>& cnodes) { GrammerNode* target = conRoot; stack<GrammerNode*> gstack; gstack.push(target); while (target->left && target->left->type == GrammerParameter::CONNECTOR) { gstack.push(target->left); target = target->left; } target = gstack.top();//最后一个connector gstack.pop(); GrammerNode* lenode = target->left;//左结点 ConnectorNode* lcnode = createConnectNode(lenode); GrammerNode* rinode = target->right;//右结点 ConnectorNode* rcnode = createConnectNode(rinode); cnodes.push_back(lcnode); cnodes.push_back(rcnode); //非叶子connecor仅有右子结点 while (!gstack.empty()) { target = gstack.top(); gstack.pop(); rinode = target->right; cnodes.push_back(createConnectNode(rinode)); } } ConnectorNode* SqlGrammer::createConnectNode(GrammerNode* target) { ConnectorNode* cnode = new ConnectorNode(); cnode->T = SqlGlobal::getInstance()->getT(target->infos[0]);//获取T值 cnode->tableName = target->infos[0]; vector<string> attrs = SqlGlobal::getInstance()->getAttribute(cnode->tableName);//获取表的所有属性 for (string attribute : attrs) { //遍历 int v = SqlGlobal::getInstance()->getV(cnode->tableName, attribute);//计算此属性对应的v值 cnode->Vs[attribute] = v; } return cnode; } GrammerNode* SqlGrammer::findFatherNode(GrammerNode* child, GrammerNode* head) { queue<GrammerNode*> gnodes; gnodes.push(head); while (!gnodes.empty()) { GrammerNode* target = gnodes.front(); gnodes.pop(); if (target->left == child || target->right == child) { return target; } if (target->left) gnodes.push(target->left); if (target->right) gnodes.push(target->right); } return nullptr; } GrammerNode* SqlGrammer::findFatherNode(string childInfo, GrammerNode* head) { queue<GrammerNode*> gnodes; gnodes.push(head); while (!gnodes.empty()) { GrammerNode* target = gnodes.front(); gnodes.pop(); if (target->left && target->left->type == GrammerParameter::FROM && target->left->infos[0] == childInfo || \ target->right && target->right->type == GrammerParameter::FROM && target->right->infos[0] == childInfo) { return target; } if (target->left) gnodes.push(target->left); if (target->right) gnodes.push(target->right); } return nullptr; } GrammerNode* SqlGrammer::findNodeByInfo(string info, GrammerNode* head) { queue<GrammerNode*> gnodes; gnodes.push(head); while (!gnodes.empty()) { GrammerNode* target = gnodes.front(); gnodes.pop(); if (target->type == GrammerParameter::FROM && target->infos[0] == info) { return target; } if (target->left) gnodes.push(target->left); if (target->right) gnodes.push(target->right); } return nullptr; } GrammerNode* SqlGrammer::findConnect() { queue<GrammerNode*> gqueue; gqueue.push(root); while (!gqueue.empty()) { GrammerNode* target = gqueue.front(); gqueue.pop(); if (target->type == GrammerParameter::CONNECTOR) return target; if (target->left) gqueue.push(target->left); if (target->right) gqueue.push(target->right); } return nullptr; } string SqlGrammer::findAttrSource(string attrName, vector<string>& tableNames) { int blongNum = 0;//属于的表数 string blongTableName; for (string tableName : tableNames) { //若tableName表存在attrName属性,则blongNum+1 vector<string>tableAttr = SqlGlobal::getInstance()->getAttribute(tableName);//获取表拥有的属性 for (string attr : tableAttr) { //attr为表内具有的属性 if (attr == attrName) { blongNum += 1; blongTableName = tableName; break; } } } if (blongNum == 1) { return blongTableName; } return ""; } void GrammerParameter::initMap() { typeMap[1] = "from"; typeMap[2] = "connector"; typeMap[3] = "condition"; typeMap[4] = "project"; typeMap[5] = "deduplicate"; typeMap[6] = "orderlist"; typeMap[7] = "insert"; typeMap[8] = "update"; typeMap[9] = "delete"; } string GrammerParameter::getType(int type) { typeMap.clear(); initMap(); return typeMap.find(type)->second; }
#include "CKobuki.h" #include "Helpers.h" #include <vector> #include <iostream> #pragma warning( push ) #pragma warning( disable : 4838) int CKobuki::checkChecksum(unsigned char* data) { unsigned char chckSum = 0; if (data == NULL) { return -1; } for (int i = 0; i < data[0] + 2; i++) { chckSum ^= data[i]; } return chckSum;//0 ak je vsetko v poriadku,inak nejake cislo } std::vector<unsigned char> CKobuki::getLedCmd(int led1, int led2) { unsigned char message[8] = { 0xaa,0x55,0x04,0x0c,0x02,0x00,(led1 + led2 * 4) % 256,0x00 }; message[7] = message[2] ^ message[3] ^ message[4] ^ message[5] ^ message[6]; std::vector<unsigned char> vystup(message, message + sizeof(message) / sizeof(message[0])); return vystup; } std::vector<unsigned char> CKobuki::getTranslationCmd(int mmpersec) { unsigned message[14] = { 0xaa,0x55,0x0A,0x0c,0x02,0xf0,0x00,0x01,0x04,mmpersec % 256,mmpersec >> 8,0x00,0x00, 0x00 }; message[13] = message[2] ^ message[3] ^ message[4] ^ message[5] ^ message[6] ^ message[7] ^ message[8] ^ message[9] ^ message[10] ^ message[11] ^ message[12]; std::vector<unsigned char> vystup(message, message + sizeof(message) / sizeof(message[0])); return vystup; } std::vector<unsigned char> CKobuki::getRotationCmd(double radpersec) { int speedvalue = (int) (radpersec * 230.0 / 2.0); unsigned char message[14] = { 0xaa,0x55,0x0A,0x0c,0x02,0xf0,0x00,0x01,0x04,speedvalue % 256,speedvalue >> 8,0x01,0x00, 0x00 }; message[13] = message[2] ^ message[3] ^ message[4] ^ message[5] ^ message[6] ^ message[7] ^ message[8] ^ message[9] ^ message[10] ^ message[11] ^ message[12]; std::vector<unsigned char> vystup(message, message + sizeof(message) / sizeof(message[0])); return vystup; } std::vector<unsigned char> CKobuki::getArcCmd(int mmpersec, int radius) { if (radius == 0) { return getTranslationCmd(mmpersec); } int speedvalue = (int) round( mmpersec * ((radius + (radius > 0 ? 230.0 : -230.0)) / 2.0) / radius); unsigned char message[14] = { 0xaa,0x55,0x0A,0x0c,0x02,0xf0,0x00,0x01,0x04,mmpersec % 256,mmpersec >> 8,radius % 256,radius >> 8, 0x00 }; message[13] = message[2] ^ message[3] ^ message[4] ^ message[5] ^ message[6] ^ message[7] ^ message[8] ^ message[9] ^ message[10] ^ message[11] ^ message[12]; std::vector<unsigned char> vystup(message, message + sizeof(message) / sizeof(message[0])); return vystup; } std::vector<unsigned char> CKobuki::getArc2Cmd(int mmPerSec, double radPerSec) { if (abs(radPerSec) < 1e-5) return getTranslationCmd(mmPerSec); double r = mmPerSec / radPerSec; int rVal = (int)round(r); if (abs(rVal) > 10000) rVal = 0; return getArcCmd(mmPerSec, rVal); } std::vector<unsigned char> CKobuki::getSoundCmd(int noteinHz, int duration) { int notevalue = (int) floor(1.0 / ((double)noteinHz * 0.00000275) + 0.5); unsigned char message[13] = { 0xaa,0x55,0x09,0x0c,0x02,0xf0,0x00,0x03,0x03,notevalue % 256,notevalue >> 8,duration % 256,0x00 }; message[12] = message[2] ^ message[3] ^ message[4] ^ message[5] ^ message[6] ^ message[7] ^ message[8] ^ message[9] ^ message[10] ^ message[11]; std::vector<unsigned char> vystup(message, message + sizeof(message) / sizeof(message[0])); return vystup; } std::vector<unsigned char> CKobuki::getPIDCmd() { unsigned char message[23] = { 0xaa,0x55,0x13,0x0c,0x02,0xf0,0x00,0x0D,0x0D,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00 }; message[22] = 0; for (int i = 0; i < 23 - 3; i++) { message[22] = message[22] ^ message[i + 2]; } std::vector<unsigned char> vystup(message, message + sizeof(message) / sizeof(message[0])); return vystup; } #pragma warning( pop ) int CKobuki::parseKobukiMessage() { unsigned char* data = robotBuff.get(); int rtrnvalue = checkChecksum(data); //ak je zly checksum,tak kaslat na to if (rtrnvalue != 0) return -2; int checkedValue = 1; //kym neprejdeme celu dlzku while (checkedValue < data[0]) { //basic data subload switch (data[checkedValue++]) { case 0x01: { if (data[checkedValue++] != 0x0F) return -1; robotData.timestamp = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.BumperCenter = data[checkedValue] & 0x02; robotData.BumperLeft = data[checkedValue] & 0x04; robotData.BumperRight = data[checkedValue++] & 0x01; robotData.WheelDropLeft = data[checkedValue] & 0x02; robotData.WheelDropRight = data[checkedValue++] & 0x01; robotData.CliffCenter = data[checkedValue] & 0x02; robotData.CliffLeft = data[checkedValue] & 0x04; robotData.CliffRight = data[checkedValue++] & 0x01; robotData.EncoderLeft = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.EncoderRight = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.PWMleft = data[checkedValue++]; robotData.PWMright = data[checkedValue++]; robotData.ButtonPress = data[checkedValue++]; robotData.Charger = data[checkedValue++]; robotData.Battery = data[checkedValue++]; robotData.overCurrent = data[checkedValue++]; break; } case 0x03: { if (data[checkedValue++] != 0x03) return -3; robotData.IRSensorRight = data[checkedValue++]; robotData.IRSensorCenter = data[checkedValue++]; robotData.IRSensorLeft = data[checkedValue++]; break; } case 0x04: { if (data[checkedValue++] != 0x07) return -4; robotData.GyroAngle = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.GyroAngleRate = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 5;//3 unsued break; } case 0x05: { if (data[checkedValue++] != 0x06) return -5; robotData.CliffSensorRight = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.CliffSensorCenter = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.CliffSensorLeft = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; break; } case 0x06: { if (data[checkedValue++] != 0x02) return -6; robotData.wheelCurrentLeft = data[checkedValue++]; robotData.wheelCurrentRight = data[checkedValue++]; break; } case 0x0A: { if (data[checkedValue++] != 0x04) return -7; robotData.extraInfo.HardwareVersionPatch = data[checkedValue++]; robotData.extraInfo.HardwareVersionMinor = data[checkedValue++]; robotData.extraInfo.HardwareVersionMajor = data[checkedValue]; checkedValue += 2; break; } case 0x0B: { if (data[checkedValue++] != 0x04) return -8; robotData.extraInfo.FirmwareVersionPatch = data[checkedValue++]; robotData.extraInfo.FirmwareVersionMinor = data[checkedValue++]; robotData.extraInfo.FirmwareVersionMajor = data[checkedValue]; checkedValue += 2; break; } case 0x0D: { if (data[checkedValue++] % 2 != 0) return -9; robotData.frameId = data[checkedValue++]; int howmanyFrames = data[checkedValue++] / 3; robotData.gyroData.reserve(howmanyFrames); robotData.gyroData.clear(); for (int hk = 0; hk < howmanyFrames; hk++) { TRawGyroData temp; temp.x = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; temp.y = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; temp.z = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.gyroData.push_back(temp); } break; } case 0x10: { if (data[checkedValue++] != 0x10) return -10; robotData.digitalInput = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.analogInputCh0 = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.analogInputCh1 = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.analogInputCh2 = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 2; robotData.analogInputCh3 = data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 8;//2+6 break; } case 0x13: { if (data[checkedValue++] != 0x0C) return -11; robotData.extraInfo.UDID0 = data[checkedValue + 3] * 256 * 256 * 256 + data[checkedValue + 2] * 256 * 256 + data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 4; robotData.extraInfo.UDID1 = data[checkedValue + 3] * 256 * 256 * 256 + data[checkedValue + 2] * 256 * 256 + data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 4; robotData.extraInfo.UDID2 = data[checkedValue + 3] * 256 * 256 * 256 + data[checkedValue + 2] * 256 * 256 + data[checkedValue + 1] * 256 + data[checkedValue]; checkedValue += 4; break; } default: { checkedValue += data[checkedValue] + 1; break; } } // switch end } //while end return 0; }
#include "shape.h" shape::shape() { //ctor } shape::~shape() { //dtor }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #define MAX_S 60000000000 #define INF (1<<30) using namespace std; class PerfectSequences { public: string fixIt(vector <int> seq) { if (seq.size()==1) { return "Yes"; } long long max = 0; for (int i=0; i<seq.size(); ++i) { max += 2000000000; } sort(seq.begin(), seq.end()); if (seq[1] < 0) { return "No"; } for (int del=0; del<seq.size(); ++del) { if (seq[0] < 0 && del!= 0) { continue; } long long p = 1; for (int i=0; i<seq.size(); ++i) { if (del != i) { p = (p*seq[i])<max ? p*seq[i] : -1; } } long long S = 0; for (int i=0; i<seq.size(); ++i) { if (del != i) { S += seq[i]; } } if (p >= 0 && p != 1 && S%(p-1)==0) { if (S/(p-1) == seq[del] || (p==0&&S!=0)) { continue; } return "Yes"; } } return "No"; } };
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; string st; bool check(int l,int r) { //cout << l << " " << r << endl; while (l < r) { if (st[l] != st[r]) return false; l++;r--; } return true; } int main() { int k; cin >> st >> k; int len = st.size()/k; if (st.size()%k) cout << "NO" << endl; else { bool ans = true; for (int i = 1;i <= k; i++) if (!check((i-1)*len,i*len-1)) { ans = false; break; } if (ans) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <ctime> #include <cmath> #include <string> #include <cctype> #include <cstring> #include <algorithm> #include<climits> using namespace std; typedef long long ll; ll ind; ll factor[110000]; #define uint unsigned int #define ull unsigned long long ull ans=LLONG_MAX; ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); } ll mod_mul(ll x,ll y,ll mod) { x%=mod; y%=mod; ll t=0; while(y) { if(y&1) t=(t+x)%mod; x=(x<<1)%mod; y>>=1; } return t; } ll mod_pow(ll x,ll n,ll mod) { x%=mod; ll res=1; while(n) { if(n&1) res=mod_mul(res,x,mod); x=mod_mul(x,x,mod); n>>=1; } return res; } bool witness(ll n,ll a,ll u,int cnt) { ll x=mod_pow(a,u,n); ll t=x; for(int i=1; i<=cnt; i++) { t=x; x=mod_mul(x,x,n); if(x==1&&t!=1&&t!=n-1) return true; } if(x!=1) return true; return false; } bool miller_rabin(ll n,int s) { if(n<2)return false; if(n==2)return true; if(!(n&1))return false; int cnt=0; ll u=n-1; while(!(u&1)) { cnt++; u=u>>1; } ll a; for(int i=1; i<=s; i++) { a=rand()%(n-1)+1; if(witness(n,a,u,cnt)) return false; } return true; } ll pollarn_rho(ll n,ll c) { if(!(n&1)) return 2; ll x=rand()%n; ll y=x; ll i=1; ll k=2; while(true) { i++; x=(mod_mul(x,x,n)+c)%n; ll d=gcd(y-x+n,n); if(d!=1&&d!=n) return d; if(y==x) return n; if(i==k) { y=x; k+=k; } } } void Find(ll n) { if(miller_rabin(n,20)) { factor[ind++]=n; return; } ll p=n; while(p>=n) p=pollarn_rho(p,(ll)(rand()%(n-1)+1)); Find(p); Find(n/p); } int main() { // ios::sync_with_stdio(false); // cin.tie(0); ll n; int s=20; while(~scanf("%lld",&n)) { if(n==1) { cout<<"is not a D_num\n"; continue; } ind=0; Find(n); if(ind!=2&&ind!=3) { cout<<"is not a D_num"<<"\n"; continue; } sort(factor,factor+ind); if(ind==2) { if(factor[0]!=factor[1]) cout<<factor[0]<<" "<<factor[1]<<" "<<n<<"\n"; else cout<<"is not a D_num"<<"\n"; } else { if(factor[0]==factor[1]&&factor[1]==factor[2]) cout<<factor[0]<<" "<<factor[0]*factor[0]<<" "<<n<<"\n"; else cout<<"is not a D_num"<<"\n"; } } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #ifndef __SSLCIPHER_H #define __SSLCIPHER_H #ifdef _NATIVE_SSL_SUPPORT_ class SSL_Cipher: public SSL_Error_Status { public: #ifdef USE_SSL_PGP_CFB_MODE enum PGP_CFB_Mode_Type { PGP_CFB_Mode_Disabled, PGP_CFB_Mode_Enabled, PGP_CFB_Mode_Enabled_No_Resync }; #endif protected: SSL_PADDING_strategy appendpad; SSL_BulkCipherType cipher_alg; SSL_CipherType cipher_type; uint16 in_block_size; uint16 out_block_size; public: SSL_Cipher():appendpad(SSL_NO_PADDING), cipher_alg(SSL_NoCipher), cipher_type(SSL_StreamCipher),in_block_size(1),out_block_size(1) {} SSL_CipherType CipherType() const{return cipher_type;} SSL_BulkCipherType CipherID() const{return cipher_alg;} virtual void SetPaddingStrategy(SSL_PADDING_strategy); virtual SSL_PADDING_strategy GetPaddingStrategy(); virtual void InitEncrypt()=0; virtual byte *Encrypt(const byte *source,uint32 len,byte *target, uint32 &,uint32 bufferlen)=0; void EncryptVector(const SSL_varvector32 &, SSL_varvector32 &); virtual byte *FinishEncrypt(byte *target, uint32 &, uint32)=0; virtual void InitDecrypt()=0; virtual byte *Decrypt(const byte *source,uint32 len,byte *target, uint32 &,uint32 bufferlen)=0; void DecryptVector(const SSL_varvector32 &source, SSL_varvector32 &target); virtual byte *FinishDecrypt(byte *target, uint32 &,uint32 bufferlen)=0; #ifdef USE_SSL_PGP_CFB_MODE virtual void CFB_Resync(); virtual void SetPGP_CFB_Mode(SSL_Cipher::PGP_CFB_Mode_Type mode); virtual void UnloadPGP_Prefix(SSL_varvector32 &); #endif /** InitDecrypt must be called first, FinishDecrypt called if source has no MoreData */ uint32 DecryptStreamL(DataStream *source, DataStream *target, uint32 len=0); /** InitEncrypt must be called first, FinishDecrypt is called if source is NULL */ uint32 EncryptStreamL(DataStream *source, DataStream *target, uint32 len=0); uint16 InputBlockSize() const{return in_block_size;} uint16 OutputBlockSize() const{return out_block_size;}; uint32 Calc_BufferSize(uint32); }; class SSL_GeneralCipher: public SSL_Cipher { protected: uint16 key_size; uint16 iv_size; public: SSL_GeneralCipher():key_size(0), iv_size(0) {} virtual void SetCipherDirection(SSL_CipherDirection dir)=0; virtual uint16 KeySize() const{return key_size;} virtual uint16 IVSize() const{return iv_size;} virtual const byte *LoadKey(const byte *)=0; virtual const byte *LoadIV(const byte *)=0; virtual void BytesToKey(SSL_HashAlgorithmType, const SSL_varvector32 &string, const SSL_varvector32 &salt, int count)= 0; }; #endif #endif
#pragma once #include "Keng/Core/ISystem.h" #include "Keng/FileSystem/FwdDecl.h" #include "Keng/ResourceSystem/FwdDecl.h" #include "Keng/ResourceSystem/IResource.h" namespace keng::resource { class IResourceSystem : public core::ISystem { public: static const char* SystemName() { return "KengResourceSystem"; } virtual IResourcePtr GetResource(const char* filename) = 0; virtual IResourcePtr GetResource(const char* filename, const IDevicePtr& deivce) = 0; virtual void AddRuntimeResource(const IResourcePtr& resource) = 0; virtual void AddRuntimeResource(const IResourcePtr& resource, const IDevicePtr& deivce) = 0; virtual void RegisterResourceFabric(const IResourceFabricPtr& fabric) = 0; virtual void UnregisterFabric(const IResourceFabricPtr& fabric) = 0; virtual ~IResourceSystem() = default; }; }
// Created on: 1995-10-19 // Created by: Andre LIEUTIER // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Plate_PinpointConstraint_HeaderFile #define _Plate_PinpointConstraint_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <gp_XYZ.hxx> #include <gp_XY.hxx> //! define a constraint on the Plate class Plate_PinpointConstraint { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Plate_PinpointConstraint(); Standard_EXPORT Plate_PinpointConstraint(const gp_XY& point2d, const gp_XYZ& ImposedValue, const Standard_Integer iu = 0, const Standard_Integer iv = 0); const gp_XY& Pnt2d() const; const Standard_Integer& Idu() const; const Standard_Integer& Idv() const; const gp_XYZ& Value() const; protected: private: gp_XYZ value; gp_XY pnt2d; Standard_Integer idu; Standard_Integer idv; }; #include <Plate_PinpointConstraint.lxx> #endif // _Plate_PinpointConstraint_HeaderFile
#include<iostream> #include <typeinfo> #define OK 1 #define ERROR 0 #define OVERFLOW -2 using namespace std; typedef int QElemType; typedef struct QNode { QElemType data; struct QNode *next; } QNode ,*QueuePtr; typedef struct { QueuePtr front; QueuePtr rear; } LinkQueue; int InitQueue(LinkQueue &Q) { try { Q.front=Q.rear=new QNode; Q.front->next=NULL; return OK; } catch ( const bad_alloc& e ) { exit(OVERFLOW); } } int DestroyQueue(LinkQueue &Q) { while(Q.front) { Q.rear = Q.front->next; delete[] Q.front; } return OK; } int EnQueue(LinkQueue &Q,QElemType e) { try{ QueuePtr p=new QNode; p->data=e; p->nextNULL; Q.rear->next=p; Q.rear=p; return OK; }catch ( const bad_alloc& e ) { exit(OVERFLOW); } } int DeQueue(LinkQueue &Q,QElemType &e){ if(Q.front == Q.rear) return ERROR; QNode *p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.rear==p){ Q.rear=Q.front; } delete p; return OK; } int main() { return 0; }
#include "CompilationEngine.h" #include "JackTokenizer.h" #include "SymbolTable.h" #include <algorithm> #include <fstream> #include <string> #include <vector> #include <assert.h> CompilationEngine::CompilationEngine(std::string inputFile, JackTokenizer* jt, SymbolTable* st){ int dotPosition = inputFile.find('.'); outputFileName = inputFile.substr(0, dotPosition); outputFileName += ".xml"; outputFile.open(outputFileName); if(!outputFile.is_open()){ std::cerr << "Error opening output file " << outputFileName << "." << std::endl; } jt_ = jt; st_ = st; compileClass(); } CompilationEngine::~CompilationEngine(){ if(outputFile.is_open()){ outputFile.close(); } } void CompilationEngine::compileClass(){ outputFile << "<class>" << std::endl; int i = 0; assert(jt_->tokens[i] == "class"); outputFile << "<keyword> class </keyword>" << std::endl; i++; if(jt_->tokenType(jt_->tokens[i]) == "IDENTIFIER"){ outputFile << "<identifier> " << jt_->tokens[i] << " </identifier>" << std::endl; i++; } assert(jt_->tokens[i] == "{"); outputFile << "<symbol> { </symbol>" << std::endl; i++; //The class body will contain class variables and/or class functions std::string token = jt_->tokens[i]; while(i < jt_->tokens.size() && jt_->tokenType(token) == "KEYWORD"){ std::string key = jt_->keyWord(jt_->tokens[i]); if(key == "STATIC" || key == "FIELD"){ i = compileClassVarDec(i); } if(key == "CONSTRUCTOR" || key == "FUNCTION" || key == "METHOD" || key == "VOID"){ i = compileSubroutine(i); } i++; token = jt_->tokens[i]; } assert(jt_->tokens[i] == "}"); outputFile << "<symbol> } </symbol>" << std::endl; outputFile << "</class>" << std::endl; } int CompilationEngine::compileClassVarDec(int index){ outputFile << "<classVarDec>" << std::endl; //Static, Field outputFile << "<keyword> " << jt_->tokens[index] << " </keyword>" << std::endl; std::string type = ""; symboltable::Kind kind = st_->stringtoKind[stringToUpper(jt_->tokens[index])]; int lineIndex = 0; index++; while(jt_->tokens[index] != ";"){ std::string name; //int, char if(jt_->tokenType(jt_->tokens[index]) == "KEYWORD"){ outputFile << "<keyword> " << jt_->tokens[index] << " </keyword>" << std::endl; lineIndex = 1; type = jt_->tokens[index]; } if(jt_->tokens[index] == ","){ outputFile << "<symbol> , </symbol>" << std::endl; } if(jt_->tokenType(jt_->tokens[index]) == "IDENTIFIER"){ outputFile << "<identifier> " << jt_->tokens[index] << " </identifier>" << std::endl; if(lineIndex == 0){ type = jt_->tokens[index]; } else{ name = jt_->tokens[index]; st_->define(name, type, kind, "declared"); outputFile << "<variable> " << name << "," << st_->typeOf(name) << "," << st_->kindOf(name) << "," << st_->indexOf(name) << "," << st_->usage(name) << " </variable>" << std::endl; } } index++; } assert(jt_->tokens[index] == ";"); outputFile << "<symbol> ; </symbol>" << std::endl; outputFile << "</classVarDec>" << std::endl; return(index); } int CompilationEngine::compileSubroutine(int index){ st_->reset(); outputFile << "<subroutineDec>" << std::endl; //eg CONSTRUCTOR | FUNCTION | METHOD outputFile << "<keyword> " << jt_->tokens[index] << " </keyword>" << std::endl; index++; //Return type if(jt_->tokenType(jt_->tokens[index]) == "KEYWORD"){ outputFile << "<keyword> " << jt_->tokens[index] << " </keyword>" << std::endl; index++; } //eg subroutine's name else if(jt_->tokenType(jt_->tokens[index]) == "IDENTIFIER"){ outputFile << "<identifier> " << jt_->tokens[index] << " </identifier>" << std::endl; index++; } if(jt_->tokenType(jt_->tokens[index]) == "IDENTIFIER"){ outputFile << "<identifier> " << jt_->tokens[index] << " </identifier>" << std::endl; index++; if(jt_->tokens[index] == "("){ outputFile << "<symbol> ( </symbol>" << std::endl; index = compileParameterList(index); if(jt_->tokens[index] == ")"){ outputFile << "<symbol> ) </symbol>" << std::endl; index++; } } if(jt_->tokens[index] == "{"){ index = compileSubroutineBody(index); if(jt_->tokens[index] == "}"){ outputFile << "<symbol> } </symbol>" << std::endl; } outputFile << "</subroutineBody>" << std::endl; } } outputFile << "</subroutineDec>" << std::endl; return(index); } int CompilationEngine::compileParameterList(int index){ outputFile << "<parameterList>" << std::endl; symboltable::Kind kind = symboltable::ARG; std::string type = ""; int lineIndex = 0; index++; while(jt_->tokens[index] != ")"){ std::string name; if(jt_->tokenType(jt_->tokens[index]) == "KEYWORD"){ outputFile << "<keyword> " << jt_->tokens[index] << " </keyword>" << std::endl; lineIndex = 1; type = jt_->tokens[index]; } if(jt_->tokenType(jt_->tokens[index]) == "IDENTIFIER"){ outputFile << "<identifier> " << jt_->tokens[index] << " </identifier>" << std::endl; if(lineIndex = 0){ type = jt_->tokens[index]; lineIndex = 1; } else{ name = jt_->tokens[index]; st_->define(name, type, kind, "used"); outputFile << "<variable> " << name << "," << st_->typeOf(name) << "," << st_->kindOf(name) << "," << st_->indexOf(name) << "," << st_->usage(name) << " </variable>" << std::endl; } } if(jt_->tokenType(jt_->tokens[index]) == "SYMBOL"){ outputFile << "<symbol> " << jt_->tokens[index] << " </symbol>" << std::endl; lineIndex = 0; } index++; } outputFile << "</parameterList>" << std::endl; return(index); } int CompilationEngine::compileSubroutineBody(int index){ outputFile << "<subroutineBody>" << std::endl; outputFile << "<symbol> { </symbol>" << std::endl; index++; std::string token = jt_->tokens[index]; while(token != "}"){ if(token == "do" || token == "let" || token == "while" || token == "if" || token == "return"){ index = compileStatements(index); } if(token == "var"){ index = compileVarDec(index); } token = jt_->tokens[index]; } return(index); } int CompilationEngine::compileVarDec(int index){ outputFile << "<varDec>" << std::endl; std::string type = ""; symboltable::Kind kind = symboltable::VAR; int lineIndex = 0; while(jt_->tokens[index] != ";"){ std::string name; if(jt_->tokenType(jt_->tokens[index]) == "KEYWORD"){ outputFile << "<keyword> " << jt_->tokens[index] << " </keyword>" << std::endl; if(jt_->tokens[index] != "var"){ type = jt_->tokens[index]; lineIndex = 1; } index++; } if(jt_->tokenType(jt_->tokens[index]) == "IDENTIFIER"){ outputFile << "<identifier> " << jt_->tokens[index] << " </identifier>" << std::endl; //eg var Array a if(lineIndex == 0){ type = jt_->tokens[index]; lineIndex = 1; } else{ name = jt_->tokens[index]; st_->define(name, type, kind, "declared"); outputFile << "<variable> " << name << "," << st_->typeOf(name) << "," << st_->kindOf(name) << "," << st_->indexOf(name) << "," << st_->usage(name) << " </variable>" << std::endl; } index++; } if(jt_->tokens[index] == ","){ outputFile << "<symbol> , </symbol>" << std::endl; index++; } } if(jt_->tokens[index] == ";"){ outputFile << "<symbol> ; </symbol>" << std::endl; index++; } outputFile << "</varDec>" << std::endl; return(index); } int CompilationEngine::compileStatements(int index){ outputFile << "<statements>" << std::endl; std::string token = jt_->tokens[index]; if(token == "let" || token == "do" || token == "if" || token == "while"){ while(token != ";" && token != "}"){ if(token == "let"){ index = compileLet(index); } if(token == "do"){ index = compileDo(index); index++; } if(token == "if"){ index = compileIf(index); } if(token == "while"){ index = compileWhile(index); } if(token == "return"){ index = compileReturn(index); } token = jt_->tokens[index]; } } outputFile << "</statements>" << std::endl; return(index); } int CompilationEngine::compileExpression(int index){ outputFile << "<expression>" << std::endl; index = compileTerm(index); std::string token = jt_->tokens[index]; while(token != ")" && token != "}" && token != "]" && token != ";" && token != ","){ std::string tokenType = jt_->tokenType(token); if(tokenType == "SYMBOL"){ if(token == "<"){ outputFile << "<symbol> &lt; </symbol>" << std::endl; } else if(token == ">"){ outputFile << "<symbol> &gt; </symbol>" << std::endl; } else if(token == "\""){ outputFile << "<symbol> &quot; </symbol>" << std::endl; } else if(token == "&"){ outputFile << "<symbol> &amp; </symbol>" << std::endl; } else{ outputFile << "<symbol> " << token << " </symbol>" << std::endl; } index++; index = compileTerm(index); break; } else{ index++; index = compileTerm(index); break; } token = jt_->tokens[index]; } outputFile << "</expression>" << std::endl; return(index); } int CompilationEngine::compileTerm(int index){ outputFile << "<term>" << std::endl; std::string token = jt_->tokens[index]; std::string tokenType = jt_->tokenType(token); if(tokenType == "IDENTIFIER"){ outputFile << "<identifier> " << token << " </identifier>" << std::endl; if(st_->isKey(token)){ st_->changeUsage(token); outputFile << "<variable> " << token << "," << st_->typeOf(token) << "," << st_->kindOf(token) << "," << st_->indexOf(token) << "," << st_->usage(token) << " </variable>" << std::endl; } index++; if(jt_->tokens[index] == "("){ outputFile << "<symbol> ( </symbol>" << std::endl; index++; index = compileExpression(index); if(jt_->tokens[index] == ")"){ outputFile << "<symbol> ) </symbol>" << std::endl; index++; } } else if(jt_->tokens[index] == "."){ outputFile << "<symbol> . </symbol>" << std::endl; index++; outputFile << "<identifier> " << jt_->tokens[index] << "</identifier>" << std::endl; if(st_->isKey(token)){ st_->changeUsage(token); outputFile << "<variable> " << token << "," << st_->typeOf(token) << "," << st_->kindOf(token) << "," << st_->indexOf(token) << "," << st_->usage(token) << " </variable>" << std::endl; } index++; if(jt_->tokens[index] == "("){ outputFile << "<symbol> ( </symbol>" << std::endl; index++; index = compileExpressionList(index); if(jt_->tokens[index] == ")"){ outputFile << "<symbol> ) </symbol>" << std::endl; index++; } } } else if(jt_->tokens[index] == "["){ outputFile << "<symbol> [ </symbol>" << std::endl; index++; index = compileExpression(index); if(jt_->tokens[index] == "]"){ outputFile << "<symbol> ] </symbol>" << std::endl; index++; } } } if(tokenType == "INT_CONST"){ outputFile << "<integerConstant> " << token << " </integerConstant>" << std::endl; index++; } if(tokenType == "STRING_CONST"){ outputFile << "<stringConstant> " << token.substr(1, token.length() - 2) << " </stringConstant>" << std::endl; index++; } if(tokenType == "KEYWORD"){ outputFile << "<keyword> " << token << " </keyword>" << std::endl; index++; } if(tokenType == "SYMBOL"){ if(token == "("){ outputFile << "<symbol> ( </symbol>" << std::endl; index++; index = compileExpression(index); assert(jt_->tokens[index] == ")"); outputFile << "<symbol> ) </symbol>" << std::endl; index++; } else{ outputFile << "<symbol> " << token << " </symbol>" << std::endl; index++; index = compileTerm(index); } } outputFile << "</term>" << std::endl; return(index); } int CompilationEngine::compileExpressionList(int index){ outputFile << "<expressionList>" << std::endl; std::string token = jt_->tokens[index]; while(token != ")"){ index = compileExpression(index); if(jt_->tokens[index] == ","){ outputFile << "<symbol> , </symbol>" << std::endl; index++; } token = jt_->tokens[index]; } outputFile << "</expressionList>" << std::endl; return(index); } int CompilationEngine::compileLet(int index){ outputFile << "<letStatement>" << std::endl; outputFile << "<keyword> let </keyword>" << std::endl; index++; if(jt_->tokenType(jt_->tokens[index]) == "IDENTIFIER"){ outputFile << "<identifier> " << jt_->tokens[index] << " </identifier>" << std::endl; index++; } std::string token = jt_->tokens[index]; while(token != ";"){ if(jt_->tokens[index] == "["){ outputFile << "<symbol> [ </symbol>" << std::endl; index++; index = compileExpression(index); if(jt_->tokens[index] == "]"){ outputFile << "<symbol> ] </symbol>" << std::endl; index++; } } if(jt_->tokens[index] == "="){ outputFile << "<symbol> = </symbol>" << std::endl; index++; index = compileExpression(index); } token = jt_->tokens[index]; } if(jt_->tokens[index] == ";"){ outputFile << "<symbol> ; </symbol>" << std::endl; index++; } outputFile << "</letStatement>" << std::endl; return(index); } int CompilationEngine::compileDo(int index){ outputFile << "<doStatement>" << std::endl; outputFile << "<keyword> do </keyword>" << std::endl; index++; //subroutine call std::string token = jt_->tokens[index]; while(token != ";"){ outputFile << "<identifier> " << jt_->tokens[index] << " </identifier>" << std::endl; index++; if(jt_->tokens[index] == "."){ outputFile << "<symbol> . </symbol>" << std::endl; index++; } if(jt_->tokens[index] == "("){ outputFile << "<symbol> ( </symbol>" << std::endl; index++; index = compileExpressionList(index); if(jt_->tokens[index] == ")"){ outputFile << "<symbol> ) </symbol>" << std::endl; index++; } } token = jt_->tokens[index]; } if(jt_->tokens[index] == ";"){ outputFile << "<symbol> ; </symbol>" << std::endl; } outputFile << "</doStatement>" << std::endl; return(index); } int CompilationEngine::compileIf(int index){ outputFile << "<ifStatement>" << std::endl; outputFile << "<keyword> if </keyword>" << std::endl; index++; if(jt_->tokens[index] == "("){ outputFile << "<symbol> ( </symbol>" << std::endl; index++; index = compileExpression(index); if(jt_->tokens[index] == ")"){ outputFile << "<symbol> ) </symbol>" << std::endl; index++; } } if(jt_->tokens[index] == "{"){ outputFile << "<symbol> { </symbol>" << std::endl; index++; std::string token = jt_->tokens[index]; while(token != "}"){ index = compileStatements(index); token = jt_->tokens[index]; } if(jt_->tokens[index] == "}"){ outputFile << "<symbol> } </symbol>" << std::endl; index++; } } if(jt_->tokens[index] == "else"){ outputFile << "<keyword> else </keyword>" << std::endl; index++; if(jt_->tokens[index] == "{"){ outputFile << "<symbol> { </symbol>" << std::endl; index++; std::string token_ = jt_->tokens[index]; while(token_ != "}"){ index = compileStatements(index); token_ = jt_->tokens[index]; } if(jt_->tokens[index] == "}"){ outputFile << "<symbol> } </symbol>" << std::endl; index++; } } } outputFile << "</ifStatement>" << std::endl; return(index); } int CompilationEngine::compileWhile(int index){ outputFile << "<whileStatement>" << std::endl; outputFile << "<keyword> while </keyword>" << std::endl; index++; if(jt_->tokens[index] != "("){ index++; } assert(jt_->tokens[index] == "("); outputFile << "<symbol> ( </symbol>" << std::endl; index++; index = compileExpression(index); assert(jt_->tokens[index] == ")"); outputFile << "<symbol> ) </symbol>" << std::endl; index++; assert(jt_->tokens[index] == "{"); outputFile << "<symbol> { </symbol>" << std::endl; index++; std::string token = jt_->tokens[index]; while(token != "}"){ index = compileStatements(index); token = jt_->tokens[index]; } assert(jt_->tokens[index] == "}"); outputFile << "<symbol> } </symbol>" << std::endl; index++; outputFile << "</whileStatement>" << std::endl; return(index); } int CompilationEngine::compileReturn(int index){ outputFile << "<returnStatement>" << std::endl; outputFile << "<keyword> return </keyword>" << std::endl; index++; std::string token = jt_->tokens[index]; while(token != ";"){ index = compileExpression(index); token = jt_->tokens[index]; } if(jt_->tokens[index] == ";"){ outputFile << "<symbol> ; </symbol>" << std::endl; index++; } outputFile << "</returnStatement>" << std::endl; return(index); } std::string CompilationEngine::stringToUpper(std::string input){ std::string upperString = ""; for(int i = 0; i < input.length(); i++){ upperString += toupper(input[i]); } return upperString; }
#ifndef OPTIONS_HH #define OPTIONS_HH #include <vector> #include <string> #include <list> #include <map> #include <sstream> #include <getopt.h> typedef int ARGSPEC; //possible values are: required_argument, optional_argument, no_argument class OptionSpec; //apparently I need this struct Flag { char shortopt; std::string longopt; std::string arg; ARGSPEC argspec; std::string helpdescription; //to be used in making a printable help //message }; class Flags { std::multimap<char,Flag> flags; public: //shorthand for flags iterator typedef std::multimap<char,Flag>::iterator flagiter; flagiter begin() {return flags.begin();} flagiter end() {return flags.end();} int size() { return flags.size(); } void GetArgs(char c, std::vector<std::string>& v) { v.resize(0); typedef std::pair<flagiter,flagiter> flagpair; flagpair p = flags.equal_range(c); for(flagiter i = p.first; i != p.second; ++i) { v.push_back(i->second.arg); } return; } //check to see if flag c is set: bool Check(char c) { return flags.find(c) != flags.end(); } friend void parseargs(int argc, char** argv, OptionSpec& options, Flags& flags, std::vector<std::string>& args); }; class OptionSpec { std::map<char,Flag> options; public: //shorthand for iterator to options typedef std::map<char,Flag>::iterator optionspeciter; //add a flag with shortopt c and longopt s void AddOption(char c, const std::string& s, ARGSPEC argspec, const std::string& helpdesc = "") { Flag tmp = {c,s,"",argspec,helpdesc}; options[c]=tmp; } std::string GetShortOpts() { std::stringstream ss; for(optionspeciter i = options.begin(); i != options.end(); ++i) { ss << i->second.shortopt; switch(i->second.argspec) { case optional_argument: ss << "::"; break; case required_argument: ss << ":"; break; } } return ss.str(); } int size() {return options.size();} //Return option description string, useful for making a help message std::string GetOptionDesc(int spacing = 2) { using namespace std; int maxsize=0; for(optionspeciter i = options.begin(); i != options.end(); ++i) { maxsize = (maxsize < i->second.longopt.size()) ? i->second.longopt.size() : maxsize; } stringstream ss; ss << "Options:"; for(optionspeciter i = options.begin(); i != options.end(); ++i) { ss << endl; ss << '-' << i->second.shortopt << ",--" << i->second.longopt << ':'; int numspaces=maxsize - i->second.longopt.size()+spacing; for(int j = 0; j < numspaces; ++j) ss << ' '; ss << i->second.helpdescription; } return ss.str(); } friend void parseargs(int argc, char** argv, OptionSpec& options, Flags& flags, std::vector<std::string>& args); }; class ParseException { std::string e; public: ParseException() {} ParseException(const std::string& s) : e(s) {} std::string GetErrorString() {return e;} }; void parseargs(int argc, char** argv, OptionSpec& options, Flags& flags, std::vector<std::string>& args); #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/dom/src/domglobaldata.h" #include "modules/dom/src/domcore/node.h" #include "modules/dom/src/domcore/domexception.h" #include "modules/dom/src/domcss/cssrule.h" #include "modules/dom/src/domload/lsexception.h" #include "modules/dom/src/domsvg/domsvgexception.h" #include "modules/dom/src/domtraversal/nodefilter.h" #include "modules/dom/src/domrange/range.h" #include "modules/dom/src/domxpath/xpathexception.h" #include "modules/dom/src/media/dommediaerror.h" #ifdef DOM_LIBRARY_FUNCTIONS # ifdef DOM_NO_COMPLEX_GLOBALS # define DOM_PROTOTYPES_START() \ void DOM_Runtime_prototypes_Init(DOM_GlobalData *global_data) \ { \ DOM_PrototypeDesc *prototypes = global_data->DOM_Runtime_prototypes; # define DOM_PROTOTYPES_ITEM0(name, prototype_) \ prototypes->functions = 0; \ prototypes->functions_with_data = 0; \ prototypes->library_functions = 0; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM1(name, functions_, prototype_) \ prototypes->functions = global_data->functions_; \ prototypes->functions_with_data = 0; \ prototypes->library_functions = 0; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM2(name, functions_with_data_, prototype_) \ prototypes->functions = 0; \ prototypes->functions_with_data = global_data->functions_with_data_; \ prototypes->library_functions = 0; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM3(name, functions_, functions_with_data_, prototype_) \ prototypes->functions = global_data->functions_; \ prototypes->functions_with_data = global_data->functions_with_data_; \ prototypes->library_functions = 0; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM4(name, functions_, functions_with_data_, library_functions_, prototype_) \ prototypes->functions = global_data->functions_; \ prototypes->functions_with_data = global_data->functions_with_data_; \ prototypes->library_functions = library_functions_; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_END() \ } # else // DOM_NO_COMPLEX_GLOBALS # define DOM_PROTOTYPES_START() const DOM_PrototypeDesc DOM_Runtime_prototypes[DOM_Runtime::PROTOTYPES_COUNT + 1] = { # define DOM_PROTOTYPES_ITEM0(name, prototype_) { NULL, NULL, NULL, prototype_ }, # define DOM_PROTOTYPES_ITEM1(name, functions_, prototype_) { functions_, NULL, NULL, prototype_ }, # define DOM_PROTOTYPES_ITEM2(name, functions_with_data_, prototype_) { NULL, functions_with_data_, NULL, prototype_ }, # define DOM_PROTOTYPES_ITEM3(name, functions_, functions_with_data_, prototype_) { functions_, functions_with_data_, NULL, prototype_ }, # define DOM_PROTOTYPES_ITEM4(name, functions_, functions_with_data_, library_functions_, prototype_) { functions_, functions_with_data_, library_functions_, prototype_ }, # define DOM_PROTOTYPES_END() { 0, 0, 0 } }; # endif // DOM_NO_COMPLEX_GLOBALS #else // DOM_LIBRARY_FUNCTIONS # ifdef DOM_NO_COMPLEX_GLOBALS # define DOM_PROTOTYPES_START() \ void DOM_Runtime_prototypes_Init(DOM_GlobalData *global_data) \ { \ DOM_PrototypeDesc *prototypes = global_data->DOM_Runtime_prototypes; # define DOM_PROTOTYPES_ITEM0(name, prototype_) \ prototypes->functions = 0; \ prototypes->functions_with_data = 0; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM1(name, functions_, prototype_) \ prototypes->functions = global_data->functions_; \ prototypes->functions_with_data = 0; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM2(name, functions_with_data_, prototype_) \ prototypes->functions = 0; \ prototypes->functions_with_data = global_data->functions_with_data_; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM3(name, functions_, functions_with_data_, prototype_) \ prototypes->functions = global_data->functions_; \ prototypes->functions_with_data = global_data->functions_with_data_; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_ITEM4(name, functions_, functions_with_data_, library_functions_, prototype_) \ prototypes->functions = global_data->functions_; \ prototypes->functions_with_data = global_data->functions_with_data_; \ prototypes->prototype = prototype_; \ ++prototypes; # define DOM_PROTOTYPES_END() \ } # else // DOM_NO_COMPLEX_GLOBALS # define DOM_PROTOTYPES_START() const DOM_PrototypeDesc DOM_Runtime_prototypes[DOM_Runtime::PROTOTYPES_COUNT + 1] = { # define DOM_PROTOTYPES_ITEM0(name, prototype_) { NULL, NULL, prototype_ }, # define DOM_PROTOTYPES_ITEM1(name, functions_, prototype_) { functions_, NULL, prototype_ }, # define DOM_PROTOTYPES_ITEM2(name, functions_with_data_, prototype_) { NULL, functions_with_data_, prototype_ }, # define DOM_PROTOTYPES_ITEM3(name, functions_, functions_with_data_, prototype_) { functions_, functions_with_data_, prototype_ }, # define DOM_PROTOTYPES_ITEM4(name, functions_, functions_with_data_, library_functions_, prototype_) { functions_, functions_with_data_, prototype_ }, # define DOM_PROTOTYPES_END() { 0, 0, 0 } }; # endif // DOM_NO_COMPLEX_GLOBALS #endif // DOM_LIBRARY_FUNCTIONS #include "modules/dom/src/domprototypes.cpp.inc"
// // main.cpp // Project1 // // Created by christopher kha on 1/11/19. // Copyright © 2019 christopher kha. All rights reserved. // //#include "Game.h" // //int main() //{ // // Create a game // // Use this instead to create a mini-game: Game g(3, 4, 2); // Game g(7, 8, 25); //// Game g(1, 2, 2); // // // Play the game // g.play(); //} #include "Arena.h" #include "History.h" #include "Player.h" #include "globals.h" #include <iostream> using namespace std; int main() { Arena a(4, 4); a.addPlayer(2, 4); a.addZombie(3, 2); a.addZombie(2, 3); a.addZombie(1, 4); a.player()->moveOrAttack(LEFT); a.player()->moveOrAttack(UP); a.player()->moveOrAttack(LEFT); a.player()->moveOrAttack(LEFT); a.player()->moveOrAttack(DOWN); a.player()->moveOrAttack(DOWN); a.player()->moveOrAttack(LEFT); a.player()->moveOrAttack(UP); a.player()->moveOrAttack(UP); a.player()->moveOrAttack(UP); a.history().display(); cerr << "====" << endl; }
#include "camera.h" static_func void CameraUpdate(camera &cam, vec3 dPos, vec2 dLook) { // Position cam.pos += cam.speed * dPos; // Look Dir cam.yaw += dLook.X * cam.sens; if (cam.yaw > 360.0f) cam.yaw -= 360.0f; else if (cam.yaw < 0.0f) cam.yaw = 360.0f - cam.yaw; cam.pitch += dLook.Y * cam.sens; cam.pitch = Clamp(-89.0f, cam.pitch, 89.0f); f32 pitchRad = ToRadians(cam.pitch); f32 yawRad = ToRadians(cam.yaw); cam.dir.X = CosF(yawRad) * CosF(pitchRad); cam.dir.Y = SinF(pitchRad); cam.dir.Z = SinF(yawRad) * CosF(pitchRad); } static_func void CameraInitialize(camera &cam, vec3 posIn, f32 pitch, f32 yaw, vec3 up, f32 speed, f32 sens, f32 fov) { cam.pos = posIn; cam.up = up; cam.pitch = pitch; cam.yaw = yaw; CameraUpdate(cam, {}, {}); cam.speed = speed; cam.sens = sens; cam.fov = fov; }
#include "comn.h" #include "http-deal.h" int main() { using namespace std; CInternetSession session(_T("Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"), 1, PRE_CONFIG_INTERNET_ACCESS, NULL, NULL, INTERNET_FLAG_DONT_CACHE ); DWORD value; session.QueryOption(INTERNET_OPTION_FROM_CACHE_TIMEOUT,value); cout<<value; }
#include<bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Counts Zeros Xor Pairs int t, n, x; cin >> t; while (t--) { cin >> n; map<int, int> freq; for(int i=0; i<n; i++) { cin >> x; freq[x]++; } int res=0; for(auto f: freq) { res += f.second*(f.second-1)/2; } cout << res << endl; } return 0; }
// Created on: 2015-07-16 // Created by: Irina KRYLOVA // Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepDimTol_GeneralDatumReference_HeaderFile #define _StepDimTol_GeneralDatumReference_HeaderFile #include <Standard.hxx> #include <Standard_Integer.hxx> #include <StepRepr_ShapeAspect.hxx> #include <StepDimTol_DatumOrCommonDatum.hxx> #include <StepDimTol_HArray1OfDatumReferenceModifier.hxx> class StepDimTol_GeneralDatumReference; DEFINE_STANDARD_HANDLE(StepDimTol_GeneralDatumReference, StepRepr_ShapeAspect) //! Representation of STEP entity GeneralDatumReference class StepDimTol_GeneralDatumReference : public StepRepr_ShapeAspect { public: //! Empty constructor Standard_EXPORT StepDimTol_GeneralDatumReference(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& theName, const Handle(TCollection_HAsciiString)& theDescription, const Handle(StepRepr_ProductDefinitionShape)& theOfShape, const StepData_Logical theProductDefinitional, const StepDimTol_DatumOrCommonDatum& theBase, const Standard_Boolean theHasModifiers, const Handle(StepDimTol_HArray1OfDatumReferenceModifier)& theModifiers); //! Returns field Base inline StepDimTol_DatumOrCommonDatum Base() { return myBase; } //! Set field Base inline void SetBase(const StepDimTol_DatumOrCommonDatum& theBase) { myBase = theBase; } //! Indicates is field Modifiers exist inline Standard_Boolean HasModifiers() const { return !(myModifiers.IsNull() || myModifiers->Length() == 0); } //! Returns field Modifiers inline Handle(StepDimTol_HArray1OfDatumReferenceModifier) Modifiers() { return myModifiers; } //! Set field Modifiers inline void SetModifiers(const Handle(StepDimTol_HArray1OfDatumReferenceModifier)& theModifiers) { myModifiers = theModifiers; } //! Returns number of Modifiers inline Standard_Integer NbModifiers () const { return (myModifiers.IsNull() ? 0 : myModifiers->Length()); } //! Returns Modifiers with the given number inline StepDimTol_DatumReferenceModifier ModifiersValue(const Standard_Integer theNum) const { return myModifiers->Value(theNum); } //! Sets Modifiers with given number inline void ModifiersValue(const Standard_Integer theNum, const StepDimTol_DatumReferenceModifier& theItem) { myModifiers->SetValue (theNum, theItem); } DEFINE_STANDARD_RTTIEXT(StepDimTol_GeneralDatumReference,StepRepr_ShapeAspect) private: StepDimTol_DatumOrCommonDatum myBase; Handle(StepDimTol_HArray1OfDatumReferenceModifier) myModifiers; }; #endif // _StepDimTol_GeneralDatumReference_HeaderFile
/* particle_object.cpp Component from a basic example of a particle animation Adaped from the particle animation tutorial from: http://www.opengl-tutorial.org/intermediate-tutorials/billboards-particles/particles-instancing/ Iain Martin November 2014 */ #pragma once #include "wrapper_glfw.h" #include <glm/glm.hpp> // CPU representation of a particle struct Particle{ glm::vec3 pos, speed; unsigned char r, g, b, a; // Color float size, angle, weight; float life; // Remaining life of the particle. if < 0 : dead and unused. float cameradistance; // *Squared* distance to the camera. if dead : -1.0f bool operator<(const Particle& that) const { // Sort in reverse order : far particles drawn first. return this->cameradistance > that.cameradistance; } }; class particle_object { public: particle_object(); ~particle_object(); void create(GLuint program); int FindUnusedParticle(); void SortParticles(); void drawParticles(glm::mat4 ProjectionMatrix, glm::mat4 ViewMatrix); void defineUniforms(); GLuint billboard_vertex_buffer; GLuint particles_position_buffer; GLuint particles_color_buffer; const int MaxParticles = 10000; Particle ParticlesContainer[10000]; int LastUsedParticle; GLfloat* g_particule_position_size_data; GLubyte* g_particule_color_data; int ParticlesCount; double lastTime; GLuint VertexArrayID; GLuint programID; GLuint Texture; GLuint TextureID; GLuint CameraRight_worldspace_ID; GLuint CameraUp_worldspace_ID; GLuint ViewProjMatrixID; };
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen (Anand NATRAJAN) // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESDimen_GeneralSymbol_HeaderFile #define _IGESDimen_GeneralSymbol_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IGESData_HArray1OfIGESEntity.hxx> #include <IGESDimen_HArray1OfLeaderArrow.hxx> #include <IGESData_IGESEntity.hxx> #include <Standard_Integer.hxx> class IGESDimen_GeneralNote; class IGESDimen_LeaderArrow; class IGESDimen_GeneralSymbol; DEFINE_STANDARD_HANDLE(IGESDimen_GeneralSymbol, IGESData_IGESEntity) //! defines General Symbol, Type <228>, Form <0-3,5001-9999> //! in package IGESDimen //! Consists of zero or one (Form 0) or one (all other //! forms), one or more geometry entities which define //! a symbol, and zero, one or more associated leaders. class IGESDimen_GeneralSymbol : public IGESData_IGESEntity { public: Standard_EXPORT IGESDimen_GeneralSymbol(); //! This method is used to set the fields of the class //! GeneralSymbol //! - aNote : General Note, null for form 0 //! - allGeoms : Geometric Entities //! - allLeaders : Leader Arrows Standard_EXPORT void Init (const Handle(IGESDimen_GeneralNote)& aNote, const Handle(IGESData_HArray1OfIGESEntity)& allGeoms, const Handle(IGESDimen_HArray1OfLeaderArrow)& allLeaders); //! Changes FormNumber (indicates the Nature of the Symbole) //! Error if not in ranges [0-3] or [> 5000] Standard_EXPORT void SetFormNumber (const Standard_Integer form); //! returns True if there is associated General Note Entity Standard_EXPORT Standard_Boolean HasNote() const; //! returns Null handle for form 0 only Standard_EXPORT Handle(IGESDimen_GeneralNote) Note() const; //! returns number of Geometry Entities Standard_EXPORT Standard_Integer NbGeomEntities() const; //! returns the Index'th Geometry Entity //! raises exception if Index <= 0 or Index > NbGeomEntities() Standard_EXPORT Handle(IGESData_IGESEntity) GeomEntity (const Standard_Integer Index) const; //! returns number of Leaders or zero if not specified Standard_EXPORT Standard_Integer NbLeaders() const; //! returns the Index'th Leader Arrow //! raises exception if Index <= 0 or Index > NbLeaders() Standard_EXPORT Handle(IGESDimen_LeaderArrow) LeaderArrow (const Standard_Integer Index) const; DEFINE_STANDARD_RTTIEXT(IGESDimen_GeneralSymbol,IGESData_IGESEntity) protected: private: Handle(IGESDimen_GeneralNote) theNote; Handle(IGESData_HArray1OfIGESEntity) theGeoms; Handle(IGESDimen_HArray1OfLeaderArrow) theLeaders; }; #endif // _IGESDimen_GeneralSymbol_HeaderFile
#include "../stdafx.h" CNetMgr::~CNetMgr() { for (auto &it : mSessionVec) { if (it) delete it; } } void CNetMgr::OnConnection(ISession* pSession) { CSession* session = new CSession(pSession); if (session) mSessionVec.push_back(session); } void CNetMgr::update() { for (auto &it : mSessionVec) { it->recv(); } std::this_thread::sleep_for(10s); }
#include "sched.h" #include "schedproc.h" #include <assert.h> #include <minix/com.h> #include <timers.h> #include <machine/archtypes.h> #include <sys/resource.h> /* for PRIO_MAX & PRIO_MIN */ #include "kernel/proc.h" /* for queue constants */ #define SCHEDULE_CHANGE_PRIO 0x1 #define SCHEDULE_CHANGE_QUANTUM 0x2 #define SCHEDULE_CHANGE_CPU 0x4 #define SCHEDULE_CHANGE_ALL ( \ SCHEDULE_CHANGE_PRIO | \ SCHEDULE_CHANGE_QUANTUM | \ SCHEDULE_CHANGE_CPU \ ) #define CPU_DEAD -1 #define DEFAULT_USER_TIME_SLICE 200 #define INC_PER_QUEUE 10 unsigned cpu_proc[CONFIG_MAX_CPUS]; #define cpu_is_available(c) (cpu_proc[c] >= 0) #define is_system_proc(p) ((p)->parent == RS_PROC_NR) extern "C" int call_minix_sys_schedule(endpoint_t proc_ep, int priority, int quantum, int cpu); extern "C" int call_minix_sys_schedctl(unsigned flags, endpoint_t proc_ep, int priority, int quantum, int cpu); extern "C" int accept_message(message *m_ptr); extern "C" int no_sys(int who_e, int call_nr); int sched_isokendpt(int endpoint, int *proc); int sched_isemptyendpt(int endpoint, int *proc); void Schedproc::pick_cpu() { #ifdef CONFIG_SMP unsigned cpu, c; unsigned cpu_load = (unsigned) -1; if (machine.processors_count == 1) { this->cpu = machine.bsp_id; return; } if (is_system_proc(this)) { this->cpu = machine.bsp_id; return; } cpu = machine.bsp_id; for (c = 0; c < machine.processors_count; c++) { if (!cpu_is_available(c)) continue; if (c != machine.bsp_id && cpu_load > cpu_proc[c]) { cpu_load = cpu_proc[c]; cpu = c; } } this->cpu = cpu; cpu_proc[cpu]++; #else this->cpu = 0; #endif } extern "C" int do_noquantum(message *m_ptr) { Schedproc *rmp; int rv, proc_nr_n; unsigned ipc, burst, queue_bump; short load; if (sched_isokendpt(m_ptr->m_source, &proc_nr_n) != OK) { printf("SCHED: WARNING: got an invalid endpoint in OOQ msg %u.\n",m_ptr->m_source); return EBADEPT; } rmp = &schedproc[proc_nr_n]; ipc = (unsigned)m_ptr->SCHEDULING_ACNT_IPC_ASYNC + (unsigned)m_ptr->SCHEDULING_ACNT_IPC_SYNC + 1; load = m_ptr->SCHEDULING_ACNT_CPU_LOAD; burst = (rmp->time_slice * 1000 / ipc) / 100; burst = rmp->burst_smooth(burst); queue_bump = burst/INC_PER_QUEUE; if (rmp->max_priority + queue_bump > MIN_USER_Q) { queue_bump = MIN_USER_Q - rmp->max_priority; } rmp->priority = rmp->max_priority + queue_bump; rmp->time_slice = rmp->base_time_slice + 2 * queue_bump * (rmp->base_time_slice/10); if ((rv = rmp->schedule_process(SCHEDULE_CHANGE_PRIO | SCHEDULE_CHANGE_QUANTUM)) != OK) { return rv; } return OK; } int Schedproc::burst_smooth(unsigned burst) { int i; unsigned avg_burst = 0; this->burst_history[this->burst_hist_cnt++ % BURST_HISTORY_LENGTH] = burst; for (i=0; i<BURST_HISTORY_LENGTH; i++) { if (i >= this->burst_hist_cnt) { break; } avg_burst += this->burst_history[i]; } avg_burst /= i; return avg_burst; } extern "C" int do_stop_scheduling(message *m_ptr) { Schedproc *rmp; int proc_nr_n; /* check who can send you requests */ if (!accept_message(m_ptr)) return EPERM; if (sched_isokendpt(m_ptr->SCHEDULING_ENDPOINT, &proc_nr_n) != OK) { printf("SCHED: WARNING: got an invalid endpoint in OOQ msg " "%ld\n", m_ptr->SCHEDULING_ENDPOINT); return EBADEPT; } rmp = &schedproc[proc_nr_n]; #ifdef CONFIG_SMP cpu_proc[rmp->cpu]--; #endif rmp->flags = 0; /*&= ~IN_USE;*/ return OK; } int sched_isokendpt(int endpoint, int *proc) { *proc = _ENDPOINT_P(endpoint); if (*proc < 0) return (EBADEPT); /* Don't schedule tasks */ if(*proc >= NR_PROCS) return (EINVAL); if(endpoint != schedproc[*proc].endpoint) return (EDEADEPT); if(!(schedproc[*proc].flags & IN_USE)) return (EDEADEPT); return (OK); } int sched_isemtyendpt(int endpoint, int *proc) { *proc = _ENDPOINT_P(endpoint); if (*proc < 0) return (EBADEPT); /* Don't schedule tasks */ if(*proc >= NR_PROCS) return (EINVAL); if(schedproc[*proc].flags & IN_USE) return (EDEADEPT); return (OK); } extern "C" int do_nice(message *m_ptr) { Schedproc *rmp; int rv; int proc_nr_n; unsigned new_q, old_q, old_max_q; /* check who can send you requests */ if (accept_message(m_ptr)) return EPERM; if (sched_isokendpt(m_ptr->SCHEDULING_ENDPOINT, &proc_nr_n) != OK) { printf("SCHED: WARNING: got an invalid endpoint in OOQ msg ""%ld\n", m_ptr->SCHEDULING_ENDPOINT); return EBADEPT; } rmp = &schedproc[proc_nr_n]; new_q = (unsigned) m_ptr->SCHEDULING_MAXPRIO; if (new_q >= NR_SCHED_QUEUES) { return EINVAL; } /* Store old values, in case we need to roll back the changes */ old_q = rmp->priority; old_max_q = rmp->max_priority; /* Update the proc entry and reschedule the process */ rmp->max_priority = rmp->priority = new_q; if ((rv = rmp->schedule_process(SCHEDULE_CHANGE_PRIO | SCHEDULE_CHANGE_QUANTUM)) != OK) { rmp->priority = old_q; rmp->max_priority = old_max_q; } return rv; } int Schedproc::schedule_process(unsigned flags) { int err; int new_prio, new_quantum, new_cpu; this->pick_cpu(); if (flags & SCHEDULE_CHANGE_PRIO) new_prio = this->priority; else new_prio = -1; if (flags & SCHEDULE_CHANGE_QUANTUM) new_quantum = this->time_slice; else new_quantum = -1; if (flags & SCHEDULE_CHANGE_CPU) new_cpu = this->cpu; else new_cpu = -1; if ((err = call_minix_sys_schedule(this->endpoint, new_prio, new_quantum, new_cpu)) != OK) { printf("PM: An error occurred when trying to schedule %d: %d\n",this->endpoint, err); } return err; } extern "C" int do_start_scheduling(message *m_ptr) { Schedproc *rmp; int rv, proc_nr_n, parent_nr_n; /* we can handle two kinds of messages here */ assert(m_ptr->m_type == SCHEDULING_START || m_ptr->m_type == SCHEDULING_INHERIT); /* check who can send you requests */ if (!accept_message(m_ptr)) return EPERM; /* Resolve endpoint to proc slot. */ if ((rv = sched_isemtyendpt(m_ptr->SCHEDULING_ENDPOINT, &proc_nr_n)) != OK) { return rv; } rmp = &schedproc[proc_nr_n]; /* Populate process slot */ rmp->endpoint = m_ptr->SCHEDULING_ENDPOINT; rmp->parent = m_ptr->SCHEDULING_PARENT; rmp->max_priority = (unsigned) m_ptr->SCHEDULING_MAXPRIO; rmp->burst_hist_cnt = 0; if (rmp->max_priority >= NR_SCHED_QUEUES) { return EINVAL; } /* Inherit current priority and time slice from parent. Since there * is currently only one scheduler scheduling the whole system, this * value is local and we assert that the parent endpoint is valid */ if (rmp->endpoint == rmp->parent) { /* We have a special case here for init, which is the first process scheduled, and the parent of itself. */ rmp->priority = USER_Q; rmp->time_slice = DEFAULT_USER_TIME_SLICE; /* * Since kernel never changes the cpu of a process, all are * started on the BSP and the userspace scheduling hasn't * changed that yet either, we can be sure that BSP is the * processor where the processes run now. */ #ifdef CONFIG_SMP rmp->cpu = machine.bsp_id; /* FIXME set the cpu mask */ #endif } switch (m_ptr->m_type) { case SCHEDULING_START: /* We have a special case here for system processes, for which * quanum and priority are set explicitly rather than inherited * from the parent */ rmp->priority = rmp->max_priority; rmp->time_slice = (unsigned) m_ptr->SCHEDULING_QUANTUM; rmp->base_time_slice = rmp->time_slice; break; case SCHEDULING_INHERIT: /* Inherit current priority and time slice from parent. Since there * is currently only one scheduler scheduling the whole system, this * value is local and we assert that the parent endpoint is valid */ if ((rv = sched_isokendpt(m_ptr->SCHEDULING_PARENT, &parent_nr_n)) != OK) return rv; rmp->priority = schedproc[parent_nr_n].priority; rmp->time_slice = schedproc[parent_nr_n].time_slice; rmp->base_time_slice = rmp->time_slice; break; default: /* not reachable */ assert(0); } /* Take over scheduling the process. The kernel reply message populates * the processes current priority and its time slice */ if ((rv = call_minix_sys_schedctl(0, rmp->endpoint, 0, 0, 0)) != OK) { printf("Sched: Error taking over scheduling for %d, kernel said %d\n", rmp->endpoint, rv); return rv; } rmp->flags = IN_USE; /* Schedule the process, giving it some quantum */ rmp->pick_cpu(); while ((rv = rmp->schedule_process(SCHEDULE_CHANGE_ALL)) == EBADCPU) { /* don't try this CPU ever again */ cpu_proc[rmp->cpu] = CPU_DEAD; rmp->pick_cpu(); } if (rv != OK) { printf("Sched: Error while scheduling process, kernel replied %d\n", rv); return rv; } /* Mark ourselves as the new scheduler. * By default, processes are scheduled by the parents scheduler. In case * this scheduler would want to delegate scheduling to another * scheduler, it could do so and then write the endpoint of that * scheduler into SCHEDULING_SCHEDULER */ m_ptr->SCHEDULING_SCHEDULER = SCHED_PROC_NR; return OK; } extern "C" int no_sys(int who_e, int call_nr) { /* A system call number not implemented by PM has been requested. */ printf("SCHED: in no_sys, call nr %d from %d\n", call_nr, who_e); return(ENOSYS); } extern "C" int accept_message(message *m_ptr) { /* accept all messages from PM and RS */ switch (m_ptr->m_source) { case PM_PROC_NR: case RS_PROC_NR: return 1; } /* no other messages are allowable */ return 0; }
#include <bits/stdc++.h> using namespace std; long long int f,dias,valor,i; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> f; i = 0; valor = f; while(true){ if((valor-1)%11 == 0){ cout << i << " " << valor; return 0; } valor += valor; i++; } return 0; }
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define FOR(a, b, c) for (int a = b; a <= c; ++a) #define FORW(a, b, c) for(int a = b; a >= c; --a) #define pb push_back #define SZ(a) ((int)a.size()) #define int long long const int N = 2e2; const int oo = 1e9; const int mod = 1e9 + 7; typedef pair<int, int> ii; signed main(){ freopen("alchemy_input.txt", "r", stdin); freopen("alchemy.out", "w", stdout); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; FOR(cases, 1, t) { int n; cin >> n; int cnta = 0, cntb = 0; FOR(i, 1, n) { char c; cin >> c; if(c == 'A') cnta += 1; else cntb += 1; } char res = (abs(cnta - cntb) == 1) ? 'Y' : 'N'; cout << "Case #" << cases << ": " << res << '\n'; } }
#ifndef HROCKER_H #define HROCKER_H #include <iostream> #include "cocos2d.h" using namespace cocos2d; //枚举型:用于标识摇杆与摇杆的背景 typedef enum{ tag_rocker, tag_rockerBG, }tagForHRocker; class HRocker : public Layer { public: //创建摇杆,摇杆图片,摇杆背景图片,起始坐标 static HRocker* createHRocker(const char* rockerImageName, const char* rockerBGImageName, Point position); void startlistener(); //注册监听 void stoplistener(); //注销监听 //返回角度 float is_getRad(); bool is_move();// 是否移动 //得到半径为r的圆周运动上一个角度应对应的x,y坐标 Point getAnglePosition(float r); private: EventListenerTouchOneByOne* listener1; //摇杆监听 EventListenerTouchOneByOne* listener2; //摇杆背景 Sprite* spRocker; void rockerInit(const char* rockerImageName, const char* rockerBGImageName, Point position); //是否可操作摇杆 bool isCanMove = false; //渲染一次动画 bool isaction = true; //得到摇杆与用户触屏点的角度 float getRad(Point pos1, Point pos2); //摇杆背景的坐标 Point rockerBGPosition; //摇杆背景的半径 float rockerBGR; virtual void update(float dt); Sprite* spRockerBG; float rad = 0; // 角度 bool moveed = false; CREATE_FUNC(HRocker); }; #endif
/*============================================================================== Project: Bulk Synchronous Farm (BSF) Theme: BSF Skeleton Module: BSF-Code.cpp (Problem Independent Code) Prefix: BI Author: Nadezhda A. Ezhova Supervisor: Leonid B. Sokolinsky This source code is a part of BSF Skeleton ==============================================================================*/ #include "BSF-Data.h" // Problem Independent Variables & Data Structures #include "BSF-Forwards.h" // Problem Independent Function Forwards #include "BSF-ProblemFunctions.h" // Predefined Problem Function Forwards #include "Problem-bsfParameters.h" // Predefined Problem Parameters using namespace std; int main(int argc, char *argv[]) { char emptystring[] = ""; char* message = emptystring; unsigned success; BC_MpiRun(); BD_success = true; PC_bsf_Init(&BD_success); MPI_Allreduce(&BD_success, &success, 1, MPI_UNSIGNED, MPI_LAND, MPI_COMM_WORLD); if (!success) { if (BD_rank == BD_masterRank) cout << "Error: PC_bsf_Init failed (not enough memory)!" << endl; MPI_Finalize(); exit(1); }; BD_success = true; BC_Init(&BD_success); MPI_Allreduce(&BD_success, &success, 1, MPI_UNSIGNED, MPI_LAND, MPI_COMM_WORLD); if (!success) { if (BD_rank == BD_masterRank) cout << "Error: BC_Init failed (not enough memory). N = " << endl; MPI_Finalize(); exit(1); }; if (BD_rank == BD_masterRank) BC_Master(); else BC_Worker(); MPI_Finalize(); return 0; }; static void BC_Master() { // Master Process PC_bsf_ParametersOutput(BD_numOfWorkers, BD_data); BD_iterCount = 0; BD_t -= MPI_Wtime(); do { BC_MasterMap(!BD_EXIT); BC_MasterReduce(); PC_bsf_ProcessResults(&BD_exit, &BD_extendedReduceResult_P->elem, BD_extendedReduceResult_P->counter, &BD_data); BD_iterCount++; #ifdef PP_BSF_ITER_OUTPUT if (BD_iterCount % PP_BSF_TRACE_COUNT == 0) PC_bsf_IterOutput(&BD_extendedReduceResult_P->elem, BD_extendedReduceResult_P->counter, BD_data, BD_iterCount, BD_t + MPI_Wtime()); #endif // PP_BSF_ITER_OUTPUT } while (!BD_exit); BD_t += MPI_Wtime(); BC_MasterMap(BD_EXIT); PC_bsf_ProblemOutput(&BD_extendedReduceResult_P->elem, BD_extendedReduceResult_P->counter, BD_data, BD_iterCount, BD_t); }; static void BC_Worker() { // Worker Process bool exit; while (true) { exit = BC_WorkerMap(); if (exit) break; BC_WorkerReduce(); }; }; static void BC_MasterMap(bool exit) { for (int rank = 0; rank < BD_numOfWorkers; rank++) { PC_bsf_CopyData(&BD_data, &(BD_order[rank].data)); BD_order[rank].exit = exit; MPI_Isend( &BD_order[rank], sizeof(BT_order_T), MPI_BYTE, rank, 0, MPI_COMM_WORLD, &BD_request[rank]); }; MPI_Waitall(BD_numOfWorkers, BD_request, BD_status); }; static void BC_MasterReduce() { for (int rank = 0; rank < BD_numOfWorkers; rank++) MPI_Irecv( &BD_extendedReduceList[rank], sizeof(BT_extendedReduceElem_T), MPI_BYTE, rank, 0, MPI_COMM_WORLD, &BD_request[rank]); MPI_Waitall(BD_numOfWorkers, BD_request, BD_status); BC_ProcessExtendedReduceList(BD_extendedReduceList, 0, BD_numOfWorkers, &BD_extendedReduceResult_P); }; static bool BC_WorkerMap() { MPI_Recv( &BD_order[BD_rank], sizeof(BT_order_T), MPI_BYTE, BD_masterRank, 0, MPI_COMM_WORLD, &BD_status[BD_rank]); if (BD_order[BD_rank].exit) return BD_EXIT; #ifdef PP_BSF_OMP #ifdef PP_BSF_NUM_THREADS #pragma omp parallel for num_threads(PP_BSF_NUM_THREADS) #else #pragma omp parallel for #endif // PP_BSF_NUM_THREADS #endif // PP_BSF_OMP //*debug*/int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 3) cout << "BC_WorkerMap: subListSize = " << BD_subListSize[BD_rank] << "\toffset = " << BD_offset[BD_rank] << endl; for (int index = BD_offset[BD_rank]; index < BD_offset[BD_rank] + BD_subListSize[BD_rank]; index++) { BD_extendedReduceList[index].counter = 1; PC_bsf_MapF(&BD_mapSubList[index - BD_offset[BD_rank]], &BD_extendedReduceList[index].elem, &BD_order[BD_rank].data, &BD_extendedReduceList[index].counter); }; return !BD_EXIT; }; static void BC_WorkerReduce() { BC_ProcessExtendedReduceList(BD_extendedReduceList, BD_offset[BD_rank], BD_subListSize[BD_rank], &BD_extendedReduceResult_P); MPI_Send( BD_extendedReduceResult_P, sizeof(BT_extendedReduceElem_T), MPI_BYTE, BD_masterRank, 0, MPI_COMM_WORLD); }; static void BC_ProcessExtendedReduceList(BT_extendedReduceElem_T* reduceList, int index, int length, BT_extendedReduceElem_T** extendedReduceResult_P) { int firstSuccessIndex = -1; *extendedReduceResult_P = &reduceList[index]; for (int i = index; i < index + length; i++) { if (reduceList[i].counter > 0) { *extendedReduceResult_P = &reduceList[i]; firstSuccessIndex = i; break; }; }; if (firstSuccessIndex >= 0) { for (int i = firstSuccessIndex + 1; i < index + length; i++) if (BD_extendedReduceList[i].counter > 0) { PC_bsf_ReduceF(&(*extendedReduceResult_P)->elem, &BD_extendedReduceList[i].elem, &(*extendedReduceResult_P)->elem); (*extendedReduceResult_P)->counter += BD_extendedReduceList[i].counter; }; }; }; static void BC_Init(bool* success) { // Initialization //* debug */int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) *success = false; cout << setprecision(PP_BSF_PRECISION); PC_bsf_AssignListSize(&BD_listSize); BD_extendedReduceList = (BT_extendedReduceElem_T*)malloc(BD_listSize * sizeof(BT_extendedReduceElem_T)); if (BD_extendedReduceList == NULL) { *success = false; return; }; if (BD_size > BD_listSize + 1) { if (BD_rank == 0) cout << "Error: MPI_SIZE must be < Map List Size + 2 =" << BD_listSize + 2 << endl; MPI_Finalize(); exit(1); }; BD_masterRank = BD_size - 1; BD_numOfWorkers = BD_size - 1; BD_elemsPerWorker = BD_listSize / BD_numOfWorkers; BD_tailLength = BD_listSize - BD_elemsPerWorker * BD_numOfWorkers; BD_status = (MPI_Status*)malloc(BD_numOfWorkers * sizeof(MPI_Status)); BD_request = (MPI_Request*)malloc(BD_numOfWorkers * sizeof(MPI_Request)); BD_order = (BT_order_T*)malloc(BD_numOfWorkers * sizeof(BT_order_T)); BD_subListSize = (int*)malloc(BD_numOfWorkers * sizeof(int)); BD_offset = (int*)malloc(BD_numOfWorkers * sizeof(int)); PC_bsf_SetInitApproximation(&BD_data); int offset = 0; for (int rank = 0; rank < BD_numOfWorkers; rank++) { BD_subListSize[rank] = BD_elemsPerWorker + (rank < BD_tailLength ? 1 : 0); BD_offset[rank] = offset; offset += BD_subListSize[rank]; }; if (BD_rank != BD_masterRank) { BD_mapSubList = (PT_bsf_mapElem_T*)malloc(BD_subListSize[BD_rank] * sizeof(PT_bsf_mapElem_T*)); if (BD_mapSubList == NULL) { *success = false; return; }; PC_bsf_SetMapSubList(BD_mapSubList, BD_subListSize[BD_rank], BD_offset[BD_rank], success); }; }; static void BC_MpiRun() { int rc; rc = MPI_Init(NULL, NULL); // Starting MPI if (rc != MPI_SUCCESS) { printf("Error starting MPI program. Terminating! \n"); MPI_Abort(MPI_COMM_WORLD, rc); }; MPI_Comm_rank(MPI_COMM_WORLD, &BD_rank); MPI_Comm_size(MPI_COMM_WORLD, &BD_size); if (BD_size < 2) { if (BD_rank == 0) cout << "Error: MPI_SIZE must be > 1" << endl; MPI_Finalize(); exit(1); }; };
#include <cstdio> #include <cstdlib> #include <ctime> #include <vector> #include <GL/glew.h> #include <glfw3.h> #include <common/controls.hpp> #include <common/shader.hpp> #include <customs/shapes.hpp> #include <customs/things.hpp> using namespace glm; GLFWwindow* window; GLfloat random (GLfloat min, GLfloat max) { return min + (GLfloat) rand () / (GLfloat (RAND_MAX / (max-min))); } void generateRandomTree (int n, GLfloat height, GLfloat planeSize, std::vector<Object*> &objects) { GLfloat space[] = {-planeSize/2, 5}; for (int i = 0; i < n; i++) { GLfloat x, z; x = random (-planeSize/2, planeSize/2); GLfloat s = space[rand () % 2]; z = random (s, s+(planeSize/2)-5); int size = 5 + rand () % (10-5+1); objects.push_back (new Tree (x, height, z, size)); } } int initGL () { // initialize GLFW if (!glfwInit ()) { fprintf (stderr, "Failed to initialize GLFW\n"); getchar (); return -1; } glfwWindowHint (GLFW_SAMPLES, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow (800, 600, "FP", nullptr, nullptr); if (window == nullptr) { getchar (); glfwTerminate (); return -1; } glfwMakeContextCurrent (window); // Initialize GLEW glewExperimental = true; if (glewInit () != GLEW_OK) { fprintf (stderr, "Failed to initialize GLEW\n"); getchar (); glfwTerminate (); return -1; } glfwSetInputMode (window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetInputMode (window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwPollEvents (); glfwSetCursorPos (window, 1024/2, 768/2); glClearColor (0.4f, 0.6f, 0.9f, 0.0f); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LESS); glEnable (GL_CULL_FACE); return 0; } int main () { srand (static_cast <unsigned> (time (0))); if (initGL () == -1) return -1; GLuint programID = LoadShaders ("TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader"); GLuint MatrixID = glGetUniformLocation (programID, "MVP"); /* define all the objects here. */ std::vector<Object*> objects; //kepala objects.push_back(((Object*)((new Box (-6,-5,0,1,0,1,true))->setFaceColor(Box::FRONT, Color (67, 70,75, true))))); objects.push_back(((Object*)((new Box(-7,-6,0,0.5,0,1, true))->setFaceColor(Box::FRONT, Color(160,0,0, true))))); objects.push_back(((Object*)((new Cylinder(-6.5,0.5,0.5,0.25,0.75, true))->setSideColor (Color(67,70,75, true))))); //gerbong 1 objects.push_back(((Object*)((new Box(-5,-4.75,0.25,0.5,0.35,0.65, true))->setFaceColor (Box::FRONT, Color(160,0,0, true))))); objects.push_back(((Object*)((new Cube(-4.25,0,0.5,1, true))->setFaceColor(Box::FRONT,Color(67,70,75,true))))); //gerbong 2 objects.push_back (((Object*)((new Box(-3.75,-3.55,0.25,0.5,0.35,0.65, true))->setFaceColor(Box::FRONT, Color(160,0,0,true))))); objects.push_back (((Object*)((new Cube(-3.05,0,0.5,1, true))->setFaceColor(Box::FRONT, Color(67,70,75,true))))); //gerbong 3 objects.push_back (((Object*)((new Box(-2.55,-2.3,0.25,0.5,0.35,0.65, true))->setFaceColor(Box::FRONT,Color(160,0,0,true))))); objects.push_back (((Object*)((new Cube(-1.8,0,0.5,1, true))->setFaceColor(Box::FRONT,Color(67,70,75,true))))); //gerbong 4 objects.push_back (((Object*)((new Box(-1.3,-1,0.25,0.5,0.35,0.65, true))->setFaceColor(Box::FRONT,Color(160,0,0,true))))); objects.push_back (((Object*)((new Cube(-0.5,0,0.5,1, true))->setFaceColor(Box::FRONT,Color(67,70,75,true))))); //gerbong 5 objects.push_back (((Object*)((new Box(0,0.25,0.25,0.5,0.35,0.65, true))->setFaceColor(Box::FRONT, Color(160,0,0,true))))); objects.push_back (((Object*)((new Cube(0.75,0,0.5,1, true))->setFaceColor(Box::FRONT,Color(67,70,75,true))))); //danau objects.push_back (((Object*)((new Cylinder(-6,-0.25,6,3,0.01, false))->setCoverColor (Color(0,102,255,true))))); //pohon objects.push_back (new Tree(-4,-0.25,-6, 5)); objects.push_back (new Tree(-6,-0.25,-9, 5)); objects.push_back (new Tree(5,-0.25,-10, 5)); objects.push_back (new Tree(7,-0.25,8, 5)); objects.push_back (new Tree(10,-0.25,7, 5)); objects.push_back (new Tree(-11,-0.25,3, 5)); objects.push_back (new Tree(3,-0.25,2, 6)); objects.push_back (new Tree(9,-0.25,5, 5)); objects.push_back (new Tree(5,-0.25,8, 5)); objects.push_back (new Tree(7,-0.25,9, 7)); objects.push_back (new Tree(-9,-0.25,7, 5)); objects.push_back (new Tree(-10,-0.25,8, 5)); objects.push_back (new Tree(-4,-0.25,-6, 5)); objects.push_back (new Tree(1,-0.25,8, 5)); objects.push_back (new Tree(0,-0.25,-6, 5)); objects.push_back (new Tree(4,-0.25,-4, 5)); objects.push_back (new Tree(6,-0.25,-9, 6)); objects.push_back (new Tree(7,-0.25,-11, 5)); objects.push_back (new Tree(10,-0.25,-3, 5)); objects.push_back (new Tree(-10,-0.26,-11,8)); objects.push_back (new Tree(-9,-0.26,-11.5,8)); objects.push_back (new Tree(-8,-0.26,-10,8)); // earth objects.push_back (new Plane (0, -0.25f, 0, 25)); // rail objects.push_back (((Object*)((new Box (-12.5, 12.5, -0.25f, 0, 0, 1))->setFaceColor (Box::LEFT,Color (0,0,0, 1))->setFaceColor(Box::RIGHT,Color(0,0,0,1))->setFaceColor (Box::TOP, Color (0, 0, 0, 1))))); do { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram (programID); // Compute the MVP matrix from keyboard and mouse input computeMatricesFromInputs (); glm::mat4 ProjectionMatrix = getProjectionMatrix (); glm::mat4 ViewMatrix = getViewMatrix (); glm::mat4 ModelMatrix = glm::mat4 (1.0); glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; glUniformMatrix4fv (MatrixID, 1, GL_FALSE, &MVP[0][0]); for (int i = 0; i < objects.size (); i++) // render all objects defined objects[i]->render (); glfwSwapBuffers (window); glfwPollEvents (); } while (glfwGetKey (window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose (window) == 0); for (int i = 0; i < objects.size (); i++) objects[i]->clean (); glDeleteProgram (programID); // Close OpenGL window and terminate GLFW glfwTerminate (); return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxn = 150000 + 100; struct per { char nam[210];int v,ord; bool operator <(const per& rhs) const{ if (v != rhs.v) return v < rhs.v; else return ord > rhs.ord; } }; struct dor { int t,p; }; per p[maxn]; priority_queue<per> a; dor d[maxn]; int loc[110]; bool cmp(dor a,dor b) { return a.t < b.t; } int main() { int t; int k,m,q; scanf("%d",&t); while (t--) { scanf("%d%d%d",&k,&m,&q); for (int i = 1;i <= k; i++) { scanf("%s%d",p[i].nam,&p[i].v);p[i].ord = i; } for (int i = 0;i < m; i++) scanf("%d%d",&d[i].t,&d[i].p); sort(d,d+m,cmp); for (int i = 0;i < q; i++) scanf("%d",&loc[i]); sort(loc,loc+q); int sumin = 0,sumout = 0,fr = 0;per ans; for (int i = 0;i < m; i++) { for (int j = sumin+1; j <= d[i].t; j++) a.push(p[j]); sumin = d[i].t; for (int j = 1;j <= d[i].p; j++) { ans = a.top();a.pop(); //cout << sumout + j << " " << loc[fr] << endl; if (sumout + j == loc[fr]) { if (fr == 0) printf("%s",ans.nam); else printf(" %s",ans.nam); fr++; } } sumout += d[i].p; //cout << sumin << " " << sumout << endl; } printf("\n"); } return 0; }
#include <iostream> #include "src/dining_philosophers.h" int main(int argc, char** argv) { std::cout << "\e[1;32mAdding philosophers...\e[0m\n"; add_phil("Plato", 1, 3); add_phil("Kant", 2, 2); add_phil("Nietzsche", 3, 1); std::cout << "\e[1;32mPhilosophers added. Starting dinner...\e[0m\n"; start_dinner(100); return 0; }
// algorithm.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "../libalgorithm/algorithm.h" /* //最大子组问题 int find_max_cross_subarray(int a[], int *low, int *high) { int mid, i; int sum, lsum, rsum, lidx, ridx; mid = (*low + *high) / 2; sum = 0; lsum = 0x80000000; for (i = mid; i >= *low; i--) { sum += a[i]; if (sum > lsum) { lsum = sum; lidx = i; } } sum = 0; rsum = 0x80000000; for (i = mid + 1; i <= *high; i++) { sum += a[i]; if (sum > rsum) { rsum = sum; ridx = i; } } *low = lidx; *high = ridx; return (lsum + rsum); } int find_maximum_subarray(int a[], int *low, int *high) { int mid, llow, lhigh, rlow, rhigh, clow, chigh; int rsum, lsum, csum; if (*high == *low) { return a[*high]; } mid = (*low + *high) / 2; llow = *low; lhigh = mid; lsum = find_maximum_subarray(a, &llow, &lhigh); printf("left low:%d high:%d sum:%d\n", llow, lhigh, lsum); rlow = mid + 1; rhigh = *high; rsum = find_maximum_subarray(a, &rlow, &rhigh); printf("right low:%d high:%d sum:%d\n", rlow, rhigh, rsum); clow = *low; chigh = *high; csum = find_max_cross_subarray(a, &clow, &chigh); printf("cross low:%d high:%d sum:%d\n", clow, chigh, csum); if (lsum >= rsum && lsum >= csum) { *low = llow; *high = lhigh; return lsum; } if (rsum >= lsum && rsum >= csum) { *low = rlow; *high = rhigh; return rsum; } *low = clow; *high = chigh; return csum; } void find_maximum_subarray2(int a[], int len) { int i, j, sum; int maxsum, maxlow, maxhigh; maxlow = maxhigh = 0; maxsum = a[0]; for (j = 1; j < len; j++) { sum = 0; for (i = j; i >= 0; i--) { sum += a[i]; if (sum > maxsum) { maxsum = sum; maxlow = i; maxhigh = j; } } } printf("maximum array from %d to %d, sum:%d\n", maxlow, maxhigh, maxsum); } void find_maximum_subarray3(int *arr, int len) { int i; int low = 0, high = 0, tlow = 0; int MaxSum = 0; int CurSum = 0; for(i=0;i<len;i++) { CurSum += arr[i]; if(CurSum > MaxSum) { MaxSum = CurSum; low = tlow; high = i; } //如果累加和出现小于0的情况, //则和最大的子序列肯定不可能包含前面的元素, //这时将累加和置0,从下个元素重新开始累加 if(CurSum < 0) { tlow = i + 1; CurSum = 0; } } printf("maximum array from %d to %d, sum:%d\n", low, high, MaxSum); } */ #include "../libalgorithm/xtest.h" typedef struct { int key; rb_tree_st rb_tree; int udata; }rb_test_st; typedef struct { int kseq[64]; int cur; }rb_chk_st; int rb_my_cmp(rb_tree_st *l, rb_tree_st *r) { rb_test_st *lt = rb_entry(l, rb_test_st, rb_tree); rb_test_st *rt = rb_entry(r, rb_test_st, rb_tree); return (lt->key - rt->key); } int xtest_check1(rb_tree_st *n, void *udata) { rb_test_st *t = rb_entry(n, rb_test_st, rb_tree); rb_chk_st *chk = (rb_chk_st *)udata; EXPECT_EQ(t->key, chk->kseq[chk->cur]); chk->cur++; return 0; } int _tmain(int argc, _TCHAR* argv[]) { /* 最大子数组测试用例 int low, high, sum; int a[] = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7}; low = 0; high = 15; sum = find_maximum_subarray(a, &low, &high); printf("maximum array from %d to %d, sum:%d\n", low, high, sum); */ /* int a[] = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7}; find_maximum_subarray2(a, 16); find_maximum_subarray3(a, 16); */ int i; rb_tree_st *root = NULL; rb_test_st t[10]; rb_chk_st chk1; t[0].key = 1; t[1].key = 2; t[2].key = 4; for (i = 0; i < 3; i++) { rb_tree_insert(&root, &t[i].rb_tree, rb_my_cmp); } EXPECT_EQ(rb_tree_height(root), 2); chk1.cur = 0; chk1.kseq[0] = 1; chk1.kseq[1] = 2; chk1.kseq[2] = 4; rb_tree_walk(root, xtest_check1, (void*)&chk1); t[3].key = 5; t[4].key = 7; t[5].key = 8; t[6].key = 11; t[7].key = 14; t[8].key = 15; for (i = 3; i < 9; i++) { rb_tree_insert(&root, &t[i].rb_tree, rb_my_cmp); } chk1.kseq[3] = 5; chk1.kseq[4] = 7; chk1.kseq[5] = 8; chk1.kseq[6] = 11; chk1.kseq[7] = 14; chk1.kseq[8] = 15; EXPECT_EQ(rb_tree_height(root), 4); chk1.cur = 0; rb_tree_walk(root, xtest_check1, (void*)&chk1); return 0; }
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #ifndef ISP_HPP_ #define ISP_HPP_ /*! \brief In-circuit Serial Programming * */ namespace isp {} #include "isp/LpcIsp.hpp" using namespace isp; #endif /* ISP_HPP_ */
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> using namespace std; vector<int> prime; vector<int> not_prime; bool is_prime[1003]; class ColorfulCards { public: vector <int> theCards(int N, string colors) { bool is_prime[1003]; memset(is_prime, true, sizeof(is_prime)); is_prime[1] = false; for (int i=2; i<=N; ++i) { if (is_prime[i]) { for (int j=2*i; j<=N; j+=i) { is_prime[j] = false; } } } vector<int> low(colors.size()); int x = 0; for (int i=0; i<colors.size(); ++i) { do { ++x; } while (is_prime[x] == (colors[i] == 'B') ); low[i] = x; } vector<int> high(colors.size()); x = N+1; for (int i=(int)colors.size()-1; i>=0; --i) { do { --x; } while (is_prime[x] == (colors[i] == 'B')); high[i] = x; } vector<int> ans(colors.size()); for (int i=0; i<colors.size(); ++i) { ans[i] = low[i]==high[i]?low[i]:-1; } return ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { int Arg0 = 5; string Arg1 = "RRR"; int Arr2[] = {2, 3, 5 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, theCards(Arg0, Arg1)); } void test_case_1() { int Arg0 = 7; string Arg1 = "BBB"; int Arr2[] = {1, 4, 6 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, theCards(Arg0, Arg1)); } void test_case_2() { int Arg0 = 6; string Arg1 = "RBR"; int Arr2[] = {-1, 4, 5 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, theCards(Arg0, Arg1)); } void test_case_3() { int Arg0 = 58; string Arg1 = "RBRRBRBBRBRRBBRRBBBRRBBBRR"; int Arr2[] = {-1, -1, -1, -1, -1, -1, -1, -1, 17, 18, 19, 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 47, 53 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, theCards(Arg0, Arg1)); } void test_case_4() { int Arg0 = 495; string Arg1 = "RBRRBRBBRBRRBBRRBBBRRBBBRR"; int Arr2[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, theCards(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { ColorfulCards ___test; ___test.run_test(-1); } // END CUT HERE
/* ** MenuController.cpp for cpp_indie_studio in /home/jabbar_y/rendu/cpp_indie_studio/MenuController.cpp ** ** Made by Yassir Jabbari ** Login <yassir.jabbari@epitech.eu> ** ** Started on Sat May 06 13:52:58 2017 Yassir Jabbari // Last update Wed Jun 14 10:48:19 2017 Stanislas Deneubourg */ #include "Model/MenuModel.hpp" MenuModel::MenuModel(irr::IrrlichtDevice *device, irr::video::IVideoDriver *driver, irr::scene::ISceneManager *smgr, irr::gui::IGUIEnvironment *guienv, std::vector<std::string> const &saves, bool &playSound, bool &drawWalls, irr::s32 *NbrHumanTeams, irr::s32 *NbrBotTeams, irr::s32 *NbrTeams, irr::s32 *NbrWormsPerTeam, irrklang::ISound *mainSound, bool *playMainSound) : _device(device), _driver(driver), _smgr(smgr),_guienv(guienv), event(device, mainSound, playMainSound) { this->_device->setWindowCaption(L"Worms 3D"); this->_device->setEventReceiver(&this->event); this->skin = this->_guienv->createSkin(irr::gui::EGST_WINDOWS_METALLIC); this->_guienv->setSkin(this->skin); this->skin->drop(); this->font = this->_guienv->getFont("ressources/fonts/SoftMarshmallow.png"); if (this->font != nullptr) this->_guienv->getSkin()->setFont(this->font); this->playSound = &playSound; this->drawWalls = &drawWalls; this->selected = -1; this->_saves = saves; this->event.setNbrBotTeams(NbrBotTeams); this->event.setNbrHumanTeams(NbrHumanTeams); this->event.setNbrTeams(NbrTeams); this->event.setNbrWormsPerTeam(NbrWormsPerTeam); } MenuModel::~MenuModel() { this->_guienv->clear(); } void MenuModel::setModelProperties() { irr::video::ITexture *cursor; this->screenSize = this->_driver->getScreenSize(); this->setSkinTransparency(); this->background = this->_driver->getTexture("ressources/images/worms_main_menu.png"); this->tabctrl = this->_guienv->addTabControl(irr::core::rect<int>(this->screenSize.Width / 3, this->screenSize.Height / 5, this->screenSize.Width - (this->screenSize.Width / 3), this->screenSize.Height - (this->screenSize.Height / 7)), nullptr, false, false); // CURSOR if (this->_guienv->getSpriteBank(irr::io::path("ressources/buttons")) == nullptr) this->spriteBank = this->_guienv->addEmptySpriteBank(irr::io::path("ressources/buttons")); else this->spriteBank = this->_guienv->getSpriteBank(irr::io::path("ressources/buttons")); cursor = this->_driver->getTexture("ressources/cursor/cursor.png"); if (cursor != nullptr) { this->cursorSize = cursor->getSize(); this->spriteBank->addTextureAsSprite(cursor); } this->SetMenuModelMainOptions(); this->setMenuModelSubButtons(); this->_device->getCursorControl()->setVisible(false); irr::core::rect<irr::s32> tabctrlSize = this->tabctrl->getRelativePosition(); irr::s32 tabctrlWidth = tabctrlSize.getWidth(); irr::s32 tabctrlHeight = tabctrlSize.getHeight(); this->midTabctrl = tabctrlSize.getCenter(); this->event.setSelected(this->selected); this->event.setSavesListBox(this->_guienv->addListBox(irr::core::rect<int>(tabctrlWidth / 10, tabctrlHeight / 5, tabctrlWidth - (this->midTabctrl.X / 8), tabctrlHeight - (this->midTabctrl.Y / 3)), this->tabctrl, 1), this->_saves); if (this->spriteBank->getTexture(irr::u32(MenuModel::MenuSpriteName::SAVE_SUB_MENU)) != nullptr) this->saveSubMenuSpriteSize = this->spriteBank->getTexture(irr::u32(MenuModel::MenuSpriteName::SAVE_SUB_MENU))->getSize(); this->event.setPlayAGameSubMenu(this->_driver, this->_guienv, this->tabctrl); } EventStatus MenuModel::launchModel() { EventStatus eventStatus = EventStatus::STAND_BY; this->event.setEventStatus(eventStatus); while (this->_device->run()) { if (this->_device->isWindowActive()) { this->_driver->beginScene(); if (this->background != nullptr) this->_driver->draw2DImage(this->background, irr::core::position2d<int>(0, 0)); if (this->spriteBank->getTexture(irr::u32(MenuModel::MenuSpriteName::SAVE_SUB_MENU)) != nullptr && this->event.getPressedButton() == MenuButton::SAVES) { this->spriteBank->draw2DSprite(irr::u32(MenuModel::MenuSpriteName::SAVE_SUB_MENU), irr::core::position2di( (this->screenSize.Width / 2) - this->saveSubMenuSpriteSize.Width / 2, (this->screenSize.Height / 4) - this->saveSubMenuSpriteSize.Height / 2), nullptr, irr::video::SColor(255, 255, 255, 255), 0); } if (this->event.getPressedButton() == MenuButton::PLAY_A_GAME && this->font != nullptr) this->drawPlaySubMenuText(); if (eventStatus != EventStatus::STAND_BY) { *this->playSound = this->event.getCheckboxSoundStatus(); *this->drawWalls = this->event.getCheckboxWallsStatus(); break; } this->_guienv->drawAll(); if (this->spriteBank->getTexture(irr::u32(MenuModel::MenuSpriteName::CURSOR)) != nullptr) { irr::core::position2d<irr::s32> mousePosition = this->_device->getCursorControl()->getPosition(); this->spriteBank->draw2DSprite(irr::u32(MenuModel::MenuSpriteName::CURSOR), irr::core::position2di(mousePosition.X - this->cursorSize.Width / 4, mousePosition.Y - this->cursorSize.Height / 8), nullptr, irr::video::SColor(255, 255, 255, 255), 0); } this->_driver->endScene(); } } return (eventStatus); } void MenuModel::setSkinTransparency() { for (irr::s32 i = 0; i < irr::gui::EGDC_COUNT ; ++i) { if ((irr::gui::EGUI_DEFAULT_COLOR)i != irr::gui::EGDC_HIGH_LIGHT_TEXT) this->skin->setColor((irr::gui::EGUI_DEFAULT_COLOR)i, irr::video::SColor(0, 0, 0, 0)); } this->skin->setColor(irr::gui::EGDC_BUTTON_TEXT, irr::video::SColor(255, 255, 190, 0)); } void MenuModel::setMenuModelSubButtons() { irr::core::dimension2d<irr::s32> image_size; irr::video::ITexture *texture; // CHECKBOXES texture = this->_driver->getTexture("ressources/buttons/checkboxes/sound_checked.png"); if (texture != nullptr) { image_size = texture->getSize(); this->checkboxSound = this->_guienv->addButton(irr::core::rect<int>((image_size.Width / 9), ((image_size.Height / 2)), (image_size.Width), ((image_size.Height) * 3) / 2), this->tabctrl, MenuButton::OPTION_SOUND, L""); this->event.setSoundCheckboxAndTextures(this->checkboxSound, texture, this->_driver->getTexture( "ressources/buttons/checkboxes/sound_not_checked.png")); texture = this->_driver->getTexture("ressources/buttons/checkboxes/closed_map_checked.png"); image_size = texture->getSize(); this->wallsCheckbox = this->_guienv->addButton(irr::core::rect<int>((image_size.Width / 9), ((image_size.Height / 2) * 4), (image_size.Width), ((image_size.Height) * 6) / 2), this->tabctrl, MenuButton::OPTION_MAP, L""); this->event.setWallsCheckboxAndTextures(this->wallsCheckbox, texture, this->_driver->getTexture( "ressources/buttons/checkboxes/closed_map_not_checked.png")); } // BACK texture = this->_driver->getTexture("ressources/buttons/back.png"); if (texture != nullptr) { image_size = texture->getSize(); this->event.setBackButton(this->_guienv->addButton(irr::core::rect<irr::s32>(this->tabctrl->getTabExtraWidth(), (image_size.Height * 8), (image_size.Width * 2), (image_size.Height * 9)) , this->tabctrl, MenuButton::BACK, L""), texture); } } void MenuModel::drawPlaySubMenuText() { std::string text_and_nbr; text_and_nbr = "Number of teams: "; text_and_nbr += std::to_string(this->event.getNbrTeams()); this->font->draw(text_and_nbr.c_str(), irr::core::rect<irr::s32>(this->midTabctrl.X - (text_and_nbr.size() * 4), (this->midTabctrl.Y / 2) + text_and_nbr.size(), this->midTabctrl.X, this->midTabctrl.Y / 2), irr::video::SColor(255, 255, 190, 0)); text_and_nbr.clear(); text_and_nbr = "Human teams: "; text_and_nbr += std::to_string(this->event.getNbrHumanTeams()); this->font->draw(text_and_nbr.c_str(), irr::core::rect<irr::s32>(this->midTabctrl.X - (text_and_nbr.size() * 3), this->midTabctrl.Y - (text_and_nbr.size() * 11), this->midTabctrl.X, (this->midTabctrl.Y / 2) + 38), irr::video::SColor(255, 255, 190, 0)); text_and_nbr.clear(); text_and_nbr = "AI teams: "; text_and_nbr += std::to_string(this->event.getNbrBotTeams()); this->font->draw(text_and_nbr.c_str(), irr::core::rect<irr::s32>(this->midTabctrl.X - (text_and_nbr.size() * 2), this->midTabctrl.Y - (text_and_nbr.size() * 4), this->midTabctrl.X, (this->midTabctrl.Y / 2) + 38), irr::video::SColor(255, 255, 190, 0)); text_and_nbr.clear(); text_and_nbr = "Worms per team: "; text_and_nbr += std::to_string(this->event.getNbrWormsPerTeam()); this->font->draw(text_and_nbr.c_str(), irr::core::rect<irr::s32>(this->midTabctrl.X - (text_and_nbr.size() * 4), this->midTabctrl.Y + (text_and_nbr.size() * 4), this->midTabctrl.X, (this->midTabctrl.Y / 2) + 38), irr::video::SColor(255, 255, 190, 0)); }
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <stack> #include <unordered_map> #include <unordered_set> #include <queue> #include <algorithm> #define INT_MAX 0x7fffffff #define INT_MIN 0x80000000 using namespace std; int trap(int A[],int n){ //Left high int left[n],right[n]; int maxNum = 0; left[0] = 0; right[n-1] = 0; cout << endl; for(int i=1;i<n;i++){ maxNum = max(A[i-1],maxNum); left[i] = maxNum; } maxNum=0; //Right high for(int i=n-2;i>=0;i--){ maxNum = max(A[i+1],maxNum); right[i] = maxNum; } int res = 0; for(int i=0;i<n;i++){ int k = min(left[i],right[i]); res += k>A[i]?k-A[i]:0; } return res; } int main(){ int n,temp; cin >> n; int A[n]; for(int i=0;i<n;i++){ cin >> temp; A[i] = temp; cout << temp << " "; } cout << "\nRes: " << trap(A,n) << endl; }
#pragma once #include "Singleton.h" class HGE; class CSceneManager; class CGameEngine : public CSingleton<CGameEngine> { public: CGameEngine(); ~CGameEngine(); void RunEngine(); private: //Íâ°üº¯Êý static bool FrameFunc(); static bool ReaderFunc(); bool Init(); void Release(); bool Render(); bool Update(); private: CSceneManager* m_pMgr; static HGE* m_pHge; };
// Fill out your copyright notice in the Description page of Project Settings. #include "FightWithBlock.h" #include "HerosBase.h" #include "BlockBase.h" // Sets default values AHerosBase::AHerosBase() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; bReplicates = true; bReplicateMovement = true; Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); Camera->SetRelativeLocation(FVector(0.f, 0.f, 80.f)); Camera->AttachTo(RootComponent); Camera->bUsePawnControlRotation = true; ConstructorHelpers::FObjectFinder<USkeletalMesh> FPSSkeletalMesh(TEXT("SkeletalMesh'/Game/FirstPerson/Character/Mesh/SK_Mannequin_Arms.SK_Mannequin_Arms'")); FPSMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("myFPSMesh")); FPSMesh->SetSkeletalMesh(FPSSkeletalMesh.Object); FPSMesh->SetRelativeLocation(FVector(0, 0, -170)); FPSMesh->SetRelativeRotation(FRotator(0, -90, 0)); FPSMesh->AttachTo(Camera); FPSMesh->bCastDynamicShadow = false; FPSMesh->CastShadow = false; FPSMesh->SetOnlyOwnerSee(true); ConstructorHelpers::FObjectFinder<USkeletalMesh> TPSSkeletalMesh(TEXT("SkeletalMesh'/Game/Mannequin/Character/Mesh/SK_Mannequin.SK_Mannequin'")); //ConstructorHelpers::FObjectFinder<UAnimBlueprint> AnimBlueprint(TEXT("AnimBlueprint'/Game/myBlueprint/PlayerAnimBP.PlayerAnimBP'")); GetMesh()->SetSkeletalMesh(TPSSkeletalMesh.Object); GetMesh()->SetRelativeLocation(FVector(0, 0, -90)); GetMesh()->SetOwnerNoSee(true); GetMesh()->SetRelativeRotation(FRotator(0, -90, 0)); /*if (AnimBlueprint.Succeeded()) { GetMesh()->SetAnimInstanceClass(AnimBlueprint.Object->GeneratedClass); }*/ GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); GetCapsuleComponent()->SetCollisionObjectType(ECollisionChannel::ECC_Pawn); GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_GameTraceChannel1, ECollisionResponse::ECR_Overlap); //GetCapsuleComponent()->OnComponentBeginOverlap.AddDynamic(this, &AHerosBase::BeginOverlap); //GetCapsuleComponent()->OnComponentEndOverlap.AddDynamic(this, &AHerosBase::EndOverlap); MineTraceStartArrow = CreateDefaultSubobject<UArrowComponent>(TEXT("MineTraceStartArrow")); MineTraceStartArrow->AttachTo(Camera); MineTraceStartArrow->SetRelativeLocation(FVector(0, 0, 0)); MineTraceStartArrow->SetHiddenInGame(true); AutoPossessPlayer = EAutoReceiveInput::Player0; //测试用要删的!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //多打几行引起注意!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //HeroProperty.LifeValue = 1; //HeroProperty.BlockDamage = 1; //HeroProperty.MineRate = 0.2; //HeroProperty.MineDistance = 200; //ConstructorHelpers::FObjectFinder<UDataTable> TestTable(TEXT("DataTable'/Game/myBlueprint/DataTables/TestUse.TestUse'")); //if (TestTable.Succeeded()) //{ // GEngine->AddOnScreenDebugMessage(-1, 4, FColor::Red, TEXT("Find TestUse")); // UDataTable* TestUse = TestTable.Object; // TArray<FName> RowNames = TestUse->GetRowNames(); // FHero* MyHero = TestUse->FindRow<FHero>(RowNames[0], TEXT("")); // UE_LOG(LogTemp, Warning, TEXT("%s"), *MyHero->dName.ToString()); //} } // Called when the game starts or when spawned void AHerosBase::BeginPlay() { Super::BeginPlay(); if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("this is MyHeros!")); } //handBlock = &Bag[0]; } // Called every frame void AHerosBase::Tick(float DeltaTime) { Super::Tick(DeltaTime); //RunBUFF(DeltaTime); //MineTimeCounter += DeltaTime; } // Called to bind functionality to input void AHerosBase::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("MoveForward", this, &AHerosBase::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AHerosBase::MoveRight); PlayerInputComponent->BindAxis("TurnX", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnY", this, &APawn::AddControllerPitchInput); //PlayerInputComponent->BindAction("Item_1", IE_Pressed, this, &AHerosBase::chooseItem_1); //PlayerInputComponent->BindAction("Item_2", IE_Pressed, this, &AHerosBase::chooseItem_2); //PlayerInputComponent->BindAction("Item_3", IE_Pressed, this, &AHerosBase::chooseItem_3); //PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &AHerosBase::Fire); //PlayerInputComponent->BindAction("GetItem", IE_Pressed, this, &AHerosBase::Pressed_R); //PlayerInputComponent->BindAction("GetItem", IE_Released, this, &AHerosBase::Released_R); //PlayerInputComponent->BindAction("MineBlock", IE_Pressed, this, &AHerosBase::MineBlock); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AHerosBase::Jump); } void AHerosBase::MoveForward(float val) { AddMovementInput(GetActorForwardVector(), val * 10); } void AHerosBase::MoveRight(float val) { AddMovementInput(GetActorRightVector(), val * 10); } //bool AHerosBase::AddItem(FBlock Item) //{ // for (int i = 0; i < BAGSPACE; i++) // { // if (Bag[i].Empty) // { // Bag[i].Block = Item; // Bag[i].Empty = false; // AddBUFF(Item.ToOwnerBUFF); // return true; // } // } // if (!handBlock->Empty) // { // UWorld* World = GetWorld(); // if (World) // { // GEngine->AddOnScreenDebugMessage(-1, 4, FColor::Red, TEXT("FULL!!!")); // FActorSpawnParameters SpawnParams; // SpawnParams.Owner = this; // SpawnParams.Instigator = Instigator; // ACBGBlock* tempBlock = World->SpawnActor<ACBGBlock>(Camera->GetComponentLocation(), GetActorRotation(), SpawnParams); // tempBlock->SetInitProperty(handBlock->Block); // handBlock->Block = Item; // handBlock->Empty = false; // AddBUFF(Item.ToOwnerBUFF); // return true; // } // } // GEngine->AddOnScreenDebugMessage(-1, 4, FColor::Red, TEXT("Warning!!!")); // return false; //} // //void AHerosBase::chooseItem_1() //{ // handBlock = &Bag[0]; //} //void AHerosBase::chooseItem_2() //{ // handBlock = &Bag[1]; //} //void AHerosBase::chooseItem_3() //{ // handBlock = &Bag[2]; //} // //FVector AHerosBase::GetFireLocation() //{ // FVector tempLocation = FVector(0, 0, 0); // return tempLocation; //} // //FRotator AHerosBase::GetFireRotation() //{ // FRotator tempRotation = FRotator(0, 0, 0); // return tempRotation; //} // //void AHerosBase::Fire() //{ // if (!handBlock->Empty) // { // UWorld* World = GetWorld(); // if (World) // { // UE_LOG(LogTemp, Warning, TEXT("%s"), *(MineTraceStartArrow->GetComponentLocation()).ToString()); // ABoltBlock* tempBlock = World->SpawnActor<ABoltBlock>(MineTraceStartArrow->GetComponentLocation(), MineTraceStartArrow->GetComponentRotation()); //// tempBlock->SetInitProperty(handBlock->Block, this); // tempBlock->SetFireDirection(MineTraceStartArrow->GetForwardVector(), 1000); // handBlock->Empty = true; // } // } //} // //void AHerosBase::ReloadProperty() //{ // //MovementComponent->MaxWalkSpeed = 300.f; // //HeroProperty.MoveSpeed //} // // //void AHerosBase::AddBUFF(FBUFF BUFF) //{ // //GEngine->AddOnScreenDebugMessage(-1, 4, FColor::Green, TEXT("addBUFF")); // myBUFF.Add(BUFF); //} // //void AHerosBase::RunBUFF(float DeltaTime) //{ // // for (int i = 0; i < myBUFF.Num(); i++) // { // myBUFF[i].LifeTime -= DeltaTime; // if (myBUFF[i].LifeTime <= 0) // { // EndBUFF(i); // return; // } // else if (!myBUFF[i].IsRun) // { // myBUFF[i].IsRun = true; // if (myBUFF[i].xuanyun) // { // MovementComponent->MaxWalkSpeed = 0; // } // if (!myBUFF[i].alreadyChangeSpeed) // MovementComponent->MaxWalkSpeed *= myBUFF[i].changeSpeed; // HeroProperty.LifeValue += myBUFF[i].changeHP * DeltaTime; // HeroProperty.Power += myBUFF[i].changePower * DeltaTime; // // myBUFF[i].TempParticle = UGameplayStatics::SpawnEmitterAttached(myBUFF[i].Particle, GetCapsuleComponent()); // } // } //} // //void AHerosBase::EndBUFF(int i) //{ // // if (myBUFF[i].TempParticle) // { // GEngine->AddOnScreenDebugMessage(-1, 4, FColor::Green, TEXT("rEMOVE")); // myBUFF[i].TempParticle->DestroyComponent(); // } // myBUFF.RemoveAt(i); // ReloadProperty(); //} // //void AHerosBase::BeginOverlap(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherCompnent, int32 OtherBodyIndex, bool FromSweep, const FHitResult& Hit) //{ // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, TEXT("Overlap!")); // ACBGBlock* CBGBlock = Cast<ACBGBlock>(OtherActor); // if (CBGBlock) // { // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, TEXT("Find!")); // AddBlockToPre(CBGBlock); // } //} // //void AHerosBase::EndOverlap(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherCompnent, int32 OtherBodyIndex) //{ // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, TEXT("EndOverlap!")); // ACBGBlock* CBGBlock = Cast<ACBGBlock>(OtherActor); // if (CBGBlock) // { // RemoveBlockFromPre(CBGBlock); // } //} // //void AHerosBase::AddBlockToPre(ACBGBlock* Block) //{ // for (int i = 0; i < 3; i++) // { // if (printBlock[i] == NULL) // { // printBlock[i] = Block; // break; // } // } //} // //void AHerosBase::RemoveBlockFromPre(ACBGBlock* Block) //{ // for (int i = 0; i < 3; i++) // { // if (printBlock[i] == Block) // { // printBlock[i] = NULL; // break; // } // } //} // //void AHerosBase::Pressed_R() //{ // for (int i = 0; i < 3; i++) // { // if (printBlock[i] != NULL) // { // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, TEXT("PreGET!")); // if (AddItem(printBlock[i]->BlockProperty)) // { // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Blue, TEXT("GET!")); // printBlock[i]->DestroySelf(); // printBlock[i] = NULL; // break; // } // else // { // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("GETFalse!")); // printBlock[i] = NULL; // } // } // } //} // //void AHerosBase::Released_R() //{ // Keyboard_F_Pressed = false; //} // //void AHerosBase::PrintItem(FBlock BlockProperty) //{ // //} // //void AHerosBase::MineBlock() //{ // if (MineTimeCounter >= HeroProperty.MineRate) // { // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Mine")); // MineTimeCounter = 0; // UWorld* World = GetWorld(); // if (World) // { // FHitResult TraceHit; // //UE_LOG(LogTemp, Warning, TEXT("起始点:%s"), *(MineTraceStartArrow->GetComponentLocation()).ToString()); // //UE_LOG(LogTemp, Warning, TEXT("末尾点:%s"), *(MineTraceStartArrow->GetComponentLocation() + MineTraceStartArrow->GetForwardVector() * HeroProperty.MineDistance).ToString()); // //UE_LOG(LogTemp, Warning, TEXT("距离:%f"), ((MineTraceStartArrow->GetForwardVector() * HeroProperty.MineDistance) - (MineTraceStartArrow->GetComponentLocation())).Size()); // if (World->LineTraceSingleByChannel(TraceHit, MineTraceStartArrow->GetComponentLocation(), MineTraceStartArrow->GetComponentLocation() + MineTraceStartArrow->GetForwardVector() * HeroProperty.MineDistance, ECollisionChannel::ECC_Visibility)) // { // MineLineTraceResult(TraceHit); // } // } // } // else // return; //} // //void AHerosBase::MineLineTraceResult(const FHitResult& Hit) //{ // ABlockBase* HitBlock = Cast<ABlockBase>(Hit.GetActor()); // if (HitBlock) // { // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("MineHit")); // //HitBlock->ApplyPointDamage(this, HeroProperty.BlockDamage); // } //} // //void AHerosBase::ApplyPointDamage(AHerosBase* Causer, int32 DamageValue) //{ // HeroProperty.LifeValue -= DamageValue; // if (HeroProperty.LifeValue <= 0) // { // Death(Causer); // } //} // //void AHerosBase::Death(AHerosBase* Causer) //{ // if (GetWorld()) //// GetWorld()->GetAuthGameMode<AMyGameMode>()->PrintKillMessage(Causer, this); // this->Destroy(true); // return; //}
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include <core/pch.h> #ifdef EXTENSION_SUPPORT #include "modules/dom/src/extensions/domextensioncontext.h" #include "modules/dom/src/extensions/domextensionuiitem.h" #include "modules/dom/src/extensions/domextensionuiitemevent.h" #include "modules/dom/src/extensions/domextensionuipopup.h" #include "modules/dom/src/extensions/domextensionuibadge.h" #include "modules/ecmascript_utils/essched.h" #include "modules/doc/frm_doc.h" #include "modules/gadgets/OpGadgetManager.h" /* static */ OP_STATUS DOM_ExtensionContext::Make(DOM_ExtensionContext *&new_obj, DOM_ExtensionSupport *support, DOM_ExtensionContexts::ContextType type, DOM_Runtime *origining_runtime) { RETURN_IF_ERROR(DOMSetObjectRuntime(new_obj = OP_NEW(DOM_ExtensionContext, (support, static_cast<unsigned int>(type))), origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::EXTENSION_CONTEXT_PROTOTYPE), "Context")); if (type == DOM_ExtensionContexts::CONTEXT_TOOLBAR) new_obj->m_max_items = 1; return OpStatus::OK; } void DOM_ExtensionContext::ExtensionUIListenerCallbacks::ItemAdded(OpExtensionUIListener::ExtensionId i, OpExtensionUIListener::ItemAddedStatus status) { OP_ASSERT((m_owner->m_parent && m_owner->m_parent->m_active_extension_id == i) || (!m_owner->m_parent && m_owner->m_active_extension_id == i)); if (m_owner->m_parent) m_owner->m_parent->m_add_status = status; else m_owner->m_add_status = status; /* Unblocking the thread will restart the call => status will be seen & acted on. */ if (m_owner->m_parent && m_owner->m_parent->m_blocked_thread) { OpStatus::Ignore(m_owner->m_parent->m_blocked_thread->Unblock()); m_owner->m_parent->GetThreadListener()->ES_ThreadListener::Remove(); m_owner->m_parent->m_blocked_thread = NULL; } else if (m_owner->m_blocked_thread) { OpStatus::Ignore(m_owner->m_blocked_thread->Unblock()); m_owner->GetThreadListener()->ES_ThreadListener::Remove(); m_owner->m_blocked_thread = NULL; } /* Only keep the parent alive across an async call. */ if (m_owner->m_parent) m_owner->m_parent = NULL; } void DOM_ExtensionContext::ExtensionUIListenerCallbacks::ItemRemoved(OpExtensionUIListener::ExtensionId i, OpExtensionUIListener::ItemRemovedStatus status) { OP_ASSERT((m_owner->m_parent && m_owner->m_parent->m_active_extension_id == i) || (!m_owner->m_parent && m_owner->m_active_extension_id == i)); if (m_owner->m_parent) m_owner->m_parent->m_remove_status = status; if (m_owner->m_parent && m_owner->m_parent->m_blocked_thread) { OpStatus::Ignore(m_owner->m_parent->m_blocked_thread->Unblock()); m_owner->m_parent->GetThreadListener()->Out(); m_owner->m_parent->m_blocked_thread = NULL; } if (status == OpExtensionUIListener::ItemRemovedSuccess) OnRemove(i); } void DOM_ExtensionContext::ExtensionUIListenerCallbacks::OnClick(OpExtensionUIListener::ExtensionId i) { if (m_owner->IsA(DOM_TYPE_EXTENSION_UIITEM)) { DOM_ExtensionUIItem *it = static_cast<DOM_ExtensionUIItem*>(m_owner); DOM_Runtime *runtime = it->GetRuntime(); DOM_ExtensionUIItemEvent *click_event; RETURN_VOID_IF_ERROR(DOM_ExtensionUIItemEvent::Make(click_event, it, runtime)); ES_Value argv[3]; /* ARRAY OK 2010-09-13 sof */ ES_Value value; DOMSetString(&argv[0], UNI_L("click")); DOMSetBoolean(&argv[1], FALSE); DOMSetBoolean(&argv[2], FALSE); DOM_Event::initEvent(click_event, argv, ARRAY_SIZE(argv), &value, runtime); click_event->InitEvent(ONCLICK, it); click_event->SetCurrentTarget(it); click_event->SetSynthetic(); click_event->SetEventPhase(ES_PHASE_ANY); it->GetEnvironment()->SendEvent(click_event); } } void DOM_ExtensionContext::ExtensionUIListenerCallbacks::OnRemove(OpExtensionUIListener::ExtensionId i) { if (m_owner->IsA(DOM_TYPE_EXTENSION_UIITEM)) { DOM_ExtensionUIItem *it = static_cast<DOM_ExtensionUIItem*>(m_owner); DOM_Runtime *runtime = it->GetRuntime(); DOM_ExtensionUIItemEvent *remove_event; RETURN_VOID_IF_ERROR(DOM_ExtensionUIItemEvent::Make(remove_event, it, runtime)); ES_Value argv[3]; /* ARRAY OK 2010-09-13 sof */ ES_Value unused_value; DOM_Object::DOMSetString(&argv[0], UNI_L("remove")); DOM_Object::DOMSetBoolean(&argv[1], FALSE); DOM_Object::DOMSetBoolean(&argv[2], FALSE); DOM_Event::initEvent(remove_event, argv, ARRAY_SIZE(argv), &unused_value, runtime); remove_event->InitEvent(ONREMOVE, it); remove_event->SetCurrentTarget(it); remove_event->SetSynthetic(); remove_event->SetEventPhase(ES_PHASE_ANY); it->GetEnvironment()->SendEvent(remove_event); } } /* static */ int DOM_ExtensionContext::createItem(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime) { DOM_THIS_OBJECT(context, DOM_TYPE_EXTENSION_CONTEXT, DOM_ExtensionContext); if (argc < 0) { DOM_ExtensionUIItem *item = DOM_VALUE2OBJECT(*return_value, DOM_ExtensionUIItem); item->m_is_loading_image = FALSE; return DOM_ExtensionUIItem::CopyIconImage(this_object, item, return_value); } DOM_CHECK_ARGUMENTS("o"); if (context->IsA(DOM_TYPE_EXTENSION_UIITEM)) return DOM_CALL_INTERNALEXCEPTION(WRONG_THIS_ERR); if (static_cast<DOM_ExtensionContexts::ContextType>(context->m_id) != DOM_ExtensionContexts::CONTEXT_TOOLBAR) return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); return CreateItem(this_object, context->m_extension_support, argv[0].value.object, return_value, origining_runtime); } /* static */ int DOM_ExtensionContext::CreateItem(DOM_Object *this_object, DOM_ExtensionSupport *extension_support, ES_Object *properties, ES_Value *return_value, DOM_Runtime *origining_runtime) { DOM_Runtime *runtime = this_object->GetRuntime(); ES_Value value; OP_BOOLEAN result; DOM_ExtensionUIItem *item; CALL_FAILED_IF_ERROR(DOM_ExtensionUIItem::Make(item, extension_support, runtime)); CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("disabled"), &value)); item->m_disabled = result == OpBoolean::IS_TRUE && value.type == VALUE_BOOLEAN && value.value.boolean; CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("title"), &value)); if (result == OpBoolean::IS_TRUE && value.type == VALUE_STRING) if ((item->m_title = UniSetNewStr(value.value.string)) == NULL) return ES_NO_MEMORY; CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("icon"), &value)); if (result == OpBoolean::IS_TRUE && value.type == VALUE_STRING) if ((item->m_favicon = UniSetNewStr(value.value.string)) == NULL) return ES_NO_MEMORY; CALL_FAILED_IF_ERROR(DOM_ExtensionSupport::AddEventHandler(item, item->m_onclick_handler, properties, NULL, origining_runtime, UNI_L("onclick"), ONCLICK)); CALL_FAILED_IF_ERROR(DOM_ExtensionSupport::AddEventHandler(item, item->m_onremove_handler, properties, NULL, origining_runtime, UNI_L("onremove"), ONREMOVE)); CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("popup"), &value)); if (result == OpBoolean::IS_TRUE && value.type == VALUE_OBJECT) CALL_FAILED_IF_ERROR(DOM_ExtensionUIPopup::Make(item->m_popup, value.value.object, item, return_value, origining_runtime)); CALL_FAILED_IF_ERROR(result = runtime->GetName(properties, UNI_L("badge"), &value)); if (result == OpBoolean::IS_TRUE && value.type == VALUE_OBJECT) CALL_FAILED_IF_ERROR(DOM_ExtensionUIBadge::Make(this_object, item->m_badge, value.value.object, item, return_value, origining_runtime)); item->m_id = g_gadget_manager->NextExtensionUnique(); if (item->m_favicon) { int result = DOM_ExtensionUIItem::LoadImage(extension_support->GetGadget(), item, FALSE, return_value, origining_runtime); if (result != ES_EXCEPTION) { if ((result & ES_SUSPEND) == ES_SUSPEND) item->m_is_loading_image = TRUE; return result; } else { OP_ASSERT(return_value->type == VALUE_OBJECT); CALL_FAILED_IF_ERROR(DOM_ExtensionUIItem::ReportImageLoadFailure(item->m_favicon, item->GetEnvironment()->GetFramesDocument()->GetWindow()->Id(), return_value, origining_runtime)); } } DOM_Object::DOMSetObject(return_value, item); return ES_VALUE; } /* static */ int DOM_ExtensionContext::addItem(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime) { DOM_THIS_OBJECT(context, DOM_TYPE_EXTENSION_CONTEXT, DOM_ExtensionContext); if (argc < 0) { context->m_blocked_thread = NULL; OpExtensionUIListener::ItemAddedStatus call_status = context->m_add_status; context->m_add_status = OpExtensionUIListener::ItemAddedUnknown; return DOM_ExtensionUIItem::HandleItemAddedStatus(this_object, call_status, return_value); } DOM_CHECK_ARGUMENTS("o"); DOM_ARGUMENT_OBJECT(new_item, 0, DOM_TYPE_EXTENSION_UIITEM, DOM_ExtensionUIItem); if (new_item->m_is_attached) return ES_FAILED; if (context->m_max_items >= 0 && static_cast<int>(context->m_items.Cardinal()) >= context->m_max_items) return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); new_item->Into(&context->m_items); new_item->m_parent_id = context->GetId(); new_item->m_is_attached = TRUE; CALL_INVALID_IF_ERROR(new_item->NotifyItemUpdate(origining_runtime, context)); return (ES_SUSPEND | ES_RESTART); } /* static */ int DOM_ExtensionContext::removeItem(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime) { DOM_THIS_OBJECT(context, DOM_TYPE_EXTENSION_CONTEXT, DOM_ExtensionContext); if (argc < 0) { context->m_blocked_thread = NULL; context->GetThreadListener()->Remove(); OpExtensionUIListener::ItemRemovedStatus call_status = context->m_remove_status; context->m_remove_status = OpExtensionUIListener::ItemRemovedUnknown; return DOM_ExtensionUIItem::HandleItemRemovedStatus(this_object, call_status, return_value); } else if (argc == 0) return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); DOM_ExtensionUIItem *item_to_remove = NULL; if (argv[0].type == VALUE_NUMBER) { DOM_CHECK_ARGUMENTS("n"); double d = argv[0].value.number; if (d < 0 && d >= UINT_MAX) return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); unsigned int id = static_cast<unsigned int>(d); for (DOM_ExtensionUIItem *i = context->m_items.First(); i; i = i->Suc()) if (i->GetId() == id) { i->Out(); item_to_remove = i; break; } } else if (argv[0].type == VALUE_OBJECT) { DOM_ARGUMENT_OBJECT(uiitem, 0, DOM_TYPE_EXTENSION_UIITEM, DOM_ExtensionUIItem); if (!uiitem->m_is_attached) return ES_FAILED; for (DOM_ExtensionUIItem *i = context->m_items.First(); i; i = i->Suc()) if (i == uiitem) { i->Out(); item_to_remove = i; break; } } else return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); if (item_to_remove) { /* Async call; block current thread.. */ ES_Thread *blocking_thread = origining_runtime->GetESScheduler()->GetCurrentThread(); if (blocking_thread) { /* Record the parent connection for the duration of an async call. */ item_to_remove->m_parent = context; blocking_thread->AddListener(context->GetThreadListener()); blocking_thread->Block(); } context->m_blocked_thread = blocking_thread; context->m_active_extension_id = item_to_remove->m_id; OP_STATUS status = item_to_remove->NotifyItemRemove(); if (OpStatus::IsError(status)) { item_to_remove->m_parent = NULL; /* ..but unblock if notification wasn't communicated OK. */ if (blocking_thread) { OpStatus::Ignore(blocking_thread->Unblock()); context->GetThreadListener()->Remove(); } CALL_INVALID_IF_ERROR(status); } else { item_to_remove->m_is_attached = FALSE; return (ES_SUSPEND | ES_RESTART); } } return ES_FAILED; } /* virtual */ ES_GetState DOM_ExtensionContext::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { switch (property_name) { case OP_ATOM_length: DOMSetNumber(value, m_items.Cardinal()); return GET_SUCCESS; default: return DOM_Object::GetName(property_name, value, origining_runtime); } } /* virtual */ ES_GetState DOM_ExtensionContext::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime) { BOOL allowed = OriginCheck(origining_runtime); DOM_ExtensionUIItem *it = m_items.First(); while (it && property_index-- > 0) it = it->Suc(); if (it) if (!allowed) return GET_SECURITY_VIOLATION; else { DOMSetObject(value, it); return GET_SUCCESS; } else return GET_FAILED; } /* virtual */ ES_PutState DOM_ExtensionContext::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime) { switch (property_name) { case OP_ATOM_length: return PUT_READ_ONLY; default: return DOM_Object::PutName(property_name, value, origining_runtime); } } /* virtual */ ES_PutState DOM_ExtensionContext::PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime) { return PUT_FAILED; } int DOM_ExtensionContext::item(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(context, DOM_TYPE_EXTENSION_CONTEXT, DOM_ExtensionContext); DOM_CHECK_ARGUMENTS("n"); double index = argv[0].value.number; if (index < 0.0 || index >= static_cast<double>(context->m_items.Cardinal())) DOM_CALL_DOMEXCEPTION(INDEX_SIZE_ERR); unsigned idx = static_cast<unsigned>(argv[0].value.number); DOM_ExtensionUIItem *it = context->m_items.First(); while (it && idx-- > 0) it = it->Suc(); DOMSetObject(return_value, it); return ES_VALUE; } /* virtual */ ES_GetState DOM_ExtensionContext::GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime) { count = m_items.Cardinal(); return GET_SUCCESS; } /* virtual */ void DOM_ExtensionContext::GCTrace() { for (DOM_ExtensionUIItem *i = m_items.First(); i; i = i->Suc()) GCMark(i); GCMark(m_parent); } /* virtual */ DOM_ExtensionContext::~DOM_ExtensionContext() { OP_NEW_DBG("DOM_ExtensionContext::~DOM_ExtensionContext()", "extensions.dom"); OP_DBG(("this: %p", this)); OP_ASSERT(m_items.Empty()); m_notifications.Out(); m_thread_listener.Out(); } /* virtual */ void DOM_ExtensionContext::BeforeDestroy() { OP_NEW_DBG("DOM_ExtensionContext::BeforeDestroy()", "extensions.dom"); OP_DBG(("this: %p", this)); while (DOM_ExtensionUIItem *it = m_items.First()) { it->Out(); OpStatus::Ignore(it->NotifyItemRemove(FALSE)); } } /* virtual */OP_STATUS DOM_ExtensionContext::ThreadListener::Signal(ES_Thread *thread, ES_ThreadSignal signal) { m_owner->m_blocked_thread = NULL; ES_ThreadListener::Remove(); return OpStatus::OK; } #include "modules/dom/src/domglobaldata.h" DOM_FUNCTIONS_START(DOM_ExtensionContext) DOM_FUNCTIONS_FUNCTION(DOM_ExtensionContext, DOM_ExtensionContext::createItem, "createItem", "o-") DOM_FUNCTIONS_FUNCTION(DOM_ExtensionContext, DOM_ExtensionContext::addItem, "addItem", "o-") DOM_FUNCTIONS_FUNCTION(DOM_ExtensionContext, DOM_ExtensionContext::removeItem, "removeItem", "") DOM_FUNCTIONS_FUNCTION(DOM_ExtensionContext, DOM_ExtensionContext::item, "item", "n-") DOM_FUNCTIONS_END(DOM_ExtensionContext) #endif // EXTENSION_SUPPORT
#include "PlikTekstowy.h" bool PlikTekstowy::czyPlikJestPusty() { bool pusty = true; fstream plikTekstowy; plikTekstowy.open(pobierzNazwePliku().c_str(), ios::app); if (plikTekstowy.good() == true) { plikTekstowy.seekg(0, ios::end); if (plikTekstowy.tellg() != 0) pusty = false; } plikTekstowy.close(); return pusty; }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "WalletGreen.h" #include <algorithm> #include <ctime> #include <cassert> #include <numeric> #include <random> #include <set> #include <tuple> #include <utility> #include <fstream> #include <System/EventLock.h> #include <System/RemoteContext.h> #include "ITransaction.h" #include "Common/ScopeExit.h" #include "Common/ShuffleGenerator.h" #include "Common/StdInputStream.h" #include "Common/StdOutputStream.h" #include "Common/StringTools.h" #include "CryptoNoteCore/Account.h" #include "CryptoNoteCore/Currency.h" #include "CryptoNoteCore/CryptoNoteFormatUtils.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "CryptoNoteCore/TransactionApi.h" #include <CryptoNoteCore/TransactionExtra.h> #include "crypto/crypto.h" #include "Transfers/TransfersContainer.h" #include "WalletSerializationV1.h" #include "WalletSerializationV2.h" #include "WalletErrors.h" #include "WalletUtils.h" using namespace common; using namespace crypto; using namespace cn; using namespace logging; namespace { std::vector<uint64_t> split(uint64_t amount, uint64_t dustThreshold) { std::vector<uint64_t> amounts; decompose_amount_into_digits( amount, dustThreshold, [&](uint64_t chunk) { amounts.push_back(chunk); }, [&](uint64_t dust) { amounts.push_back(dust); }); return amounts; } uint64_t calculateDepositsAmount( const std::vector<cn::TransactionOutputInformation> &transfers, const cn::Currency &currency, const std::vector<uint32_t> heights) { int index = 0; return std::accumulate(transfers.begin(), transfers.end(), static_cast<uint64_t>(0), [&currency, &index, heights](uint64_t sum, const cn::TransactionOutputInformation &deposit) { return sum + deposit.amount + currency.calculateInterest(deposit.amount, deposit.term, heights[index++]); }); } void asyncRequestCompletion(platform_system::Event &requestFinished) { requestFinished.set(); } void parseAddressString( const std::string &string, const cn::Currency &currency, cn::AccountPublicAddress &address) { if (!currency.parseAccountAddressString(string, address)) { throw std::system_error(make_error_code(cn::error::BAD_ADDRESS)); } } uint64_t countNeededMoney( const std::vector<cn::WalletTransfer> &destinations, uint64_t fee) { uint64_t neededMoney = 0; for (const auto &transfer : destinations) { if (transfer.amount == 0) { throw std::system_error(make_error_code(cn::error::ZERO_DESTINATION)); } else if (transfer.amount < 0) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } //to supress warning uint64_t uamount = static_cast<uint64_t>(transfer.amount); neededMoney += uamount; if (neededMoney < uamount) { throw std::system_error(make_error_code(cn::error::SUM_OVERFLOW)); } } neededMoney += fee; if (neededMoney < fee) { throw std::system_error(make_error_code(cn::error::SUM_OVERFLOW)); } return neededMoney; } void checkIfEnoughMixins(std::vector<cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount> &mixinResult, uint64_t mixIn) { auto notEnoughIt = std::find_if(mixinResult.begin(), mixinResult.end(), [mixIn](const cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount &ofa) { return ofa.outs.size() < mixIn; }); if (mixIn == 0 && mixinResult.empty()) { throw std::system_error(make_error_code(cn::error::MIXIN_COUNT_TOO_BIG)); } if (notEnoughIt != mixinResult.end()) { throw std::system_error(make_error_code(cn::error::MIXIN_COUNT_TOO_BIG)); } } cn::WalletEvent makeTransactionUpdatedEvent(size_t id) { cn::WalletEvent event; event.type = cn::WalletEventType::TRANSACTION_UPDATED; event.transactionUpdated.transactionIndex = id; return event; } cn::WalletEvent makeTransactionCreatedEvent(size_t id) { cn::WalletEvent event; event.type = cn::WalletEventType::TRANSACTION_CREATED; event.transactionCreated.transactionIndex = id; return event; } cn::WalletEvent makeMoneyUnlockedEvent() { cn::WalletEvent event; event.type = cn::WalletEventType::BALANCE_UNLOCKED; return event; } cn::WalletEvent makeSyncProgressUpdatedEvent(uint32_t current, uint32_t total) { cn::WalletEvent event; event.type = cn::WalletEventType::SYNC_PROGRESS_UPDATED; event.synchronizationProgressUpdated.processedBlockCount = current; event.synchronizationProgressUpdated.totalBlockCount = total; return event; } cn::WalletEvent makeSyncCompletedEvent() { cn::WalletEvent event; event.type = cn::WalletEventType::SYNC_COMPLETED; return event; } size_t getTransactionSize(const ITransactionReader &transaction) { return transaction.getTransactionData().size(); } std::vector<WalletTransfer> convertOrdersToTransfers(const std::vector<WalletOrder> &orders) { std::vector<WalletTransfer> transfers; transfers.reserve(orders.size()); for (const auto &order : orders) { WalletTransfer transfer; if (order.amount > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { throw std::system_error(make_error_code(cn::error::WRONG_AMOUNT), "Order amount must not exceed " + std::to_string(std::numeric_limits<decltype(transfer.amount)>::max())); } transfer.type = WalletTransferType::USUAL; transfer.address = order.address; transfer.amount = static_cast<int64_t>(order.amount); transfers.emplace_back(std::move(transfer)); } return transfers; } uint64_t calculateDonationAmount(uint64_t freeAmount, uint64_t donationThreshold, uint64_t dustThreshold) { std::vector<uint64_t> decomposedAmounts; decomposeAmount(freeAmount, dustThreshold, decomposedAmounts); std::sort(decomposedAmounts.begin(), decomposedAmounts.end(), std::greater<uint64_t>()); uint64_t donationAmount = 0; for (auto amount : decomposedAmounts) { if (amount > donationThreshold - donationAmount) { continue; } donationAmount += amount; } assert(donationAmount <= freeAmount); return donationAmount; } uint64_t pushDonationTransferIfPossible(const DonationSettings &donation, uint64_t freeAmount, uint64_t dustThreshold, std::vector<WalletTransfer> &destinations) { uint64_t donationAmount = 0; if (!donation.address.empty() && donation.threshold != 0) { if (donation.threshold > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { throw std::system_error(make_error_code(error::WRONG_AMOUNT), "Donation threshold must not exceed " + std::to_string(std::numeric_limits<int64_t>::max())); } donationAmount = calculateDonationAmount(freeAmount, donation.threshold, dustThreshold); if (donationAmount != 0) { destinations.emplace_back(WalletTransfer{WalletTransferType::DONATION, donation.address, static_cast<int64_t>(donationAmount)}); } } return donationAmount; } cn::AccountPublicAddress parseAccountAddressString( const std::string &addressString, const cn::Currency &currency) { cn::AccountPublicAddress address; if (!currency.parseAccountAddressString(addressString, address)) { throw std::system_error(make_error_code(cn::error::BAD_ADDRESS)); } return address; } } // namespace namespace cn { WalletGreen::WalletGreen(platform_system::Dispatcher &dispatcher, const Currency &currency, INode &node, logging::ILogger &logger, uint32_t transactionSoftLockTime) : m_dispatcher(dispatcher), m_currency(currency), m_node(node), m_logger(logger, "WalletGreen"), m_stopped(false), m_blockchainSynchronizerStarted(false), m_blockchainSynchronizer(node, currency.genesisBlockHash()), m_synchronizer(currency, logger, m_blockchainSynchronizer, node), m_eventOccurred(m_dispatcher), m_readyEvent(m_dispatcher), m_state(WalletState::NOT_INITIALIZED), m_actualBalance(0), m_pendingBalance(0), m_lockedDepositBalance(0), m_unlockedDepositBalance(0), m_transactionSoftLockTime(transactionSoftLockTime) { m_upperTransactionSizeLimit = m_currency.transactionMaxSize(); m_readyEvent.set(); } WalletGreen::~WalletGreen() { if (m_state == WalletState::INITIALIZED) { doShutdown(); } m_dispatcher.yield(); //let remote spawns finish } void WalletGreen::initialize( const std::string &path, const std::string &password) { crypto::PublicKey viewPublicKey; crypto::SecretKey viewSecretKey; crypto::generate_keys(viewPublicKey, viewSecretKey); initWithKeys(path, password, viewPublicKey, viewSecretKey); m_logger(DEBUGGING, BRIGHT_WHITE) << "New container initialized, public view key " << common::podToHex(viewPublicKey); } void WalletGreen::withdrawDeposit( DepositId depositId, std::string &transactionHash) { throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); /* Check for the existance of the deposit */ if (m_deposits.size() <= depositId) { throw std::system_error(make_error_code(cn::error::DEPOSIT_DOESNOT_EXIST)); } /* Get the details of the deposit, and the address */ Deposit deposit = getDeposit(depositId); WalletTransfer firstTransfer = getTransactionTransfer(deposit.creatingTransactionId, 0); std::string address = firstTransfer.address; uint64_t blockCount = getBlockCount(); /* Is the deposit unlocked */ if (deposit.unlockHeight > blockCount) { throw std::system_error(make_error_code(cn::error::DEPOSIT_LOCKED)); } /* Create the transaction */ std::unique_ptr<ITransaction> transaction = createTransaction(); std::vector<TransactionOutputInformation> selectedTransfers; const auto &wallet = getWalletRecord(address); ITransfersContainer *container = wallet.container; AccountKeys account = makeAccountKeys(wallet); ITransfersContainer::TransferState state; TransactionOutputInformation transfer; uint64_t foundMoney = 0; foundMoney += deposit.amount + deposit.interest; m_logger(DEBUGGING, WHITE) << "found money " << foundMoney; container->getTransfer(deposit.transactionHash, deposit.outputInTransaction, transfer, state); if (state != ITransfersContainer::TransferState::TransferAvailable) { throw std::system_error(make_error_code(cn::error::DEPOSIT_LOCKED)); } selectedTransfers.push_back(std::move(transfer)); m_logger(DEBUGGING, BRIGHT_WHITE) << "Withdraw deposit, id " << depositId << " found transfer for " << transfer.amount << " with a global output index of " << transfer.globalOutputIndex; std::vector<MultisignatureInput> inputs = prepareMultisignatureInputs(selectedTransfers); for (const auto &input : inputs) { transaction->addInput(input); } std::vector<uint64_t> outputAmounts = split(foundMoney - 10, parameters::DEFAULT_DUST_THRESHOLD); for (auto amount : outputAmounts) { transaction->addOutput(amount, account.address); } transaction->setUnlockTime(0); crypto::SecretKey transactionSK; transaction->getTransactionSecretKey(transactionSK); /* Add the transaction extra */ std::vector<WalletMessage> messages; crypto::PublicKey publicKey = transaction->getTransactionPublicKey(); cn::KeyPair kp = {publicKey, transactionSK}; for (size_t i = 0; i < messages.size(); ++i) { cn::AccountPublicAddress addressBin; if (!m_currency.parseAccountAddressString(messages[i].address, addressBin)) continue; cn::tx_extra_message tag; if (!tag.encrypt(i, messages[i].message, &addressBin, kp)) continue; BinaryArray ba; toBinaryArray(tag, ba); ba.insert(ba.begin(), TX_EXTRA_MESSAGE_TAG); transaction->appendExtra(ba); } assert(inputs.size() == selectedTransfers.size()); for (size_t i = 0; i < inputs.size(); ++i) { transaction->signInputMultisignature(i, selectedTransfers[i].transactionPublicKey, selectedTransfers[i].outputInTransaction, account); } transactionHash = common::podToHex(transaction->getTransactionHash()); size_t id = validateSaveAndSendTransaction(*transaction, {}, false, true); } crypto::SecretKey WalletGreen::getTransactionDeterministicSecretKey(crypto::Hash &transactionHash) const { throwIfNotInitialized(); throwIfStopped(); crypto::SecretKey txKey = cn::NULL_SECRET_KEY; auto getTransactionCompleted = std::promise<std::error_code>(); auto getTransactionWaitFuture = getTransactionCompleted.get_future(); cn::Transaction tx; m_node.getTransaction(std::move(transactionHash), std::ref(tx), [&getTransactionCompleted](std::error_code ec) { auto detachedPromise = std::move(getTransactionCompleted); detachedPromise.set_value(ec); }); std::error_code ec = getTransactionWaitFuture.get(); if (ec) { m_logger(ERROR) << "Failed to get tx: " << ec << ", " << ec.message(); return cn::NULL_SECRET_KEY; } crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(tx.extra); KeyPair deterministicTxKeys; bool ok = generateDeterministicTransactionKeys(tx, m_viewSecretKey, deterministicTxKeys) && deterministicTxKeys.publicKey == txPubKey; return ok ? deterministicTxKeys.secretKey : cn::NULL_SECRET_KEY; return txKey; } std::vector<MultisignatureInput> WalletGreen::prepareMultisignatureInputs(const std::vector<TransactionOutputInformation> &selectedTransfers) { std::vector<MultisignatureInput> inputs; inputs.reserve(selectedTransfers.size()); for (const auto &output : selectedTransfers) { assert(output.type == transaction_types::OutputType::Multisignature); assert(output.requiredSignatures == 1); //Other types are currently unsupported MultisignatureInput input; input.amount = output.amount; input.signatureCount = output.requiredSignatures; input.outputIndex = output.globalOutputIndex; input.term = output.term; inputs.emplace_back(std::move(input)); } return inputs; } void WalletGreen::createDeposit( uint64_t amount, uint64_t term, std::string sourceAddress, std::string destinationAddress, std::string &transactionHash) { throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); /* If a source address is not specified, use the primary (first) wallet address for the creation of the deposit */ if (sourceAddress.empty()) { sourceAddress = getAddress(0); } if (destinationAddress.empty()) { destinationAddress = sourceAddress; } /* Ensure that the address is valid and a part of this container */ validateSourceAddresses({sourceAddress}); cn::AccountPublicAddress sourceAddr = parseAddress(sourceAddress); cn::AccountPublicAddress destAddr = parseAddress(destinationAddress); /* Create the transaction */ std::unique_ptr<ITransaction> transaction = createTransaction(); /* Select the wallet - If no source address was specified then it will pick funds from anywhere and the change will go to the primary address of the wallet container */ std::vector<WalletOuts> wallets; wallets = pickWallets({sourceAddress}); /* Select the transfers */ uint64_t fee = 1000; uint64_t neededMoney = amount + fee; std::vector<OutputToTransfer> selectedTransfers; uint64_t foundMoney = selectTransfers(neededMoney, m_currency.defaultDustThreshold(), std::move(wallets), selectedTransfers); /* Do we have enough funds */ if (foundMoney < neededMoney) { throw std::system_error(make_error_code(error::WRONG_AMOUNT)); } /* Now we add the outputs to the transaction, starting with the deposits output which includes the term, and then after that the change outputs */ /* Add the deposit outputs to the transaction */ auto depositIndex = transaction->addOutput( neededMoney - fee, {destAddr}, 1, term); /* Let's add the change outputs to the transaction */ std::vector<uint64_t> amounts; /* Breakdown the change into specific amounts */ decompose_amount_into_digits( foundMoney - neededMoney, m_currency.defaultDustThreshold(), [&](uint64_t chunk) { amounts.push_back(chunk); }, [&](uint64_t dust) { amounts.push_back(dust); }); std::vector<uint64_t> decomposedChange = amounts; /* Now pair each of those amounts to the change address which in the case of a deposit is the source address */ typedef std::pair<const AccountPublicAddress *, uint64_t> AmountToAddress; std::vector<AmountToAddress> amountsToAddresses; for (const auto &output : decomposedChange) { amountsToAddresses.emplace_back(AmountToAddress{&sourceAddr, output}); } /* For the sake of privacy, we shuffle the output order randomly */ std::shuffle(amountsToAddresses.begin(), amountsToAddresses.end(), std::default_random_engine{crypto::rand<std::default_random_engine::result_type>()}); std::sort(amountsToAddresses.begin(), amountsToAddresses.end(), [](const AmountToAddress &left, const AmountToAddress &right) { return left.second < right.second; }); /* Add the change outputs to the transaction */ try { for (const auto &amountToAddress : amountsToAddresses) { transaction->addOutput(amountToAddress.second, *amountToAddress.first); } } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } /* Now add the other components of the transaction such as the transaction secret key, unlocktime since this is a deposit, we don't need to add messages or added extras beyond the transaction publick key */ crypto::SecretKey transactionSK; transaction->getTransactionSecretKey(transactionSK); transaction->setUnlockTime(0); /* Add the transaction extra */ std::vector<WalletMessage> messages; crypto::PublicKey publicKey = transaction->getTransactionPublicKey(); cn::KeyPair kp = {publicKey, transactionSK}; for (size_t i = 0; i < messages.size(); ++i) { cn::AccountPublicAddress addressBin; if (!m_currency.parseAccountAddressString(messages[i].address, addressBin)) continue; cn::tx_extra_message tag; if (!tag.encrypt(i, messages[i].message, &addressBin, kp)) continue; BinaryArray ba; toBinaryArray(tag, ba); ba.insert(ba.begin(), TX_EXTRA_MESSAGE_TAG); transaction->appendExtra(ba); } /* Prepare the inputs */ /* Get additional inputs for the mixin */ typedef cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount; std::vector<outs_for_amount> mixinResult; requestMixinOuts(selectedTransfers, cn::parameters::MINIMUM_MIXIN, mixinResult); std::vector<InputInfo> keysInfo; prepareInputs(selectedTransfers, mixinResult, cn::parameters::MINIMUM_MIXIN, keysInfo); /* Add the inputs to the transaction */ std::vector<KeyPair> ephKeys; for (auto &input : keysInfo) { transaction->addInput(makeAccountKeys(*input.walletRecord), input.keyInfo, input.ephKeys); } /* Now sign the inputs so we can proceed with the transaction */ size_t i = 0; for (auto &input : keysInfo) { transaction->signInputKey(i++, input.keyInfo, input.ephKeys); } /* Return the transaction hash */ transactionHash = common::podToHex(transaction->getTransactionHash()); size_t id = validateSaveAndSendTransaction(*transaction, {}, false, true); } void WalletGreen::validateOrders(const std::vector<WalletOrder> &orders) const { for (const auto &order : orders) { if (!cn::validateAddress(order.address, m_currency)) { throw std::system_error(make_error_code(cn::error::BAD_ADDRESS)); } if (order.amount >= static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { std::string message = "Order amount must not exceed " + m_currency.formatAmount(std::numeric_limits<int64_t>::max()); throw std::system_error(make_error_code(cn::error::WRONG_AMOUNT), message); } } } void WalletGreen::decryptKeyPair(const EncryptedWalletRecord &cipher, PublicKey &publicKey, SecretKey &secretKey, uint64_t &creationTimestamp, const crypto::chacha8_key &key) { std::array<char, sizeof(cipher.data)> buffer; chacha8(cipher.data, sizeof(cipher.data), key, cipher.iv, buffer.data()); MemoryInputStream stream(buffer.data(), buffer.size()); BinaryInputStreamSerializer serializer(stream); serializer(publicKey, "publicKey"); serializer(secretKey, "secretKey"); serializer.binary(&creationTimestamp, sizeof(uint64_t), "creationTimestamp"); } void WalletGreen::decryptKeyPair(const EncryptedWalletRecord &cipher, PublicKey &publicKey, SecretKey &secretKey, uint64_t &creationTimestamp) const { decryptKeyPair(cipher, publicKey, secretKey, creationTimestamp, m_key); } EncryptedWalletRecord WalletGreen::encryptKeyPair(const PublicKey &publicKey, const SecretKey &secretKey, uint64_t creationTimestamp, const crypto::chacha8_key &key, const crypto::chacha8_iv &iv) { EncryptedWalletRecord result; std::string serializedKeys; StringOutputStream outputStream(serializedKeys); BinaryOutputStreamSerializer serializer(outputStream); serializer(const_cast<PublicKey &>(publicKey), "publicKey"); serializer(const_cast<SecretKey &>(secretKey), "secretKey"); serializer.binary(&creationTimestamp, sizeof(uint64_t), "creationTimestamp"); assert(serializedKeys.size() == sizeof(result.data)); result.iv = iv; chacha8(serializedKeys.data(), serializedKeys.size(), key, result.iv, reinterpret_cast<char *>(result.data)); return result; } crypto::chacha8_iv WalletGreen::getNextIv() const { const auto *prefix = reinterpret_cast<const ContainerStoragePrefix *>(m_containerStorage.prefix()); return prefix->nextIv; } EncryptedWalletRecord WalletGreen::encryptKeyPair(const PublicKey &publicKey, const SecretKey &secretKey, uint64_t creationTimestamp) const { return encryptKeyPair(publicKey, secretKey, creationTimestamp, m_key, getNextIv()); } void WalletGreen::loadSpendKeys() { bool isTrackingMode; for (size_t i = 0; i < m_containerStorage.size(); ++i) { WalletRecord wallet; uint64_t creationTimestamp; decryptKeyPair(m_containerStorage[i], wallet.spendPublicKey, wallet.spendSecretKey, creationTimestamp); wallet.creationTimestamp = creationTimestamp; if (i == 0) { isTrackingMode = wallet.spendSecretKey == NULL_SECRET_KEY; } else if ((isTrackingMode && wallet.spendSecretKey != NULL_SECRET_KEY) || (!isTrackingMode && wallet.spendSecretKey == NULL_SECRET_KEY)) { throw std::system_error(make_error_code(error::BAD_ADDRESS), "All addresses must be whether tracking or not"); } if (wallet.spendSecretKey != NULL_SECRET_KEY) { throwIfKeysMissmatch(wallet.spendSecretKey, wallet.spendPublicKey, "Restored spend public key doesn't correspond to secret key"); } else { if (!crypto::check_key(wallet.spendPublicKey)) { throw std::system_error(make_error_code(error::WRONG_PASSWORD), "Public spend key is incorrect"); } } wallet.actualBalance = 0; wallet.pendingBalance = 0; wallet.lockedDepositBalance = 0; wallet.unlockedDepositBalance = 0; wallet.container = reinterpret_cast<cn::ITransfersContainer *>(i); //dirty hack. container field must be unique m_walletsContainer.emplace_back(std::move(wallet)); } } void WalletGreen::validateAddresses(const std::vector<std::string> &addresses) const { for (const auto &address : addresses) { if (!cn::validateAddress(address, m_currency)) { throw std::system_error(make_error_code(cn::error::BAD_ADDRESS)); } } } void WalletGreen::initializeWithViewKey(const std::string &path, const std::string &password, const crypto::SecretKey &viewSecretKey) { crypto::PublicKey viewPublicKey; if (!crypto::secret_key_to_public_key(viewSecretKey, viewPublicKey)) { m_logger(ERROR, BRIGHT_RED) << "initializeWithViewKey(" << common::podToHex(viewSecretKey) << ") Failed to convert secret key to public key"; throw std::system_error(make_error_code(cn::error::KEY_GENERATION_ERROR)); } initWithKeys(path, password, viewPublicKey, viewSecretKey); m_logger(INFO, BRIGHT_WHITE) << "Container initialized with view secret key, public view key " << common::podToHex(viewPublicKey); } void WalletGreen::shutdown() { throwIfNotInitialized(); doShutdown(); m_dispatcher.yield(); //let remote spawns finish } void WalletGreen::initBlockchain(const crypto::PublicKey &viewPublicKey) { std::vector<crypto::Hash> blockchain = m_synchronizer.getViewKeyKnownBlocks(m_viewPublicKey); m_blockchain.insert(m_blockchain.end(), blockchain.begin(), blockchain.end()); } void WalletGreen::deleteOrphanTransactions(const std::unordered_set<crypto::PublicKey> &deletedKeys) { for (auto spendPublicKey : deletedKeys) { AccountPublicAddress deletedAccountAddress; deletedAccountAddress.spendPublicKey = spendPublicKey; deletedAccountAddress.viewPublicKey = m_viewPublicKey; auto deletedAddressString = m_currency.accountAddressAsString(deletedAccountAddress); std::vector<size_t> deletedTransactions; std::vector<size_t> updatedTransactions = deleteTransfersForAddress(deletedAddressString, deletedTransactions); deleteFromUncommitedTransactions(deletedTransactions); } } void WalletGreen::saveWalletCache(ContainerStorage &storage, const crypto::chacha8_key &key, WalletSaveLevel saveLevel, const std::string &extra) { m_logger(INFO) << "Saving cache..."; WalletTransactions transactions; WalletTransfers transfers; if (saveLevel == WalletSaveLevel::SAVE_KEYS_AND_TRANSACTIONS) { filterOutTransactions(transactions, transfers, [](const WalletTransaction &tx) { return tx.state == WalletTransactionState::CREATED || tx.state == WalletTransactionState::DELETED; }); for (auto it = transactions.begin(); it != transactions.end(); ++it) { transactions.modify(it, [](WalletTransaction &tx) { tx.state = WalletTransactionState::CANCELLED; tx.blockHeight = WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; }); } } else if (saveLevel == WalletSaveLevel::SAVE_ALL) { filterOutTransactions(transactions, transfers, [](const WalletTransaction &tx) { return tx.state == WalletTransactionState::DELETED; }); } std::string containerData; common::StringOutputStream containerStream(containerData); WalletSerializerV2 s( *this, m_viewPublicKey, m_viewSecretKey, m_actualBalance, m_pendingBalance, m_lockedDepositBalance, m_unlockedDepositBalance, m_walletsContainer, m_synchronizer, m_unlockTransactionsJob, transactions, transfers, m_deposits, m_uncommitedTransactions, const_cast<std::string &>(extra), m_transactionSoftLockTime); s.save(containerStream, saveLevel); encryptAndSaveContainerData(storage, key, containerData.data(), containerData.size()); storage.flush(); m_extra = extra; m_logger(INFO) << "Container saving finished"; } void WalletGreen::doShutdown() { if (m_walletsContainer.size() != 0) { m_synchronizer.unsubscribeConsumerNotifications(m_viewPublicKey, this); } stopBlockchainSynchronizer(); m_blockchainSynchronizer.removeObserver(this); m_containerStorage.close(); m_walletsContainer.clear(); clearCaches(true, true); std::queue<WalletEvent> noEvents; std::swap(m_events, noEvents); m_state = WalletState::NOT_INITIALIZED; } void WalletGreen::initTransactionPool() { std::unordered_set<crypto::Hash> uncommitedTransactionsSet; std::transform(m_uncommitedTransactions.begin(), m_uncommitedTransactions.end(), std::inserter(uncommitedTransactionsSet, uncommitedTransactionsSet.end()), [](const UncommitedTransactions::value_type &pair) { return getObjectHash(pair.second); }); m_synchronizer.initTransactionPool(uncommitedTransactionsSet); } void WalletGreen::initWithKeys(const std::string &path, const std::string &password, const crypto::PublicKey &viewPublicKey, const crypto::SecretKey &viewSecretKey) { if (m_state != WalletState::NOT_INITIALIZED) { m_logger(ERROR, BRIGHT_RED) << "Failed to initialize with keys: already initialized."; throw std::system_error(make_error_code(cn::error::ALREADY_INITIALIZED)); } throwIfStopped(); ContainerStorage newStorage(path, common::FileMappedVectorOpenMode::CREATE, sizeof(ContainerStoragePrefix)); ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(newStorage.prefix()); prefix->version = static_cast<uint8_t>(WalletSerializerV2::SERIALIZATION_VERSION); prefix->nextIv = crypto::rand<crypto::chacha8_iv>(); crypto::cn_context cnContext; crypto::generate_chacha8_key(cnContext, password, m_key); uint64_t creationTimestamp = time(nullptr); prefix->encryptedViewKeys = encryptKeyPair(viewPublicKey, viewSecretKey, creationTimestamp, m_key, prefix->nextIv); newStorage.flush(); m_containerStorage.swap(newStorage); incNextIv(); m_viewPublicKey = viewPublicKey; m_viewSecretKey = viewSecretKey; m_password = password; m_path = path; m_logger = logging::LoggerRef(m_logger.getLogger(), "WalletGreen/" + podToHex(m_viewPublicKey).substr(0, 5)); assert(m_blockchain.empty()); m_blockchain.push_back(m_currency.genesisBlockHash()); m_blockchainSynchronizer.addObserver(this); m_state = WalletState::INITIALIZED; } void WalletGreen::save(WalletSaveLevel saveLevel, const std::string &extra) { m_logger(INFO, BRIGHT_WHITE) << "Saving container..."; throwIfNotInitialized(); throwIfStopped(); stopBlockchainSynchronizer(); try { saveWalletCache(m_containerStorage, m_key, saveLevel, extra); } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to save container: " << e.what(); startBlockchainSynchronizer(); throw; } startBlockchainSynchronizer(); m_logger(INFO, BRIGHT_WHITE) << "Container saved"; } void WalletGreen::copyContainerStorageKeys(ContainerStorage &src, const chacha8_key &srcKey, ContainerStorage &dst, const chacha8_key &dstKey) { dst.reserve(src.size()); dst.setAutoFlush(false); tools::ScopeExit exitHandler([&dst] { dst.setAutoFlush(true); dst.flush(); }); size_t counter = 0; for (auto &encryptedSpendKeys : src) { crypto::PublicKey publicKey; crypto::SecretKey secretKey; uint64_t creationTimestamp; decryptKeyPair(encryptedSpendKeys, publicKey, secretKey, creationTimestamp, srcKey); // push_back() can resize container, and dstPrefix address can be changed, so it is requested for each key pair ContainerStoragePrefix *dstPrefix = reinterpret_cast<ContainerStoragePrefix *>(dst.prefix()); crypto::chacha8_iv keyPairIv = dstPrefix->nextIv; incIv(dstPrefix->nextIv); dst.push_back(encryptKeyPair(publicKey, secretKey, creationTimestamp, dstKey, keyPairIv)); } } void WalletGreen::copyContainerStoragePrefix(ContainerStorage &src, const chacha8_key &srcKey, ContainerStorage &dst, const chacha8_key &dstKey) { ContainerStoragePrefix *srcPrefix = reinterpret_cast<ContainerStoragePrefix *>(src.prefix()); ContainerStoragePrefix *dstPrefix = reinterpret_cast<ContainerStoragePrefix *>(dst.prefix()); dstPrefix->version = srcPrefix->version; dstPrefix->nextIv = crypto::randomChachaIV(); crypto::PublicKey publicKey; crypto::SecretKey secretKey; uint64_t creationTimestamp; decryptKeyPair(srcPrefix->encryptedViewKeys, publicKey, secretKey, creationTimestamp, srcKey); dstPrefix->encryptedViewKeys = encryptKeyPair(publicKey, secretKey, creationTimestamp, dstKey, dstPrefix->nextIv); incIv(dstPrefix->nextIv); } void WalletGreen::exportWallet(const std::string &path, WalletSaveLevel saveLevel, bool encrypt, const std::string &extra) { m_logger(INFO, BRIGHT_WHITE) << "Exporting container..."; throwIfNotInitialized(); throwIfStopped(); stopBlockchainSynchronizer(); try { bool storageCreated = false; tools::ScopeExit failExitHandler([path, &storageCreated] { // Don't delete file if it has existed if (storageCreated) { boost::system::error_code ignore; boost::filesystem::remove(path, ignore); } }); ContainerStorage newStorage(path, FileMappedVectorOpenMode::CREATE, m_containerStorage.prefixSize()); storageCreated = true; chacha8_key newStorageKey; if (encrypt) { newStorageKey = m_key; } else { cn_context cnContext; generate_chacha8_key(cnContext, "", newStorageKey); } copyContainerStoragePrefix(m_containerStorage, m_key, newStorage, newStorageKey); copyContainerStorageKeys(m_containerStorage, m_key, newStorage, newStorageKey); saveWalletCache(newStorage, newStorageKey, saveLevel, extra); failExitHandler.cancel(); m_logger(INFO) << "Container export finished"; } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to export container: " << e.what(); startBlockchainSynchronizer(); throw; } startBlockchainSynchronizer(); m_logger(INFO, BRIGHT_WHITE) << "Container exported"; } void WalletGreen::convertAndLoadWalletFile(const std::string &path, std::ifstream &&walletFileStream) { WalletSerializer s( *this, m_viewPublicKey, m_viewSecretKey, m_actualBalance, m_pendingBalance, m_walletsContainer, m_synchronizer, m_unlockTransactionsJob, m_transactions, m_transfers, m_transactionSoftLockTime, m_uncommitedTransactions); StdInputStream stream(walletFileStream); s.load(m_key, stream); walletFileStream.close(); boost::filesystem::path bakPath = path + ".backup"; boost::filesystem::path tmpPath = boost::filesystem::unique_path(path + ".tmp.%%%%-%%%%"); if (boost::filesystem::exists(bakPath)) { m_logger(INFO) << "Wallet backup already exists! Creating random file name backup."; bakPath = boost::filesystem::unique_path(path + ".%%%%-%%%%" + ".backup"); } tools::ScopeExit tmpFileDeleter([&tmpPath] { boost::system::error_code ignore; boost::filesystem::remove(tmpPath, ignore); }); m_containerStorage.open(tmpPath.string(), common::FileMappedVectorOpenMode::CREATE, sizeof(ContainerStoragePrefix)); ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); prefix->version = WalletSerializerV2::SERIALIZATION_VERSION; prefix->nextIv = crypto::randomChachaIV(); uint64_t creationTimestamp = time(nullptr); prefix->encryptedViewKeys = encryptKeyPair(m_viewPublicKey, m_viewSecretKey, creationTimestamp); for (auto spendKeys : m_walletsContainer.get<RandomAccessIndex>()) { m_containerStorage.push_back(encryptKeyPair(spendKeys.spendPublicKey, spendKeys.spendSecretKey, spendKeys.creationTimestamp)); incNextIv(); } saveWalletCache(m_containerStorage, m_key, WalletSaveLevel::SAVE_ALL, ""); boost::filesystem::rename(path, bakPath); std::error_code ec; m_containerStorage.rename(path, ec); if (ec) { m_logger(ERROR, BRIGHT_RED) << "Failed to rename " << tmpPath << " to " << path; boost::system::error_code ignore; boost::filesystem::rename(bakPath, path, ignore); throw std::system_error(ec, "Failed to replace wallet file"); } tmpFileDeleter.cancel(); m_logger(INFO, BRIGHT_WHITE) << "Wallet file converted! Previous version: " << bakPath; } void WalletGreen::incNextIv() { static_assert(sizeof(uint64_t) == sizeof(crypto::chacha8_iv), "Bad crypto::chacha8_iv size"); auto *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); incIv(prefix->nextIv); } void WalletGreen::loadAndDecryptContainerData(ContainerStorage &storage, const crypto::chacha8_key &key, BinaryArray &containerData) { common::MemoryInputStream suffixStream(storage.suffix(), storage.suffixSize()); BinaryInputStreamSerializer suffixSerializer(suffixStream); crypto::chacha8_iv suffixIv; BinaryArray encryptedContainer; suffixSerializer(suffixIv, "suffixIv"); suffixSerializer(encryptedContainer, "encryptedContainer"); containerData.resize(encryptedContainer.size()); chacha8(encryptedContainer.data(), encryptedContainer.size(), key, suffixIv, reinterpret_cast<char *>(containerData.data())); } void WalletGreen::loadWalletCache(std::unordered_set<crypto::PublicKey> &addedKeys, std::unordered_set<crypto::PublicKey> &deletedKeys, std::string &extra) { assert(m_containerStorage.isOpened()); BinaryArray contanerData; loadAndDecryptContainerData(m_containerStorage, m_key, contanerData); WalletSerializerV2 s( *this, m_viewPublicKey, m_viewSecretKey, m_actualBalance, m_pendingBalance, m_lockedDepositBalance, m_unlockedDepositBalance, m_walletsContainer, m_synchronizer, m_unlockTransactionsJob, m_transactions, m_transfers, m_deposits, m_uncommitedTransactions, extra, m_transactionSoftLockTime); common::MemoryInputStream containerStream(contanerData.data(), contanerData.size()); s.load(containerStream, reinterpret_cast<const ContainerStoragePrefix *>(m_containerStorage.prefix())->version); addedKeys = std::move(s.addedKeys()); deletedKeys = std::move(s.deletedKeys()); m_logger(INFO) << "Container cache loaded"; } void WalletGreen::loadContainerStorage(const std::string &path) { try { m_containerStorage.open(path, FileMappedVectorOpenMode::OPEN, sizeof(ContainerStoragePrefix)); ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); assert(prefix->version >= WalletSerializerV2::MIN_VERSION); uint64_t creationTimestamp; decryptKeyPair(prefix->encryptedViewKeys, m_viewPublicKey, m_viewSecretKey, creationTimestamp); throwIfKeysMissmatch(m_viewSecretKey, m_viewPublicKey, "Restored view public key doesn't correspond to secret key"); m_logger = logging::LoggerRef(m_logger.getLogger(), "WalletGreen/" + podToHex(m_viewPublicKey).substr(0, 5)); loadSpendKeys(); m_logger(DEBUGGING) << "Container keys were successfully loaded"; } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to load container keys: " << e.what(); m_walletsContainer.clear(); m_containerStorage.close(); throw; } } void WalletGreen::encryptAndSaveContainerData(ContainerStorage &storage, const crypto::chacha8_key &key, const void *containerData, size_t containerDataSize) { ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(storage.prefix()); crypto::chacha8_iv suffixIv = prefix->nextIv; incIv(prefix->nextIv); BinaryArray encryptedContainer; encryptedContainer.resize(containerDataSize); chacha8(containerData, containerDataSize, key, suffixIv, reinterpret_cast<char *>(encryptedContainer.data())); std::string suffix; common::StringOutputStream suffixStream(suffix); BinaryOutputStreamSerializer suffixSerializer(suffixStream); suffixSerializer(suffixIv, "suffixIv"); suffixSerializer(encryptedContainer, "encryptedContainer"); storage.resizeSuffix(suffix.size()); std::copy(suffix.begin(), suffix.end(), storage.suffix()); } void WalletGreen::incIv(crypto::chacha8_iv &iv) { static_assert(sizeof(uint64_t) == sizeof(crypto::chacha8_iv), "Bad crypto::chacha8_iv size"); uint64_t *i = reinterpret_cast<uint64_t *>(&iv); if (*i < std::numeric_limits<uint64_t>::max()) { ++(*i); } else { *i = 0; } } void WalletGreen::load(const std::string &path, const std::string &password, std::string &extra) { m_logger(INFO, BRIGHT_WHITE) << "Loading container..."; if (m_state != WalletState::NOT_INITIALIZED) { m_logger(ERROR, BRIGHT_RED) << "Failed to load: already initialized."; throw std::system_error(make_error_code(error::WRONG_STATE)); } throwIfStopped(); stopBlockchainSynchronizer(); crypto::cn_context cnContext; generate_chacha8_key(cnContext, password, m_key); std::ifstream walletFileStream(path, std::ios_base::binary); int version = walletFileStream.peek(); if (version == EOF) { m_logger(ERROR, BRIGHT_RED) << "Failed to read wallet version"; throw std::system_error(make_error_code(error::WRONG_VERSION), "Failed to read wallet version"); } if (version < WalletSerializerV2::MIN_VERSION) { convertAndLoadWalletFile(path, std::move(walletFileStream)); } else { walletFileStream.close(); if (version > WalletSerializerV2::SERIALIZATION_VERSION) { m_logger(ERROR, BRIGHT_RED) << "Unsupported wallet version: " << version; throw std::system_error(make_error_code(error::WRONG_VERSION), "Unsupported wallet version"); } loadContainerStorage(path); subscribeWallets(); if (m_containerStorage.suffixSize() > 0) { try { std::unordered_set<crypto::PublicKey> addedSpendKeys; std::unordered_set<crypto::PublicKey> deletedSpendKeys; loadWalletCache(addedSpendKeys, deletedSpendKeys, extra); if (!addedSpendKeys.empty()) { m_logger(WARNING, BRIGHT_YELLOW) << "Found addresses not saved in container cache. Resynchronize container"; clearCaches(false, true); subscribeWallets(); } if (!deletedSpendKeys.empty()) { m_logger(WARNING, BRIGHT_YELLOW) << "Found deleted addresses saved in container cache. Remove its transactions"; deleteOrphanTransactions(deletedSpendKeys); } if (!addedSpendKeys.empty() || !deletedSpendKeys.empty()) { saveWalletCache(m_containerStorage, m_key, WalletSaveLevel::SAVE_ALL, extra); } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to load cache: " << e.what() << ", reset wallet data"; clearCaches(true, true); subscribeWallets(); } } } // Read all output keys cache try { std::vector<AccountPublicAddress> subscriptionList; m_synchronizer.getSubscriptions(subscriptionList); for (auto &addr : subscriptionList) { auto sub = m_synchronizer.getSubscription(addr); if (sub != nullptr) { std::vector<TransactionOutputInformation> allTransfers; ITransfersContainer *container = &sub->getContainer(); container->getOutputs(allTransfers, ITransfersContainer::IncludeAll); m_logger(INFO, BRIGHT_WHITE) << "Known Transfers " << allTransfers.size(); for (auto &o : allTransfers) { if (o.type != transaction_types::OutputType::Invalid) { m_synchronizer.addPublicKeysSeen(addr, o.transactionHash, o.outputKey); } } } } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to read output keys!! Continue without output keys: " << e.what(); } m_blockchainSynchronizer.addObserver(this); initTransactionPool(); assert(m_blockchain.empty()); if (m_walletsContainer.get<RandomAccessIndex>().size() != 0) { m_synchronizer.subscribeConsumerNotifications(m_viewPublicKey, this); initBlockchain(m_viewPublicKey); startBlockchainSynchronizer(); } else { m_blockchain.push_back(m_currency.genesisBlockHash()); m_logger(DEBUGGING) << "Add genesis block hash to blockchain"; } m_password = password; m_path = path; m_extra = extra; m_state = WalletState::INITIALIZED; m_logger(INFO, BRIGHT_WHITE) << "Container loaded, view public key " << common::podToHex(m_viewPublicKey) << ", wallet count " << m_walletsContainer.size() << ", actual balance " << m_currency.formatAmount(m_actualBalance) << ", pending balance " << m_currency.formatAmount(m_pendingBalance); } void WalletGreen::clearCaches(bool clearTransactions, bool clearCachedData) { if (clearTransactions) { m_transactions.clear(); m_transfers.clear(); m_deposits.clear(); } if (clearCachedData) { size_t walletIndex = 0; for (auto it = m_walletsContainer.begin(); it != m_walletsContainer.end(); ++it) { m_walletsContainer.modify(it, [&walletIndex](WalletRecord &wallet) { wallet.actualBalance = 0; wallet.pendingBalance = 0; wallet.lockedDepositBalance = 0; wallet.unlockedDepositBalance = 0; wallet.container = reinterpret_cast<cn::ITransfersContainer *>(walletIndex++); //dirty hack. container field must be unique }); } if (!clearTransactions) { for (auto it = m_transactions.begin(); it != m_transactions.end(); ++it) { m_transactions.modify(it, [](WalletTransaction &tx) { tx.state = WalletTransactionState::CANCELLED; tx.blockHeight = WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; }); } } std::vector<AccountPublicAddress> subscriptions; m_synchronizer.getSubscriptions(subscriptions); std::for_each(subscriptions.begin(), subscriptions.end(), [this](const AccountPublicAddress &address) { m_synchronizer.removeSubscription(address); }); m_uncommitedTransactions.clear(); m_unlockTransactionsJob.clear(); m_actualBalance = 0; m_pendingBalance = 0; m_lockedDepositBalance = 0; m_unlockedDepositBalance = 0; m_fusionTxsCache.clear(); m_blockchain.clear(); } } void WalletGreen::subscribeWallets() { try { auto &index = m_walletsContainer.get<RandomAccessIndex>(); for (auto it = index.begin(); it != index.end(); ++it) { const auto &wallet = *it; AccountSubscription sub; sub.keys.address.viewPublicKey = m_viewPublicKey; sub.keys.address.spendPublicKey = wallet.spendPublicKey; sub.keys.viewSecretKey = m_viewSecretKey; sub.keys.spendSecretKey = wallet.spendSecretKey; sub.transactionSpendableAge = m_transactionSoftLockTime; sub.syncStart.height = 0; sub.syncStart.timestamp = std::max(static_cast<uint64_t>(wallet.creationTimestamp), ACCOUNT_CREATE_TIME_ACCURACY) - ACCOUNT_CREATE_TIME_ACCURACY; auto &subscription = m_synchronizer.addSubscription(sub); bool r = index.modify(it, [&subscription](WalletRecord &rec) { rec.container = &subscription.getContainer(); }); assert(r); if (r) { }; subscription.addObserver(this); } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to subscribe wallets: " << e.what(); std::vector<AccountPublicAddress> subscriptionList; m_synchronizer.getSubscriptions(subscriptionList); for (auto &subscription : subscriptionList) { m_synchronizer.removeSubscription(subscription); } throw; } } void WalletGreen::load(const std::string &path, const std::string &password) { std::string extra; load(path, password, extra); } void WalletGreen::changePassword(const std::string &oldPassword, const std::string &newPassword) { throwIfNotInitialized(); throwIfStopped(); if (m_password.compare(oldPassword)) { throw std::system_error(make_error_code(error::WRONG_PASSWORD)); } m_password = newPassword; } size_t WalletGreen::getAddressCount() const { throwIfNotInitialized(); throwIfStopped(); return m_walletsContainer.get<RandomAccessIndex>().size(); } size_t WalletGreen::getWalletDepositCount() const { throwIfNotInitialized(); throwIfStopped(); return m_deposits.get<RandomAccessIndex>().size(); } std::string WalletGreen::getAddress(size_t index) const { throwIfNotInitialized(); throwIfStopped(); if (index >= m_walletsContainer.get<RandomAccessIndex>().size()) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } const WalletRecord &wallet = m_walletsContainer.get<RandomAccessIndex>()[index]; return m_currency.accountAddressAsString({wallet.spendPublicKey, m_viewPublicKey}); } KeyPair WalletGreen::getAddressSpendKey(size_t index) const { throwIfNotInitialized(); throwIfStopped(); if (index >= m_walletsContainer.get<RandomAccessIndex>().size()) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } const WalletRecord &wallet = m_walletsContainer.get<RandomAccessIndex>()[index]; return {wallet.spendPublicKey, wallet.spendSecretKey}; } KeyPair WalletGreen::getAddressSpendKey(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); cn::AccountPublicAddress pubAddr = parseAddress(address); auto it = m_walletsContainer.get<KeysIndex>().find(pubAddr.spendPublicKey); if (it == m_walletsContainer.get<KeysIndex>().end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND)); } return {it->spendPublicKey, it->spendSecretKey}; } KeyPair WalletGreen::getViewKey() const { throwIfNotInitialized(); throwIfStopped(); return {m_viewPublicKey, m_viewSecretKey}; } std::string WalletGreen::createAddress() { KeyPair spendKey; crypto::generate_keys(spendKey.publicKey, spendKey.secretKey); uint64_t creationTimestamp = static_cast<uint64_t>(time(nullptr)); return doCreateAddress(spendKey.publicKey, spendKey.secretKey, creationTimestamp); } std::string WalletGreen::createAddress(const crypto::SecretKey &spendSecretKey) { crypto::PublicKey spendPublicKey; if (!crypto::secret_key_to_public_key(spendSecretKey, spendPublicKey)) { throw std::system_error(make_error_code(cn::error::KEY_GENERATION_ERROR)); } uint64_t creationTimestamp = static_cast<uint64_t>(time(nullptr)); return doCreateAddress(spendPublicKey, spendSecretKey, creationTimestamp); } std::string WalletGreen::createAddress(const crypto::PublicKey &spendPublicKey) { if (!crypto::check_key(spendPublicKey)) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS), "Wrong public key format"); } uint64_t creationTimestamp = static_cast<uint64_t>(time(nullptr)); return doCreateAddress(spendPublicKey, NULL_SECRET_KEY, creationTimestamp); } std::vector<std::string> WalletGreen::createAddressList(const std::vector<crypto::SecretKey> &spendSecretKeys, bool reset) { std::vector<NewAddressData> addressDataList(spendSecretKeys.size()); for (size_t i = 0; i < spendSecretKeys.size(); ++i) { crypto::PublicKey spendPublicKey; if (!crypto::secret_key_to_public_key(spendSecretKeys[i], spendPublicKey)) { m_logger(ERROR) << "createAddressList(): failed to convert secret key to public key"; throw std::system_error(make_error_code(cn::error::KEY_GENERATION_ERROR)); } addressDataList[i].spendSecretKey = spendSecretKeys[i]; addressDataList[i].spendPublicKey = spendPublicKey; addressDataList[i].creationTimestamp = reset ? 0 : static_cast<uint64_t>(time(nullptr)); } return doCreateAddressList(addressDataList); } std::vector<std::string> WalletGreen::doCreateAddressList(const std::vector<NewAddressData> &addressDataList) { throwIfNotInitialized(); throwIfStopped(); stopBlockchainSynchronizer(); std::vector<std::string> addresses; try { uint64_t minCreationTimestamp = std::numeric_limits<uint64_t>::max(); { if (addressDataList.size() > 1) { m_containerStorage.setAutoFlush(false); } tools::ScopeExit exitHandler([this] { if (!m_containerStorage.getAutoFlush()) { m_containerStorage.setAutoFlush(true); m_containerStorage.flush(); } }); for (auto &addressData : addressDataList) { assert(addressData.creationTimestamp <= std::numeric_limits<uint64_t>::max() - m_currency.blockFutureTimeLimit()); std::string address = addWallet(addressData.spendPublicKey, addressData.spendSecretKey, addressData.creationTimestamp); m_logger(INFO, BRIGHT_WHITE) << "New wallet added " << address << ", creation timestamp " << addressData.creationTimestamp; addresses.push_back(std::move(address)); minCreationTimestamp = std::min(minCreationTimestamp, addressData.creationTimestamp); } } m_containerStorage.setAutoFlush(true); auto currentTime = static_cast<uint64_t>(time(nullptr)); if (minCreationTimestamp + m_currency.blockFutureTimeLimit() < currentTime) { m_logger(DEBUGGING) << "Reset is required"; save(WalletSaveLevel::SAVE_KEYS_AND_TRANSACTIONS, m_extra); shutdown(); load(m_path, m_password); } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to add wallets: " << e.what(); startBlockchainSynchronizer(); throw; } startBlockchainSynchronizer(); return addresses; } std::string WalletGreen::doCreateAddress(const crypto::PublicKey &spendPublicKey, const crypto::SecretKey &spendSecretKey, uint64_t creationTimestamp) { assert(creationTimestamp <= std::numeric_limits<uint64_t>::max() - m_currency.blockFutureTimeLimit()); std::vector<NewAddressData> addressDataList; addressDataList.push_back(NewAddressData{spendPublicKey, spendSecretKey, creationTimestamp}); std::vector<std::string> addresses = doCreateAddressList(addressDataList); assert(addresses.size() == 1); return addresses.front(); } std::string WalletGreen::addWallet(const crypto::PublicKey &spendPublicKey, const crypto::SecretKey &spendSecretKey, uint64_t creationTimestamp) { auto &index = m_walletsContainer.get<KeysIndex>(); auto trackingMode = getTrackingMode(); if ((trackingMode == WalletTrackingMode::TRACKING && spendSecretKey != NULL_SECRET_KEY) || (trackingMode == WalletTrackingMode::NOT_TRACKING && spendSecretKey == NULL_SECRET_KEY)) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS)); } auto insertIt = index.find(spendPublicKey); if (insertIt != index.end()) { m_logger(ERROR, BRIGHT_RED) << "Failed to add wallet: address already exists, " << m_currency.accountAddressAsString(AccountPublicAddress{spendPublicKey, m_viewPublicKey}); throw std::system_error(make_error_code(error::ADDRESS_ALREADY_EXISTS)); } m_containerStorage.push_back(encryptKeyPair(spendPublicKey, spendSecretKey, creationTimestamp)); incNextIv(); try { AccountSubscription sub; sub.keys.address.viewPublicKey = m_viewPublicKey; sub.keys.address.spendPublicKey = spendPublicKey; sub.keys.viewSecretKey = m_viewSecretKey; sub.keys.spendSecretKey = spendSecretKey; sub.transactionSpendableAge = m_transactionSoftLockTime; sub.syncStart.height = 0; sub.syncStart.timestamp = std::max(creationTimestamp, ACCOUNT_CREATE_TIME_ACCURACY) - ACCOUNT_CREATE_TIME_ACCURACY; auto &trSubscription = m_synchronizer.addSubscription(sub); ITransfersContainer *container = &trSubscription.getContainer(); WalletRecord wallet; wallet.spendPublicKey = spendPublicKey; wallet.spendSecretKey = spendSecretKey; wallet.container = container; wallet.creationTimestamp = static_cast<time_t>(creationTimestamp); trSubscription.addObserver(this); index.insert(insertIt, std::move(wallet)); m_logger(DEBUGGING) << "Wallet count " << m_walletsContainer.size(); if (index.size() == 1) { m_synchronizer.subscribeConsumerNotifications(m_viewPublicKey, this); initBlockchain(m_viewPublicKey); } auto address = m_currency.accountAddressAsString({spendPublicKey, m_viewPublicKey}); m_logger(DEBUGGING) << "Wallet added " << address << ", creation timestamp " << creationTimestamp; return address; } catch (const std::exception &e) { m_logger(ERROR) << "Failed to add wallet: " << e.what(); try { m_containerStorage.pop_back(); } catch (...) { m_logger(ERROR) << "Failed to rollback adding wallet to storage"; } throw; } } void WalletGreen::deleteAddress(const std::string &address) { throwIfNotInitialized(); throwIfStopped(); cn::AccountPublicAddress pubAddr = parseAddress(address); auto it = m_walletsContainer.get<KeysIndex>().find(pubAddr.spendPublicKey); if (it == m_walletsContainer.get<KeysIndex>().end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND)); } stopBlockchainSynchronizer(); m_actualBalance -= it->actualBalance; m_pendingBalance -= it->pendingBalance; m_synchronizer.removeSubscription(pubAddr); deleteContainerFromUnlockTransactionJobs(it->container); std::vector<size_t> deletedTransactions; std::vector<size_t> updatedTransactions = deleteTransfersForAddress(address, deletedTransactions); deleteFromUncommitedTransactions(deletedTransactions); m_walletsContainer.get<KeysIndex>().erase(it); auto addressIndex = std::distance( m_walletsContainer.get<RandomAccessIndex>().begin(), m_walletsContainer.project<RandomAccessIndex>(it)); m_containerStorage.erase(std::next(m_containerStorage.begin(), addressIndex)); if (m_walletsContainer.get<RandomAccessIndex>().size() != 0) { startBlockchainSynchronizer(); } else { m_blockchain.clear(); m_blockchain.push_back(m_currency.genesisBlockHash()); } for (auto transactionId : updatedTransactions) { pushEvent(makeTransactionUpdatedEvent(transactionId)); } } uint64_t WalletGreen::getActualBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_actualBalance; } uint64_t WalletGreen::getActualBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.actualBalance; } uint64_t WalletGreen::getPendingBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_pendingBalance; } uint64_t WalletGreen::getLockedDepositBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.lockedDepositBalance; } uint64_t WalletGreen::getUnlockedDepositBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.unlockedDepositBalance; } uint64_t WalletGreen::getLockedDepositBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_lockedDepositBalance; } uint64_t WalletGreen::getUnlockedDepositBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_unlockedDepositBalance; } uint64_t WalletGreen::getPendingBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.pendingBalance; } size_t WalletGreen::getTransactionCount() const { throwIfNotInitialized(); throwIfStopped(); return m_transactions.get<RandomAccessIndex>().size(); } WalletTransaction WalletGreen::getTransaction(size_t transactionIndex) const { throwIfNotInitialized(); throwIfStopped(); if (m_transactions.size() <= transactionIndex) { throw std::system_error(make_error_code(cn::error::INDEX_OUT_OF_RANGE)); } return m_transactions.get<RandomAccessIndex>()[transactionIndex]; } Deposit WalletGreen::getDeposit(size_t depositIndex) const { throwIfNotInitialized(); throwIfStopped(); if (m_deposits.size() <= depositIndex) { throw std::system_error(make_error_code(cn::error::DEPOSIT_DOESNOT_EXIST)); } return m_deposits.get<RandomAccessIndex>()[depositIndex]; } size_t WalletGreen::getTransactionTransferCount(size_t transactionIndex) const { throwIfNotInitialized(); throwIfStopped(); auto bounds = getTransactionTransfersRange(transactionIndex); return static_cast<size_t>(std::distance(bounds.first, bounds.second)); } WalletTransfer WalletGreen::getTransactionTransfer(size_t transactionIndex, size_t transferIndex) const { throwIfNotInitialized(); throwIfStopped(); auto bounds = getTransactionTransfersRange(transactionIndex); if (transferIndex >= static_cast<size_t>(std::distance(bounds.first, bounds.second))) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } return std::next(bounds.first, transferIndex)->second; } WalletGreen::TransfersRange WalletGreen::getTransactionTransfersRange(size_t transactionIndex) const { auto val = std::make_pair(transactionIndex, WalletTransfer()); auto bounds = std::equal_range(m_transfers.begin(), m_transfers.end(), val, [](const TransactionTransferPair &a, const TransactionTransferPair &b) { return a.first < b.first; }); return bounds; } size_t WalletGreen::transfer(const TransactionParameters &transactionParameters, crypto::SecretKey &transactionSK) { tools::ScopeExit releaseContext([this] { m_dispatcher.yield(); }); platform_system::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); return doTransfer(transactionParameters, transactionSK); } void WalletGreen::prepareTransaction( std::vector<WalletOuts> &&wallets, const std::vector<WalletOrder> &orders, const std::vector<WalletMessage> &messages, uint64_t fee, uint64_t mixIn, const std::string &extra, uint64_t unlockTimestamp, const DonationSettings &donation, const cn::AccountPublicAddress &changeDestination, PreparedTransaction &preparedTransaction, crypto::SecretKey &transactionSK) { preparedTransaction.destinations = convertOrdersToTransfers(orders); preparedTransaction.neededMoney = countNeededMoney(preparedTransaction.destinations, fee); std::vector<OutputToTransfer> selectedTransfers; uint64_t foundMoney = selectTransfers(preparedTransaction.neededMoney, m_currency.defaultDustThreshold(), std::move(wallets), selectedTransfers); if (foundMoney < preparedTransaction.neededMoney) { throw std::system_error(make_error_code(error::WRONG_AMOUNT), "Not enough money"); } typedef cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount; std::vector<outs_for_amount> mixinResult; if (mixIn != 0) { requestMixinOuts(selectedTransfers, mixIn, mixinResult); } std::vector<InputInfo> keysInfo; prepareInputs(selectedTransfers, mixinResult, mixIn, keysInfo); uint64_t donationAmount = pushDonationTransferIfPossible(donation, foundMoney - preparedTransaction.neededMoney, m_currency.defaultDustThreshold(), preparedTransaction.destinations); preparedTransaction.changeAmount = foundMoney - preparedTransaction.neededMoney - donationAmount; std::vector<ReceiverAmounts> decomposedOutputs = splitDestinations(preparedTransaction.destinations, m_currency.defaultDustThreshold(), m_currency); if (preparedTransaction.changeAmount != 0) { WalletTransfer changeTransfer; changeTransfer.type = WalletTransferType::CHANGE; changeTransfer.address = m_currency.accountAddressAsString(changeDestination); changeTransfer.amount = static_cast<int64_t>(preparedTransaction.changeAmount); preparedTransaction.destinations.emplace_back(std::move(changeTransfer)); auto splittedChange = splitAmount(preparedTransaction.changeAmount, changeDestination, m_currency.defaultDustThreshold()); decomposedOutputs.emplace_back(std::move(splittedChange)); } preparedTransaction.transaction = makeTransaction(decomposedOutputs, keysInfo, messages, extra, unlockTimestamp, transactionSK); } void WalletGreen::validateTransactionParameters(const TransactionParameters &transactionParameters) const { if (transactionParameters.destinations.empty()) { throw std::system_error(make_error_code(error::ZERO_DESTINATION)); } if (transactionParameters.donation.address.empty() != (transactionParameters.donation.threshold == 0)) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS)); } validateSourceAddresses(transactionParameters.sourceAddresses); validateChangeDestination(transactionParameters.sourceAddresses, transactionParameters.changeDestination, false); validateOrders(transactionParameters.destinations); } size_t WalletGreen::doTransfer(const TransactionParameters &transactionParameters, crypto::SecretKey &transactionSK) { validateTransactionParameters(transactionParameters); cn::AccountPublicAddress changeDestination = getChangeDestination(transactionParameters.changeDestination, transactionParameters.sourceAddresses); std::vector<WalletOuts> wallets; if (!transactionParameters.sourceAddresses.empty()) { wallets = pickWallets(transactionParameters.sourceAddresses); } else { wallets = pickWalletsWithMoney(); } PreparedTransaction preparedTransaction; prepareTransaction( std::move(wallets), transactionParameters.destinations, transactionParameters.messages, transactionParameters.fee, transactionParameters.mixIn, transactionParameters.extra, transactionParameters.unlockTimestamp, transactionParameters.donation, changeDestination, preparedTransaction, transactionSK); return validateSaveAndSendTransaction(*preparedTransaction.transaction, preparedTransaction.destinations, false, true); } size_t WalletGreen::makeTransaction(const TransactionParameters &sendingTransaction) { size_t id = WALLET_INVALID_TRANSACTION_ID; tools::ScopeExit releaseContext([this, &id] { m_dispatcher.yield(); if (id != WALLET_INVALID_TRANSACTION_ID) { auto &tx = m_transactions[id]; } }); platform_system::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); validateTransactionParameters(sendingTransaction); cn::AccountPublicAddress changeDestination = getChangeDestination(sendingTransaction.changeDestination, sendingTransaction.sourceAddresses); m_logger(DEBUGGING) << "Change address " << m_currency.accountAddressAsString(changeDestination); std::vector<WalletOuts> wallets; if (!sendingTransaction.sourceAddresses.empty()) { wallets = pickWallets(sendingTransaction.sourceAddresses); } else { wallets = pickWalletsWithMoney(); } PreparedTransaction preparedTransaction; crypto::SecretKey txSecretKey; prepareTransaction( std::move(wallets), sendingTransaction.destinations, sendingTransaction.messages, sendingTransaction.fee, sendingTransaction.mixIn, sendingTransaction.extra, sendingTransaction.unlockTimestamp, sendingTransaction.donation, changeDestination, preparedTransaction, txSecretKey); id = validateSaveAndSendTransaction(*preparedTransaction.transaction, preparedTransaction.destinations, false, false); return id; } void WalletGreen::commitTransaction(size_t transactionId) { platform_system::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfStopped(); throwIfTrackingMode(); if (transactionId >= m_transactions.size()) { m_logger(ERROR, BRIGHT_RED) << "Failed to commit transaction: invalid index " << transactionId << ". Number of transactions: " << m_transactions.size(); throw std::system_error(make_error_code(cn::error::INDEX_OUT_OF_RANGE)); } auto txIt = std::next(m_transactions.get<RandomAccessIndex>().begin(), transactionId); if (m_uncommitedTransactions.count(transactionId) == 0 || txIt->state != WalletTransactionState::CREATED) { throw std::system_error(make_error_code(error::TX_TRANSFER_IMPOSSIBLE)); } platform_system::Event completion(m_dispatcher); std::error_code ec; m_node.relayTransaction(m_uncommitedTransactions[transactionId], [&ec, &completion, this](std::error_code error) { ec = error; this->m_dispatcher.remoteSpawn(std::bind(asyncRequestCompletion, std::ref(completion))); }); completion.wait(); if (!ec) { updateTransactionStateAndPushEvent(transactionId, WalletTransactionState::SUCCEEDED); m_uncommitedTransactions.erase(transactionId); } else { throw std::system_error(ec); } } void WalletGreen::rollbackUncommitedTransaction(size_t transactionId) { tools::ScopeExit releaseContext([this] { m_dispatcher.yield(); }); platform_system::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfStopped(); throwIfTrackingMode(); if (transactionId >= m_transactions.size()) { throw std::system_error(make_error_code(cn::error::INDEX_OUT_OF_RANGE)); } auto txIt = m_transactions.get<RandomAccessIndex>().begin(); std::advance(txIt, transactionId); if (m_uncommitedTransactions.count(transactionId) == 0 || txIt->state != WalletTransactionState::CREATED) { throw std::system_error(make_error_code(error::TX_CANCEL_IMPOSSIBLE)); } removeUnconfirmedTransaction(getObjectHash(m_uncommitedTransactions[transactionId])); m_uncommitedTransactions.erase(transactionId); } void WalletGreen::pushBackOutgoingTransfers(size_t txId, const std::vector<WalletTransfer> &destinations) { for (const auto &dest : destinations) { WalletTransfer d; d.type = dest.type; d.address = dest.address; d.amount = dest.amount; m_transfers.emplace_back(txId, std::move(d)); } } size_t WalletGreen::insertOutgoingTransactionAndPushEvent(const Hash &transactionHash, uint64_t fee, const BinaryArray &extra, uint64_t unlockTimestamp) { WalletTransaction insertTx; insertTx.state = WalletTransactionState::CREATED; insertTx.creationTime = static_cast<uint64_t>(time(nullptr)); insertTx.unlockTime = unlockTimestamp; insertTx.blockHeight = cn::WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; insertTx.extra.assign(reinterpret_cast<const char *>(extra.data()), extra.size()); insertTx.fee = fee; insertTx.hash = transactionHash; insertTx.totalAmount = 0; // 0 until transactionHandlingEnd() is called insertTx.timestamp = 0; //0 until included in a block insertTx.isBase = false; size_t txId = m_transactions.get<RandomAccessIndex>().size(); m_transactions.get<RandomAccessIndex>().push_back(std::move(insertTx)); pushEvent(makeTransactionCreatedEvent(txId)); return txId; } void WalletGreen::updateTransactionStateAndPushEvent(size_t transactionId, WalletTransactionState state) { auto it = std::next(m_transactions.get<RandomAccessIndex>().begin(), transactionId); if (it->state != state) { m_transactions.get<RandomAccessIndex>().modify(it, [state](WalletTransaction &tx) { tx.state = state; }); pushEvent(makeTransactionUpdatedEvent(transactionId)); } } bool WalletGreen::updateWalletDepositInfo(size_t depositId, const cn::Deposit &info) { auto &txIdIndex = m_deposits.get<RandomAccessIndex>(); assert(depositId < txIdIndex.size()); auto it = std::next(txIdIndex.begin(), depositId); bool updated = false; bool r = txIdIndex.modify(it, [&info, &updated](Deposit &deposit) { if (deposit.spendingTransactionId != info.spendingTransactionId) { deposit.spendingTransactionId = info.spendingTransactionId; updated = true; } }); assert(r); return updated; } bool WalletGreen::updateWalletTransactionInfo(size_t transactionId, const cn::TransactionInformation &info, int64_t totalAmount) { auto &txIdIndex = m_transactions.get<RandomAccessIndex>(); assert(transactionId < txIdIndex.size()); auto it = std::next(txIdIndex.begin(), transactionId); bool updated = false; bool r = txIdIndex.modify(it, [&info, totalAmount, &updated](WalletTransaction &transaction) { if (transaction.firstDepositId != info.firstDepositId) { transaction.firstDepositId = info.firstDepositId; updated = true; transaction.depositCount = 1; } if (transaction.blockHeight != info.blockHeight) { transaction.blockHeight = info.blockHeight; updated = true; } if (transaction.timestamp != info.timestamp) { transaction.timestamp = info.timestamp; updated = true; } bool isSucceeded = transaction.state == WalletTransactionState::SUCCEEDED; // If transaction was sent to daemon, it can not have CREATED and FAILED states, its state can be SUCCEEDED, CANCELLED or DELETED bool wasSent = transaction.state != WalletTransactionState::CREATED && transaction.state != WalletTransactionState::FAILED; bool isConfirmed = transaction.blockHeight != WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; if (!isSucceeded && (wasSent || isConfirmed)) { //transaction may be deleted first then added again transaction.state = WalletTransactionState::SUCCEEDED; updated = true; } if (transaction.totalAmount != totalAmount) { transaction.totalAmount = totalAmount; updated = true; } // Fix LegacyWallet error. Some old versions didn't fill extra field if (transaction.extra.empty() && !info.extra.empty()) { transaction.extra = common::asString(info.extra); updated = true; } bool isBase = info.totalAmountIn == 0; if (transaction.isBase != isBase) { transaction.isBase = isBase; updated = true; } }); assert(r); return updated; } size_t WalletGreen::insertBlockchainTransaction(const TransactionInformation &info, int64_t txBalance) { auto &index = m_transactions.get<RandomAccessIndex>(); WalletTransaction tx; tx.state = WalletTransactionState::SUCCEEDED; tx.timestamp = info.timestamp; tx.blockHeight = info.blockHeight; tx.hash = info.transactionHash; tx.depositCount = 0; tx.firstDepositId = WALLET_INVALID_DEPOSIT_ID; tx.isBase = info.totalAmountIn == 0; if (tx.isBase) { tx.fee = 0; } else { tx.fee = info.totalAmountIn < info.totalAmountOut ? cn::parameters::MINIMUM_FEE : info.totalAmountIn - info.totalAmountOut; } tx.unlockTime = info.unlockTime; tx.extra.assign(reinterpret_cast<const char *>(info.extra.data()), info.extra.size()); tx.totalAmount = txBalance; tx.creationTime = info.timestamp; size_t txId = index.size(); index.push_back(std::move(tx)); return txId; } uint64_t WalletGreen::scanHeightToTimestamp(const uint32_t scanHeight) { if (scanHeight == 0) { return 0; } /* Get the amount of seconds since the blockchain launched */ double secondsSinceLaunch = scanHeight * cn::parameters::DIFFICULTY_TARGET; /* Add a bit of a buffer in case of difficulty weirdness, blocks coming out too fast */ secondsSinceLaunch = secondsSinceLaunch * 0.95; /* Get the genesis block timestamp and add the time since launch */ uint64_t timestamp = m_currency.getGenesisTimestamp() + static_cast<uint64_t>(secondsSinceLaunch); /* Timestamp in the future */ if (timestamp >= static_cast<uint64_t>(std::time(nullptr))) { return getCurrentTimestampAdjusted(); } return timestamp; } uint64_t WalletGreen::getCurrentTimestampAdjusted() { /* Get the current time as a unix timestamp */ std::time_t time = std::time(nullptr); /* Take the amount of time a block can potentially be in the past/future */ std::initializer_list<uint64_t> limits = { cn::parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT, cn::parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT_V1}; /* Get the largest adjustment possible */ uint64_t adjust = std::max(limits); /* Take the earliest timestamp that will include all possible blocks */ return time - adjust; } void WalletGreen::reset(const uint64_t scanHeight) { throwIfNotInitialized(); throwIfStopped(); /* Stop so things can't be added to the container as we're looping */ stop(); /* Grab the wallet encrypted prefix */ auto *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); m_logger(INFO, BRIGHT_WHITE) << "reset with height " << scanHeight; uint64_t newTimestamp = scanHeightToTimestamp((uint32_t)scanHeight); m_logger(INFO, BRIGHT_WHITE) << "new timestamp " << newTimestamp; /* Reencrypt with the new creation timestamp so we rescan from here when we relaunch */ prefix->encryptedViewKeys = encryptKeyPair(m_viewPublicKey, m_viewSecretKey, newTimestamp); /* As a reference so we can update it */ for (auto &encryptedSpendKeys : m_containerStorage) { crypto::PublicKey publicKey; crypto::SecretKey secretKey; uint64_t oldTimestamp; /* Decrypt the key pair we're pointing to */ decryptKeyPair(encryptedSpendKeys, publicKey, secretKey, oldTimestamp); /* Re-encrypt with the new timestamp */ encryptedSpendKeys = encryptKeyPair(publicKey, secretKey, newTimestamp); } /* Start again so we can save */ start(); /* Save just the keys + timestamp to file */ save(cn::WalletSaveLevel::SAVE_KEYS_ONLY); /* Stop and shutdown */ stop(); /* Shutdown the wallet */ shutdown(); start(); /* Reopen from truncated storage */ load(m_path, m_password); } bool WalletGreen::updateTransactionTransfers(size_t transactionId, const std::vector<ContainerAmounts> &containerAmountsList, int64_t allInputsAmount, int64_t allOutputsAmount) { assert(allInputsAmount <= 0); assert(allOutputsAmount >= 0); bool updated = false; auto transfersRange = getTransactionTransfersRange(transactionId); // Iterators can be invalidated, so the first transfer is addressed by its index size_t firstTransferIdx = std::distance(m_transfers.cbegin(), transfersRange.first); TransfersMap initialTransfers = getKnownTransfersMap(transactionId, firstTransferIdx); std::unordered_set<std::string> myInputAddresses; std::unordered_set<std::string> myOutputAddresses; int64_t myInputsAmount = 0; int64_t myOutputsAmount = 0; for (auto containerAmount : containerAmountsList) { AccountPublicAddress address{getWalletRecord(containerAmount.container).spendPublicKey, m_viewPublicKey}; std::string addressString = m_currency.accountAddressAsString(address); updated |= updateAddressTransfers(transactionId, firstTransferIdx, addressString, initialTransfers[addressString].input, containerAmount.amounts.input); updated |= updateAddressTransfers(transactionId, firstTransferIdx, addressString, initialTransfers[addressString].output, containerAmount.amounts.output); myInputsAmount += containerAmount.amounts.input; myOutputsAmount += containerAmount.amounts.output; if (containerAmount.amounts.input != 0) { myInputAddresses.emplace(addressString); } if (containerAmount.amounts.output != 0) { myOutputAddresses.emplace(addressString); } } assert(myInputsAmount >= allInputsAmount); assert(myOutputsAmount <= allOutputsAmount); int64_t knownInputsAmount = 0; int64_t knownOutputsAmount = 0; auto updatedTransfers = getKnownTransfersMap(transactionId, firstTransferIdx); for (const auto &pair : updatedTransfers) { knownInputsAmount += pair.second.input; knownOutputsAmount += pair.second.output; } assert(myInputsAmount >= knownInputsAmount); assert(myOutputsAmount <= knownOutputsAmount); updated |= updateUnknownTransfers(transactionId, firstTransferIdx, myInputAddresses, knownInputsAmount, myInputsAmount, allInputsAmount, false); updated |= updateUnknownTransfers(transactionId, firstTransferIdx, myOutputAddresses, knownOutputsAmount, myOutputsAmount, allOutputsAmount, true); return updated; } WalletGreen::TransfersMap WalletGreen::getKnownTransfersMap(size_t transactionId, size_t firstTransferIdx) const { TransfersMap result; for (auto it = std::next(m_transfers.begin(), firstTransferIdx); it != m_transfers.end() && it->first == transactionId; ++it) { const auto &address = it->second.address; if (!address.empty()) { if (it->second.amount < 0) { result[address].input += it->second.amount; } else { assert(it->second.amount > 0); result[address].output += it->second.amount; } } } return result; } bool WalletGreen::updateAddressTransfers(size_t transactionId, size_t firstTransferIdx, const std::string &address, int64_t knownAmount, int64_t targetAmount) { assert((knownAmount > 0 && targetAmount > 0) || (knownAmount < 0 && targetAmount < 0) || knownAmount == 0 || targetAmount == 0); bool updated = false; if (knownAmount != targetAmount) { if (knownAmount == 0) { appendTransfer(transactionId, firstTransferIdx, address, targetAmount); updated = true; } else if (targetAmount == 0) { assert(knownAmount != 0); updated |= eraseTransfersByAddress(transactionId, firstTransferIdx, address, knownAmount > 0); } else { updated |= adjustTransfer(transactionId, firstTransferIdx, address, targetAmount); } } return updated; } bool WalletGreen::updateUnknownTransfers(size_t transactionId, size_t firstTransferIdx, const std::unordered_set<std::string> &myAddresses, int64_t knownAmount, int64_t myAmount, int64_t totalAmount, bool isOutput) { bool updated = false; if (std::abs(knownAmount) > std::abs(totalAmount)) { updated |= eraseForeignTransfers(transactionId, firstTransferIdx, myAddresses, isOutput); if (totalAmount == myAmount) { updated |= eraseTransfersByAddress(transactionId, firstTransferIdx, std::string(), isOutput); } else { assert(std::abs(totalAmount) > std::abs(myAmount)); updated |= adjustTransfer(transactionId, firstTransferIdx, std::string(), totalAmount - myAmount); } } else if (knownAmount == totalAmount) { updated |= eraseTransfersByAddress(transactionId, firstTransferIdx, std::string(), isOutput); } else { assert(std::abs(totalAmount) > std::abs(knownAmount)); updated |= adjustTransfer(transactionId, firstTransferIdx, std::string(), totalAmount - knownAmount); } return updated; } void WalletGreen::appendTransfer(size_t transactionId, size_t firstTransferIdx, const std::string &address, int64_t amount) { auto it = std::next(m_transfers.begin(), firstTransferIdx); auto insertIt = std::upper_bound(it, m_transfers.end(), transactionId, [](size_t transactionId, const TransactionTransferPair &pair) { return transactionId < pair.first; }); WalletTransfer transfer{WalletTransferType::USUAL, address, amount}; m_transfers.emplace(insertIt, std::piecewise_construct, std::forward_as_tuple(transactionId), std::forward_as_tuple(transfer)); } bool WalletGreen::adjustTransfer(size_t transactionId, size_t firstTransferIdx, const std::string &address, int64_t amount) { assert(amount != 0); bool updated = false; bool updateOutputTransfers = amount > 0; bool firstAddressTransferFound = false; auto it = std::next(m_transfers.begin(), firstTransferIdx); while (it != m_transfers.end() && it->first == transactionId) { assert(it->second.amount != 0); bool transferIsOutput = it->second.amount > 0; if (transferIsOutput == updateOutputTransfers && it->second.address == address) { if (firstAddressTransferFound) { it = m_transfers.erase(it); updated = true; } else { if (it->second.amount != amount) { it->second.amount = amount; updated = true; } firstAddressTransferFound = true; ++it; } } else { ++it; } } if (!firstAddressTransferFound) { WalletTransfer transfer{WalletTransferType::USUAL, address, amount}; m_transfers.emplace(it, std::piecewise_construct, std::forward_as_tuple(transactionId), std::forward_as_tuple(transfer)); updated = true; } return updated; } bool WalletGreen::eraseTransfers(size_t transactionId, size_t firstTransferIdx, std::function<bool(bool, const std::string &)> &&predicate) { bool erased = false; auto it = std::next(m_transfers.begin(), firstTransferIdx); while (it != m_transfers.end() && it->first == transactionId) { bool transferIsOutput = it->second.amount > 0; if (predicate(transferIsOutput, it->second.address)) { it = m_transfers.erase(it); erased = true; } else { ++it; } } return erased; } bool WalletGreen::eraseTransfersByAddress(size_t transactionId, size_t firstTransferIdx, const std::string &address, bool eraseOutputTransfers) { return eraseTransfers(transactionId, firstTransferIdx, [&address, eraseOutputTransfers](bool isOutput, const std::string &transferAddress) { return eraseOutputTransfers == isOutput && address == transferAddress; }); } bool WalletGreen::eraseForeignTransfers(size_t transactionId, size_t firstTransferIdx, const std::unordered_set<std::string> &knownAddresses, bool eraseOutputTransfers) { return eraseTransfers(transactionId, firstTransferIdx, [this, &knownAddresses, eraseOutputTransfers](bool isOutput, const std::string &transferAddress) { return eraseOutputTransfers == isOutput && knownAddresses.count(transferAddress) == 0; }); } std::unique_ptr<cn::ITransaction> WalletGreen::makeTransaction(const std::vector<ReceiverAmounts> &decomposedOutputs, std::vector<InputInfo> &keysInfo, const std::vector<WalletMessage> &messages, const std::string &extra, uint64_t unlockTimestamp, crypto::SecretKey &transactionSK) { std::unique_ptr<ITransaction> tx = createTransaction(); using AmountToAddress = std::pair<const AccountPublicAddress *, uint64_t>; std::vector<AmountToAddress> amountsToAddresses; for (const auto &output : decomposedOutputs) { for (auto amount : output.amounts) { amountsToAddresses.emplace_back(AmountToAddress{&output.receiver, amount}); } } std::shuffle(amountsToAddresses.begin(), amountsToAddresses.end(), std::default_random_engine{crypto::rand<std::default_random_engine::result_type>()}); std::sort(amountsToAddresses.begin(), amountsToAddresses.end(), [](const AmountToAddress &left, const AmountToAddress &right) { return left.second < right.second; }); tx->setUnlockTime(unlockTimestamp); for (auto &input : keysInfo) { tx->addInput(makeAccountKeys(*input.walletRecord), input.keyInfo, input.ephKeys); } tx->setDeterministicTransactionSecretKey(m_viewSecretKey); tx->getTransactionSecretKey(transactionSK); crypto::PublicKey publicKey = tx->getTransactionPublicKey(); cn::KeyPair kp = {publicKey, transactionSK}; for (size_t i = 0; i < messages.size(); ++i) { cn::AccountPublicAddress addressBin; if (!m_currency.parseAccountAddressString(messages[i].address, addressBin)) continue; cn::tx_extra_message tag; if (!tag.encrypt(i, messages[i].message, &addressBin, kp)) continue; BinaryArray ba; toBinaryArray(tag, ba); ba.insert(ba.begin(), TX_EXTRA_MESSAGE_TAG); tx->appendExtra(ba); } for (const auto &amountToAddress : amountsToAddresses) { tx->addOutput(amountToAddress.second, *amountToAddress.first); } tx->appendExtra(common::asBinaryArray(extra)); size_t i = 0; for (const auto &input : keysInfo) { tx->signInputKey(i, input.keyInfo, input.ephKeys); i++; } return tx; } void WalletGreen::sendTransaction(const cn::Transaction &cryptoNoteTransaction) { platform_system::Event completion(m_dispatcher); std::error_code ec; throwIfStopped(); m_node.relayTransaction(cryptoNoteTransaction, [&ec, &completion, this](std::error_code error) { ec = error; this->m_dispatcher.remoteSpawn(std::bind(asyncRequestCompletion, std::ref(completion))); }); completion.wait(); if (ec) { throw std::system_error(ec); } } size_t WalletGreen::validateSaveAndSendTransaction( const ITransactionReader &transaction, const std::vector<WalletTransfer> &destinations, bool isFusion, bool send) { BinaryArray transactionData = transaction.getTransactionData(); if ((transactionData.size() > m_upperTransactionSizeLimit) && (isFusion == false)) { m_logger(ERROR, BRIGHT_RED) << "Transaction is too big"; throw std::system_error(make_error_code(error::TRANSACTION_SIZE_TOO_BIG)); } if ((transactionData.size() > m_currency.fusionTxMaxSize()) && (isFusion == true)) { m_logger(ERROR, BRIGHT_RED) << "Fusion transaction is too big. Transaction hash"; throw std::system_error(make_error_code(error::TRANSACTION_SIZE_TOO_BIG)); } cn::Transaction cryptoNoteTransaction; if (!fromBinaryArray(cryptoNoteTransaction, transactionData)) { throw std::system_error(make_error_code(error::INTERNAL_WALLET_ERROR), "Failed to deserialize created transaction"); } uint64_t fee = transaction.getInputTotalAmount() < transaction.getOutputTotalAmount() ? cn::parameters::MINIMUM_FEE : transaction.getInputTotalAmount() - transaction.getOutputTotalAmount(); size_t transactionId = insertOutgoingTransactionAndPushEvent(transaction.getTransactionHash(), fee, transaction.getExtra(), transaction.getUnlockTime()); tools::ScopeExit rollbackTransactionInsertion([this, transactionId] { updateTransactionStateAndPushEvent(transactionId, WalletTransactionState::FAILED); }); m_fusionTxsCache.emplace(transactionId, isFusion); pushBackOutgoingTransfers(transactionId, destinations); addUnconfirmedTransaction(transaction); tools::ScopeExit rollbackAddingUnconfirmedTransaction([this, &transaction] { try { removeUnconfirmedTransaction(transaction.getTransactionHash()); } catch (...) { m_logger(WARNING, BRIGHT_RED) << "Rollback has failed. The TX will be stored as unconfirmed and will be deleted after the wallet is relaunched during TX pool sync."; // Ignore any exceptions. If rollback fails then the transaction is stored as unconfirmed and will be deleted after wallet relaunch // during transaction pool synchronization } }); if (send) { sendTransaction(cryptoNoteTransaction); updateTransactionStateAndPushEvent(transactionId, WalletTransactionState::SUCCEEDED); } else { assert(m_uncommitedTransactions.count(transactionId) == 0); m_uncommitedTransactions.emplace(transactionId, std::move(cryptoNoteTransaction)); } rollbackAddingUnconfirmedTransaction.cancel(); rollbackTransactionInsertion.cancel(); return transactionId; } AccountKeys WalletGreen::makeAccountKeys(const WalletRecord &wallet) const { AccountKeys keys; keys.address.spendPublicKey = wallet.spendPublicKey; keys.address.viewPublicKey = m_viewPublicKey; keys.spendSecretKey = wallet.spendSecretKey; keys.viewSecretKey = m_viewSecretKey; return keys; } void WalletGreen::requestMixinOuts( const std::vector<OutputToTransfer> &selectedTransfers, uint64_t mixIn, std::vector<cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount> &mixinResult) { std::vector<uint64_t> amounts; for (const auto &out : selectedTransfers) { amounts.push_back(out.out.amount); } platform_system::Event requestFinished(m_dispatcher); std::error_code mixinError; throwIfStopped(); m_node.getRandomOutsByAmounts(std::move(amounts), mixIn, mixinResult, [&requestFinished, &mixinError, this](std::error_code ec) { mixinError = ec; this->m_dispatcher.remoteSpawn(std::bind(asyncRequestCompletion, std::ref(requestFinished))); }); requestFinished.wait(); checkIfEnoughMixins(mixinResult, mixIn); if (mixinError) { throw std::system_error(mixinError); } } uint64_t WalletGreen::selectTransfers( uint64_t neededMoney, uint64_t dustThreshold, std::vector<WalletOuts> &&wallets, std::vector<OutputToTransfer> &selectedTransfers) { uint64_t foundMoney = 0; typedef std::pair<WalletRecord *, TransactionOutputInformation> OutputData; std::vector<OutputData> walletOuts; std::unordered_map<uint64_t, std::vector<OutputData>> buckets; for (auto walletIt = wallets.begin(); walletIt != wallets.end(); ++walletIt) { for (auto outIt = walletIt->outs.begin(); outIt != walletIt->outs.end(); ++outIt) { int numberOfDigits = floor(log10(outIt->amount)) + 1; if (outIt->amount > dustThreshold) { buckets[numberOfDigits].emplace_back( std::piecewise_construct, std::forward_as_tuple(walletIt->wallet), std::forward_as_tuple(*outIt)); } } } while (foundMoney < neededMoney && !buckets.empty()) { /* Take one element from each bucket, smallest first. */ for (auto bucket = buckets.begin(); bucket != buckets.end();) { /* Bucket has been exhausted, remove from list */ if (bucket->second.empty()) { bucket = buckets.erase(bucket); } else { /** Add the amount to the selected transfers so long as * foundMoney is still less than neededMoney. This prevents * larger outputs than we need when we already have enough funds */ if (foundMoney < neededMoney) { auto out = bucket->second.back(); selectedTransfers.emplace_back(OutputToTransfer{std::move(out.second), std::move(out.first)}); foundMoney += out.second.amount; } /* Remove amount we just added */ bucket->second.pop_back(); bucket++; } } } return foundMoney; }; std::vector<WalletGreen::WalletOuts> WalletGreen::pickWalletsWithMoney() const { auto &walletsIndex = m_walletsContainer.get<RandomAccessIndex>(); std::vector<WalletOuts> walletOuts; for (const auto &wallet : walletsIndex) { if (wallet.actualBalance == 0) { continue; } ITransfersContainer *container = wallet.container; WalletOuts outs; container->getOutputs(outs.outs, ITransfersContainer::IncludeKeyUnlocked); outs.wallet = const_cast<WalletRecord *>(&wallet); walletOuts.push_back(std::move(outs)); }; return walletOuts; } WalletGreen::WalletOuts WalletGreen::pickWallet(const std::string &address) const { const auto &wallet = getWalletRecord(address); ITransfersContainer *container = wallet.container; WalletOuts outs; container->getOutputs(outs.outs, ITransfersContainer::IncludeKeyUnlocked); outs.wallet = const_cast<WalletRecord *>(&wallet); return outs; } std::vector<WalletGreen::WalletOuts> WalletGreen::pickWallets(const std::vector<std::string> &addresses) const { std::vector<WalletOuts> wallets; wallets.reserve(addresses.size()); for (const auto &address : addresses) { WalletOuts wallet = pickWallet(address); if (!wallet.outs.empty()) { wallets.emplace_back(std::move(wallet)); } } return wallets; } std::vector<cn::WalletGreen::ReceiverAmounts> WalletGreen::splitDestinations(const std::vector<cn::WalletTransfer> &destinations, uint64_t dustThreshold, const cn::Currency &currency) { std::vector<ReceiverAmounts> decomposedOutputs; for (const auto &destination : destinations) { AccountPublicAddress address; parseAddressString(destination.address, currency, address); decomposedOutputs.push_back(splitAmount(destination.amount, address, dustThreshold)); } return decomposedOutputs; } cn::WalletGreen::ReceiverAmounts WalletGreen::splitAmount( uint64_t amount, const AccountPublicAddress &destination, uint64_t dustThreshold) { ReceiverAmounts receiverAmounts; receiverAmounts.receiver = destination; decomposeAmount(amount, dustThreshold, receiverAmounts.amounts); return receiverAmounts; } void WalletGreen::prepareInputs( const std::vector<OutputToTransfer> &selectedTransfers, std::vector<cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount> &mixinResult, uint64_t mixIn, std::vector<InputInfo> &keysInfo) { typedef cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry out_entry; size_t i = 0; for (const auto &input : selectedTransfers) { transaction_types::InputKeyInfo keyInfo; keyInfo.amount = input.out.amount; if (mixinResult.size()) { std::sort(mixinResult[i].outs.begin(), mixinResult[i].outs.end(), [](const out_entry &a, const out_entry &b) { return a.global_amount_index < b.global_amount_index; }); for (auto &fakeOut : mixinResult[i].outs) { if (input.out.globalOutputIndex == fakeOut.global_amount_index) { continue; } transaction_types::GlobalOutput globalOutput; globalOutput.outputIndex = static_cast<uint32_t>(fakeOut.global_amount_index); globalOutput.targetKey = reinterpret_cast<PublicKey &>(fakeOut.out_key); keyInfo.outputs.push_back(std::move(globalOutput)); if (keyInfo.outputs.size() >= mixIn) break; } } //paste real transaction to the random index auto insertIn = std::find_if(keyInfo.outputs.begin(), keyInfo.outputs.end(), [&](const transaction_types::GlobalOutput &a) { return a.outputIndex >= input.out.globalOutputIndex; }); transaction_types::GlobalOutput realOutput; realOutput.outputIndex = input.out.globalOutputIndex; realOutput.targetKey = reinterpret_cast<const PublicKey &>(input.out.outputKey); auto insertedIn = keyInfo.outputs.insert(insertIn, realOutput); keyInfo.realOutput.transactionPublicKey = reinterpret_cast<const PublicKey &>(input.out.transactionPublicKey); keyInfo.realOutput.transactionIndex = static_cast<size_t>(insertedIn - keyInfo.outputs.begin()); keyInfo.realOutput.outputInTransaction = input.out.outputInTransaction; //Important! outputs in selectedTransfers and in keysInfo must have the same order! InputInfo inputInfo; inputInfo.keyInfo = std::move(keyInfo); inputInfo.walletRecord = input.wallet; keysInfo.push_back(std::move(inputInfo)); ++i; } } WalletTransactionWithTransfers WalletGreen::getTransaction(const crypto::Hash &transactionHash) const { throwIfNotInitialized(); throwIfStopped(); auto &hashIndex = m_transactions.get<TransactionIndex>(); auto it = hashIndex.find(transactionHash); if (it == hashIndex.end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND), "Transaction not found"); } WalletTransactionWithTransfers walletTransaction; walletTransaction.transaction = *it; walletTransaction.transfers = getTransactionTransfers(*it); return walletTransaction; } std::vector<TransactionsInBlockInfo> WalletGreen::getTransactions(const crypto::Hash &blockHash, size_t count) const { throwIfNotInitialized(); throwIfStopped(); auto &hashIndex = m_blockchain.get<BlockHashIndex>(); auto it = hashIndex.find(blockHash); if (it == hashIndex.end()) { return std::vector<TransactionsInBlockInfo>(); } auto heightIt = m_blockchain.project<BlockHeightIndex>(it); uint32_t blockIndex = static_cast<uint32_t>(std::distance(m_blockchain.get<BlockHeightIndex>().begin(), heightIt)); return getTransactionsInBlocks(blockIndex, count); } std::vector<DepositsInBlockInfo> WalletGreen::getDeposits(const crypto::Hash &blockHash, size_t count) const { throwIfNotInitialized(); throwIfStopped(); auto &hashIndex = m_blockchain.get<BlockHashIndex>(); auto it = hashIndex.find(blockHash); if (it == hashIndex.end()) { return std::vector<DepositsInBlockInfo>(); } auto heightIt = m_blockchain.project<BlockHeightIndex>(it); uint32_t blockIndex = static_cast<uint32_t>(std::distance(m_blockchain.get<BlockHeightIndex>().begin(), heightIt)); return getDepositsInBlocks(blockIndex, count); } std::vector<TransactionsInBlockInfo> WalletGreen::getTransactions(uint32_t blockIndex, size_t count) const { throwIfNotInitialized(); throwIfStopped(); return getTransactionsInBlocks(blockIndex, count); } std::vector<DepositsInBlockInfo> WalletGreen::getDeposits(uint32_t blockIndex, size_t count) const { throwIfNotInitialized(); throwIfStopped(); return getDepositsInBlocks(blockIndex, count); } std::vector<crypto::Hash> WalletGreen::getBlockHashes(uint32_t blockIndex, size_t count) const { throwIfNotInitialized(); throwIfStopped(); auto &index = m_blockchain.get<BlockHeightIndex>(); if (blockIndex >= index.size()) { return std::vector<crypto::Hash>(); } auto start = std::next(index.begin(), blockIndex); auto end = std::next(index.begin(), std::min(index.size(), blockIndex + count)); return std::vector<crypto::Hash>(start, end); } uint32_t WalletGreen::getBlockCount() const { throwIfNotInitialized(); throwIfStopped(); uint32_t blockCount = static_cast<uint32_t>(m_blockchain.size()); assert(blockCount != 0); return blockCount; } std::vector<WalletTransactionWithTransfers> WalletGreen::getUnconfirmedTransactions() const { throwIfNotInitialized(); throwIfStopped(); std::vector<WalletTransactionWithTransfers> result; auto lowerBound = m_transactions.get<BlockHeightIndex>().lower_bound(WALLET_UNCONFIRMED_TRANSACTION_HEIGHT); for (auto it = lowerBound; it != m_transactions.get<BlockHeightIndex>().end(); ++it) { if (it->state != WalletTransactionState::SUCCEEDED) { continue; } WalletTransactionWithTransfers transaction; transaction.transaction = *it; transaction.transfers = getTransactionTransfers(*it); result.push_back(transaction); } return result; } std::vector<size_t> WalletGreen::getDelayedTransactionIds() const { throwIfNotInitialized(); throwIfStopped(); throwIfTrackingMode(); std::vector<size_t> result; result.reserve(m_uncommitedTransactions.size()); for (const auto &kv : m_uncommitedTransactions) { result.push_back(kv.first); } return result; } void WalletGreen::start() { m_stopped = false; } void WalletGreen::stop() { m_stopped = true; m_eventOccurred.set(); } WalletEvent WalletGreen::getEvent() { throwIfNotInitialized(); throwIfStopped(); while (m_events.empty()) { m_eventOccurred.wait(); m_eventOccurred.clear(); throwIfStopped(); } WalletEvent event = std::move(m_events.front()); m_events.pop(); return event; } void WalletGreen::throwIfNotInitialized() const { if (m_state != WalletState::INITIALIZED) { throw std::system_error(make_error_code(cn::error::NOT_INITIALIZED)); } } void WalletGreen::onError(ITransfersSubscription *object, uint32_t height, std::error_code ec) { } void WalletGreen::synchronizationProgressUpdated(uint32_t processedBlockCount, uint32_t totalBlockCount) { m_dispatcher.remoteSpawn([processedBlockCount, totalBlockCount, this]() { onSynchronizationProgressUpdated(processedBlockCount, totalBlockCount); }); } void WalletGreen::synchronizationCompleted(std::error_code result) { m_dispatcher.remoteSpawn([this]() { onSynchronizationCompleted(); }); } void WalletGreen::onSynchronizationProgressUpdated(uint32_t processedBlockCount, uint32_t totalBlockCount) { assert(processedBlockCount > 0); platform_system::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } pushEvent(makeSyncProgressUpdatedEvent(processedBlockCount, totalBlockCount)); uint32_t currentHeight = processedBlockCount - 1; unlockBalances(currentHeight); } void WalletGreen::onSynchronizationCompleted() { platform_system::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } pushEvent(makeSyncCompletedEvent()); } void WalletGreen::onBlocksAdded(const crypto::PublicKey &viewPublicKey, const std::vector<crypto::Hash> &blockHashes) { m_dispatcher.remoteSpawn([this, blockHashes]() { blocksAdded(blockHashes); }); } void WalletGreen::blocksAdded(const std::vector<crypto::Hash> &blockHashes) { platform_system::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } m_blockchain.insert(m_blockchain.end(), blockHashes.begin(), blockHashes.end()); } void WalletGreen::onBlockchainDetach(const crypto::PublicKey &viewPublicKey, uint32_t blockIndex) { m_dispatcher.remoteSpawn([this, blockIndex]() { blocksRollback(blockIndex); }); } void WalletGreen::blocksRollback(uint32_t blockIndex) { platform_system::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } auto &blockHeightIndex = m_blockchain.get<BlockHeightIndex>(); blockHeightIndex.erase(std::next(blockHeightIndex.begin(), blockIndex), blockHeightIndex.end()); } void WalletGreen::onTransactionDeleteBegin(const crypto::PublicKey &viewPublicKey, crypto::Hash transactionHash) { m_dispatcher.remoteSpawn([=]() { transactionDeleteBegin(transactionHash); }); } // TODO remove void WalletGreen::transactionDeleteBegin(crypto::Hash /*transactionHash*/) { } void WalletGreen::onTransactionDeleteEnd(const crypto::PublicKey &viewPublicKey, crypto::Hash transactionHash) { m_dispatcher.remoteSpawn([=]() { transactionDeleteEnd(transactionHash); }); } // TODO remove void WalletGreen::transactionDeleteEnd(crypto::Hash transactionHash) { } void WalletGreen::unlockBalances(uint32_t height) { auto &index = m_unlockTransactionsJob.get<BlockHeightIndex>(); auto upper = index.upper_bound(height); if (index.begin() != upper) { for (auto it = index.begin(); it != upper; ++it) { updateBalance(it->container); } index.erase(index.begin(), upper); pushEvent(makeMoneyUnlockedEvent()); } } void WalletGreen::onTransactionUpdated(ITransfersSubscription * /*object*/, const crypto::Hash & /*transactionHash*/) { // Deprecated, ignore it. New event handler is onTransactionUpdated(const crypto::PublicKey&, const crypto::Hash&, const std::vector<ITransfersContainer*>&) } void WalletGreen::onTransactionUpdated( const crypto::PublicKey &, const crypto::Hash &transactionHash, const std::vector<ITransfersContainer *> &containers) { assert(!containers.empty()); TransactionInformation info; std::vector<ContainerAmounts> containerAmountsList; containerAmountsList.reserve(containers.size()); for (auto container : containers) { uint64_t inputsAmount; // Don't move this code to the following remote spawn, because it guarantees that the container has the // transaction uint64_t outputsAmount; bool found = container->getTransactionInformation(transactionHash, info, &inputsAmount, &outputsAmount); if (found) { } assert(found); ContainerAmounts containerAmounts; containerAmounts.container = container; containerAmounts.amounts.input = -static_cast<int64_t>(inputsAmount); containerAmounts.amounts.output = static_cast<int64_t>(outputsAmount); containerAmountsList.emplace_back(std::move(containerAmounts)); } m_dispatcher.remoteSpawn( [this, info, containerAmountsList] { this->transactionUpdated(info, containerAmountsList); }); } /* Insert a new deposit into the deposit index */ DepositId WalletGreen::insertNewDeposit( const TransactionOutputInformation &depositOutput, TransactionId creatingTransactionId, const Currency &currency, uint32_t height) { assert(depositOutput.type == transaction_types::OutputType::Multisignature); assert(depositOutput.term != 0); Deposit deposit; deposit.amount = depositOutput.amount; deposit.creatingTransactionId = creatingTransactionId; deposit.term = depositOutput.term; deposit.spendingTransactionId = WALLET_INVALID_TRANSACTION_ID; deposit.interest = currency.calculateInterest(deposit.amount, deposit.term, height); deposit.height = height; deposit.unlockHeight = height + depositOutput.term; deposit.locked = true; return insertDeposit(deposit, depositOutput.outputInTransaction, depositOutput.transactionHash); } DepositId WalletGreen::insertDeposit( const Deposit &deposit, size_t depositIndexInTransaction, const Hash &transactionHash) { Deposit info = deposit; info.outputInTransaction = static_cast<uint32_t>(depositIndexInTransaction); info.transactionHash = transactionHash; auto &hashIndex = m_transactions.get<TransactionIndex>(); auto it = hashIndex.find(transactionHash); if (it == hashIndex.end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND), "Transaction not found"); } WalletTransactionWithTransfers walletTransaction; walletTransaction.transaction = *it; walletTransaction.transfers = getTransactionTransfers(*it); DepositId id = m_deposits.size(); m_deposits.push_back(std::move(info)); m_logger(DEBUGGING, BRIGHT_GREEN) << "New deposit created, id " << id << ", locking " << m_currency.formatAmount(deposit.amount) << " ,for a term of " << deposit.term << " blocks, at block " << deposit.height; return id; } /* Process transactions, this covers both new transactions AND confirmed transactions */ void WalletGreen::transactionUpdated( TransactionInformation transactionInfo, const std::vector<ContainerAmounts> &containerAmountsList) { platform_system::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } size_t firstDepositId = WALLET_INVALID_DEPOSIT_ID; size_t depositCount = 0; bool updated = false; bool isNew = false; int64_t totalAmount = std::accumulate(containerAmountsList.begin(), containerAmountsList.end(), static_cast<int64_t>(0), [](int64_t sum, const ContainerAmounts &containerAmounts) { return sum + containerAmounts.amounts.input + containerAmounts.amounts.output; }); size_t transactionId; auto &hashIndex = m_transactions.get<TransactionIndex>(); auto it = hashIndex.find(transactionInfo.transactionHash); if (it != hashIndex.end()) { transactionId = std::distance(m_transactions.get<RandomAccessIndex>().begin(), m_transactions.project<RandomAccessIndex>(it)); updated |= updateWalletTransactionInfo(transactionId, transactionInfo, totalAmount); } else { isNew = true; transactionId = insertBlockchainTransaction(transactionInfo, totalAmount); m_fusionTxsCache.emplace(transactionId, isFusionTransaction(*it)); } for (auto containerAmounts : containerAmountsList) { auto newDepositOuts = containerAmounts.container->getTransactionOutputs(transactionInfo.transactionHash, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateAll); auto spentDepositOutputs = containerAmounts.container->getTransactionInputs(transactionInfo.transactionHash, ITransfersContainer::IncludeTypeDeposit); std::vector<DepositId> updatedDepositIds; /* Check for new deposits in this transaction, and create them */ for (size_t i = 0; i < newDepositOuts.size(); i++) { /* We only add confirmed deposit entries, so this condition prevents the same deposit in the deposit index during creation and during confirmation */ if (transactionInfo.blockHeight == WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { continue; } auto id = insertNewDeposit(newDepositOuts[i], transactionId, m_currency, transactionInfo.blockHeight); updatedDepositIds.push_back(id); } /* Now check for any deposit withdrawals in the transactions */ for (size_t i = 0; i < spentDepositOutputs.size(); i++) { auto depositId = getDepositId(spentDepositOutputs[i].transactionHash); assert(depositId != WALLET_INVALID_DEPOSIT_ID); if (depositId == WALLET_INVALID_DEPOSIT_ID) { throw std::invalid_argument("processSpentDeposits error: requested deposit doesn't exist"); } auto info = m_deposits[depositId]; info.spendingTransactionId = transactionId; updated |= updateWalletDepositInfo(depositId, info); } /* If there are new deposits, update the transaction information with the firstDepositId and the depositCount */ if (!updatedDepositIds.empty()) { firstDepositId = updatedDepositIds[0]; depositCount = updatedDepositIds.size(); transactionInfo.depositCount = depositCount; transactionInfo.firstDepositId = firstDepositId; updated |= updateWalletTransactionInfo(transactionId, transactionInfo, totalAmount); } } if (transactionInfo.blockHeight != cn::WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { // In some cases a transaction can be included to a block but not removed from m_uncommitedTransactions. Fix it m_uncommitedTransactions.erase(transactionId); } // Update cached balance for (auto containerAmounts : containerAmountsList) { updateBalance(containerAmounts.container); if (transactionInfo.blockHeight != cn::WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { uint32_t unlockHeight = std::max(transactionInfo.blockHeight + m_transactionSoftLockTime, static_cast<uint32_t>(transactionInfo.unlockTime)); insertUnlockTransactionJob(transactionInfo.transactionHash, unlockHeight, containerAmounts.container); } } updated |= updateTransactionTransfers(transactionId, containerAmountsList, -static_cast<int64_t>(transactionInfo.totalAmountIn), static_cast<int64_t>(transactionInfo.totalAmountOut)); if (isNew) { pushEvent(makeTransactionCreatedEvent(transactionId)); } else if (updated) { pushEvent(makeTransactionUpdatedEvent(transactionId)); } } void WalletGreen::pushEvent(const WalletEvent &event) { m_events.push(event); m_eventOccurred.set(); } size_t WalletGreen::getTransactionId(const Hash &transactionHash) const { auto it = m_transactions.get<TransactionIndex>().find(transactionHash); if (it == m_transactions.get<TransactionIndex>().end()) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } auto rndIt = m_transactions.project<RandomAccessIndex>(it); auto txId = std::distance(m_transactions.get<RandomAccessIndex>().begin(), rndIt); return txId; } size_t WalletGreen::getDepositId(const Hash &transactionHash) const { auto it = m_deposits.get<TransactionIndex>().find(transactionHash); if (it == m_deposits.get<TransactionIndex>().end()) { return WALLET_INVALID_DEPOSIT_ID; } auto rndIt = m_deposits.project<RandomAccessIndex>(it); auto depositId = std::distance(m_deposits.get<RandomAccessIndex>().begin(), rndIt); return depositId; } void WalletGreen::onTransactionDeleted(ITransfersSubscription *object, const Hash &transactionHash) { m_dispatcher.remoteSpawn([object, transactionHash, this]() { this->transactionDeleted(object, transactionHash); }); } void WalletGreen::transactionDeleted(ITransfersSubscription *object, const Hash &transactionHash) { platform_system::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } auto it = m_transactions.get<TransactionIndex>().find(transactionHash); if (it == m_transactions.get<TransactionIndex>().end()) { return; } cn::ITransfersContainer *container = &object->getContainer(); updateBalance(container); deleteUnlockTransactionJob(transactionHash); bool updated = false; m_transactions.get<TransactionIndex>().modify(it, [&updated](cn::WalletTransaction &tx) { if (tx.state == WalletTransactionState::CREATED || tx.state == WalletTransactionState::SUCCEEDED) { tx.state = WalletTransactionState::CANCELLED; updated = true; } if (tx.blockHeight != WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { tx.blockHeight = WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; updated = true; } }); if (updated) { auto transactionId = getTransactionId(transactionHash); pushEvent(makeTransactionUpdatedEvent(transactionId)); } } void WalletGreen::insertUnlockTransactionJob(const Hash &transactionHash, uint32_t blockHeight, cn::ITransfersContainer *container) { auto &index = m_unlockTransactionsJob.get<BlockHeightIndex>(); index.insert({blockHeight, container, transactionHash}); } void WalletGreen::deleteUnlockTransactionJob(const Hash &transactionHash) { auto &index = m_unlockTransactionsJob.get<TransactionHashIndex>(); index.erase(transactionHash); } void WalletGreen::startBlockchainSynchronizer() { if (!m_walletsContainer.empty() && !m_blockchainSynchronizerStarted) { m_blockchainSynchronizer.start(); m_blockchainSynchronizerStarted = true; } } void WalletGreen::stopBlockchainSynchronizer() { if (m_blockchainSynchronizerStarted) { m_blockchainSynchronizer.stop(); m_blockchainSynchronizerStarted = false; } } void WalletGreen::addUnconfirmedTransaction(const ITransactionReader &transaction) { platform_system::RemoteContext<std::error_code> context(m_dispatcher, [this, &transaction] { return m_blockchainSynchronizer.addUnconfirmedTransaction(transaction).get(); }); auto ec = context.get(); if (ec) { throw std::system_error(ec, "Failed to add unconfirmed transaction"); } } void WalletGreen::removeUnconfirmedTransaction(const crypto::Hash &transactionHash) { platform_system::RemoteContext<void> context(m_dispatcher, [this, &transactionHash] { m_blockchainSynchronizer.removeUnconfirmedTransaction(transactionHash).get(); }); context.get(); } void WalletGreen::updateBalance(cn::ITransfersContainer *container) { auto it = m_walletsContainer.get<TransfersContainerIndex>().find(container); if (it == m_walletsContainer.get<TransfersContainerIndex>().end()) { return; } bool updated = false; /* First get the available and pending balances from the container */ uint64_t actual = container->balance(ITransfersContainer::IncludeAllUnlocked); uint64_t pending = container->balance(ITransfersContainer::IncludeKeyNotUnlocked); /* Now update the overall balance (getBalance without parameters) */ if (it->actualBalance < actual) { m_actualBalance += actual - it->actualBalance; updated = true; } else { m_actualBalance -= it->actualBalance - actual; updated = true; } if (it->pendingBalance < pending) { m_pendingBalance += pending - it->pendingBalance; updated = true; } else { m_pendingBalance -= it->pendingBalance - pending; updated = true; } /* Update locked deposit balance, this will cover deposits, as well as investments since they are all deposits with different parameters */ std::vector<TransactionOutputInformation> transfers2; container->getOutputs(transfers2, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateLocked | ITransfersContainer::IncludeStateSoftLocked); std::vector<uint32_t> heights2; for (auto transfer2 : transfers2) { crypto::Hash hash2 = transfer2.transactionHash; TransactionInformation info2; bool ok2 = container->getTransactionInformation(hash2, info2, NULL, NULL); if (ok2) { heights2.push_back(info2.blockHeight); updated = true; } } uint64_t locked = calculateDepositsAmount(transfers2, m_currency, heights2); /* This updates the unlocked deposit balance, these are the deposits that have matured and can be withdrawn */ std::vector<TransactionOutputInformation> transfers; container->getOutputs(transfers, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateUnlocked); std::vector<uint32_t> heights; for (auto transfer : transfers) { crypto::Hash hash = transfer.transactionHash; TransactionInformation info; bool ok = container->getTransactionInformation(hash, info, NULL, NULL); assert(ok); heights.push_back(info.blockHeight); } uint64_t unlocked = calculateDepositsAmount(transfers, m_currency, heights); /* Now do the same thing for overall deposit balances */ if (it->lockedDepositBalance < locked) { m_lockedDepositBalance += locked - it->lockedDepositBalance; updated = true; } else { m_lockedDepositBalance -= it->lockedDepositBalance - locked; updated = true; } if (it->unlockedDepositBalance < unlocked) { m_unlockedDepositBalance += unlocked - it->unlockedDepositBalance; updated = true; } else { m_unlockedDepositBalance -= it->unlockedDepositBalance - unlocked; updated = true; } /* Write any changes to the wallet balances to the container */ if (updated) { m_walletsContainer.get<TransfersContainerIndex>().modify(it, [actual, pending, locked, unlocked](WalletRecord &wallet) { wallet.actualBalance = actual; wallet.pendingBalance = pending; wallet.lockedDepositBalance = locked; wallet.unlockedDepositBalance = unlocked; }); /* Keep the logging to debugging */ m_logger(DEBUGGING, BRIGHT_WHITE) << "Wallet balance updated, address " << m_currency.accountAddressAsString({it->spendPublicKey, m_viewPublicKey}) << ", actual " << m_currency.formatAmount(it->actualBalance) << ", pending " << m_currency.formatAmount(it->pendingBalance); m_logger(DEBUGGING, BRIGHT_WHITE) << "Container balance updated, actual " << m_currency.formatAmount(m_actualBalance) << ", pending " << m_currency.formatAmount(m_pendingBalance) << ", locked deposits " << m_currency.formatAmount(m_lockedDepositBalance) << ",unlocked deposits " << m_currency.formatAmount(m_unlockedDepositBalance); } } const WalletRecord &WalletGreen::getWalletRecord(const PublicKey &key) const { auto it = m_walletsContainer.get<KeysIndex>().find(key); if (it == m_walletsContainer.get<KeysIndex>().end()) { throw std::system_error(make_error_code(error::WALLET_NOT_FOUND)); } return *it; } const WalletRecord &WalletGreen::getWalletRecord(const std::string &address) const { cn::AccountPublicAddress pubAddr = parseAddress(address); return getWalletRecord(pubAddr.spendPublicKey); } const WalletRecord &WalletGreen::getWalletRecord(cn::ITransfersContainer *container) const { auto it = m_walletsContainer.get<TransfersContainerIndex>().find(container); if (it == m_walletsContainer.get<TransfersContainerIndex>().end()) { throw std::system_error(make_error_code(error::WALLET_NOT_FOUND)); } return *it; } cn::AccountPublicAddress WalletGreen::parseAddress(const std::string &address) const { cn::AccountPublicAddress pubAddr; if (!m_currency.parseAccountAddressString(address, pubAddr)) { throw std::system_error(make_error_code(error::BAD_ADDRESS)); } return pubAddr; } void WalletGreen::throwIfStopped() const { if (m_stopped) { throw std::system_error(make_error_code(error::OPERATION_CANCELLED)); } } void WalletGreen::throwIfTrackingMode() const { if (getTrackingMode() == WalletTrackingMode::TRACKING) { throw std::system_error(make_error_code(error::TRACKING_MODE)); } } WalletGreen::WalletTrackingMode WalletGreen::getTrackingMode() const { if (m_walletsContainer.get<RandomAccessIndex>().empty()) { return WalletTrackingMode::NO_ADDRESSES; } return m_walletsContainer.get<RandomAccessIndex>().begin()->spendSecretKey == NULL_SECRET_KEY ? WalletTrackingMode::TRACKING : WalletTrackingMode::NOT_TRACKING; } size_t WalletGreen::createFusionTransaction( uint64_t threshold, uint64_t mixin, const std::vector<std::string> &sourceAddresses, const std::string &destinationAddress) { size_t id = WALLET_INVALID_TRANSACTION_ID; tools::ScopeExit releaseContext([this, &id] { m_dispatcher.yield(); if (id != WALLET_INVALID_TRANSACTION_ID) { auto &tx = m_transactions[id]; } }); platform_system::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); validateSourceAddresses(sourceAddresses); validateChangeDestination(sourceAddresses, destinationAddress, true); const size_t MAX_FUSION_OUTPUT_COUNT = 8; uint64_t fusionTreshold = m_currency.defaultDustThreshold(); if (threshold <= fusionTreshold) { throw std::system_error(make_error_code(error::THRESHOLD_TOO_LOW)); } if (m_walletsContainer.get<RandomAccessIndex>().size() == 0) { throw std::system_error(make_error_code(error::MINIMUM_ONE_ADDRESS)); } size_t estimatedFusionInputsCount = m_currency.getApproximateMaximumInputCount(m_currency.fusionTxMaxSize(), MAX_FUSION_OUTPUT_COUNT, mixin); if (estimatedFusionInputsCount < m_currency.fusionTxMinInputCount()) { throw std::system_error(make_error_code(error::MIXIN_COUNT_TOO_BIG)); } auto fusionInputs = pickRandomFusionInputs(sourceAddresses, threshold, m_currency.fusionTxMinInputCount(), estimatedFusionInputsCount); if (fusionInputs.size() < m_currency.fusionTxMinInputCount()) { //nothing to optimize throw std::system_error(make_error_code(error::NOTHING_TO_OPTIMIZE)); return WALLET_INVALID_TRANSACTION_ID; } typedef cn::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount; std::vector<outs_for_amount> mixinResult; if (mixin != 0) { requestMixinOuts(fusionInputs, mixin, mixinResult); } std::vector<InputInfo> keysInfo; prepareInputs(fusionInputs, mixinResult, mixin, keysInfo); AccountPublicAddress destination = getChangeDestination(destinationAddress, sourceAddresses); std::unique_ptr<ITransaction> fusionTransaction; size_t transactionSize; int round = 0; uint64_t transactionAmount; do { if (round != 0) { fusionInputs.pop_back(); keysInfo.pop_back(); } uint64_t inputsAmount = std::accumulate(fusionInputs.begin(), fusionInputs.end(), static_cast<uint64_t>(0), [](uint64_t amount, const OutputToTransfer &input) { return amount + input.out.amount; }); transactionAmount = inputsAmount; ReceiverAmounts decomposedOutputs = decomposeFusionOutputs(destination, inputsAmount); assert(decomposedOutputs.amounts.size() <= MAX_FUSION_OUTPUT_COUNT); crypto::SecretKey txkey; std::vector<WalletMessage> messages; fusionTransaction = makeTransaction(std::vector<ReceiverAmounts>{decomposedOutputs}, keysInfo, messages, "", 0, txkey); transactionSize = getTransactionSize(*fusionTransaction); ++round; } while ((transactionSize > m_currency.fusionTxMaxSize()) && (fusionInputs.size() >= m_currency.fusionTxMinInputCount())); if (fusionInputs.size() < m_currency.fusionTxMinInputCount()) { throw std::system_error(make_error_code(error::MINIMUM_INPUT_COUNT)); } id = validateSaveAndSendTransaction(*fusionTransaction, {}, true, true); return id; } WalletGreen::ReceiverAmounts WalletGreen::decomposeFusionOutputs(const AccountPublicAddress &address, uint64_t inputsAmount) { WalletGreen::ReceiverAmounts outputs; outputs.receiver = address; decomposeAmount(inputsAmount, 0, outputs.amounts); std::sort(outputs.amounts.begin(), outputs.amounts.end()); return outputs; } bool WalletGreen::isFusionTransaction(size_t transactionId) const { throwIfNotInitialized(); throwIfStopped(); if (m_transactions.size() <= transactionId) { throw std::system_error(make_error_code(cn::error::INDEX_OUT_OF_RANGE)); } auto isFusionIter = m_fusionTxsCache.find(transactionId); if (isFusionIter != m_fusionTxsCache.end()) { return isFusionIter->second; } bool result = isFusionTransaction(m_transactions.get<RandomAccessIndex>()[transactionId]); m_fusionTxsCache.emplace(transactionId, result); return result; } bool WalletGreen::isFusionTransaction(const WalletTransaction &walletTx) const { if (walletTx.fee != 0) { return false; } uint64_t inputsSum = 0; uint64_t outputsSum = 0; std::vector<uint64_t> outputsAmounts; std::vector<uint64_t> inputsAmounts; TransactionInformation txInfo; bool gotTx = false; const auto &walletsIndex = m_walletsContainer.get<RandomAccessIndex>(); for (const WalletRecord &wallet : walletsIndex) { for (const TransactionOutputInformation &output : wallet.container->getTransactionOutputs(walletTx.hash, ITransfersContainer::IncludeTypeKey | ITransfersContainer::IncludeStateAll)) { if (outputsAmounts.size() <= output.outputInTransaction) { outputsAmounts.resize(output.outputInTransaction + 1, 0); } assert(output.amount != 0); assert(outputsAmounts[output.outputInTransaction] == 0); outputsAmounts[output.outputInTransaction] = output.amount; outputsSum += output.amount; } for (const TransactionOutputInformation &input : wallet.container->getTransactionInputs(walletTx.hash, ITransfersContainer::IncludeTypeKey)) { inputsSum += input.amount; inputsAmounts.push_back(input.amount); } if (!gotTx) { gotTx = wallet.container->getTransactionInformation(walletTx.hash, txInfo); } } if (!gotTx) { return false; } if (outputsSum != inputsSum || outputsSum != txInfo.totalAmountOut || inputsSum != txInfo.totalAmountIn) { return false; } else { return m_currency.isFusionTransaction(inputsAmounts, outputsAmounts, 0); //size = 0 here because can't get real size of tx in wallet. } } void WalletGreen::validateChangeDestination(const std::vector<std::string> &sourceAddresses, const std::string &changeDestination, bool isFusion) const { std::string message; if (changeDestination.empty()) { if (sourceAddresses.size() > 1 || (sourceAddresses.empty() && m_walletsContainer.size() > 1)) { message = std::string(isFusion ? "Destination" : "Change destination") + " address is necessary"; m_logger(ERROR, BRIGHT_RED) << message << ". Source addresses size=" << sourceAddresses.size() << ", wallets count=" << m_walletsContainer.size(); throw std::system_error(make_error_code(isFusion ? error::DESTINATION_ADDRESS_REQUIRED : error::CHANGE_ADDRESS_REQUIRED), message); } } else { if (!cn::validateAddress(changeDestination, m_currency)) { message = std::string("Bad ") + (isFusion ? "destination" : "change destination") + " address: " + changeDestination; m_logger(ERROR, BRIGHT_RED) << message; throw std::system_error(make_error_code(cn::error::BAD_ADDRESS), message); } if (!isMyAddress(changeDestination)) { message = std::string(isFusion ? "Destination" : "Change destination") + " address is not found in current container: " + changeDestination; m_logger(ERROR, BRIGHT_RED) << message; throw std::system_error(make_error_code(isFusion ? error::DESTINATION_ADDRESS_NOT_FOUND : error::CHANGE_ADDRESS_NOT_FOUND), message); } } } void WalletGreen::validateSourceAddresses(const std::vector<std::string> &sourceAddresses) const { validateAddresses(sourceAddresses); auto badAddr = std::find_if(sourceAddresses.begin(), sourceAddresses.end(), [this](const std::string &addr) { return !isMyAddress(addr); }); if (badAddr != sourceAddresses.end()) { throw std::system_error(make_error_code(error::BAD_ADDRESS), "Source address must belong to current container: " + *badAddr); } } IFusionManager::EstimateResult WalletGreen::estimate(uint64_t threshold, const std::vector<std::string> &sourceAddresses) const { platform_system::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfStopped(); validateSourceAddresses(sourceAddresses); IFusionManager::EstimateResult result{0, 0}; auto walletOuts = sourceAddresses.empty() ? pickWalletsWithMoney() : pickWallets(sourceAddresses); std::array<size_t, std::numeric_limits<uint64_t>::digits10 + 1> bucketSizes; bucketSizes.fill(0); for (size_t walletIndex = 0; walletIndex < walletOuts.size(); ++walletIndex) { for (auto &out : walletOuts[walletIndex].outs) { uint8_t powerOfTen = 0; if (m_currency.isAmountApplicableInFusionTransactionInput(out.amount, threshold, powerOfTen, m_node.getLastKnownBlockHeight())) { assert(powerOfTen < std::numeric_limits<uint64_t>::digits10 + 1); bucketSizes[powerOfTen]++; } } result.totalOutputCount += walletOuts[walletIndex].outs.size(); } for (auto bucketSize : bucketSizes) { if (bucketSize >= m_currency.fusionTxMinInputCount()) { result.fusionReadyCount += bucketSize; } } return result; } std::vector<WalletGreen::OutputToTransfer> WalletGreen::pickRandomFusionInputs(const std::vector<std::string> &addresses, uint64_t threshold, size_t minInputCount, size_t maxInputCount) { std::vector<WalletGreen::OutputToTransfer> allFusionReadyOuts; auto walletOuts = addresses.empty() ? pickWalletsWithMoney() : pickWallets(addresses); std::array<size_t, std::numeric_limits<uint64_t>::digits10 + 1> bucketSizes; bucketSizes.fill(0); for (size_t walletIndex = 0; walletIndex < walletOuts.size(); ++walletIndex) { for (auto &out : walletOuts[walletIndex].outs) { uint8_t powerOfTen = 0; if (m_currency.isAmountApplicableInFusionTransactionInput(out.amount, threshold, powerOfTen, m_node.getLastKnownBlockHeight())) { allFusionReadyOuts.push_back({std::move(out), walletOuts[walletIndex].wallet}); assert(powerOfTen < std::numeric_limits<uint64_t>::digits10 + 1); bucketSizes[powerOfTen]++; } } } //now, pick the bucket std::vector<uint8_t> bucketNumbers(bucketSizes.size()); std::iota(bucketNumbers.begin(), bucketNumbers.end(), 0); std::shuffle(bucketNumbers.begin(), bucketNumbers.end(), std::default_random_engine{crypto::rand<std::default_random_engine::result_type>()}); size_t bucketNumberIndex = 0; for (; bucketNumberIndex < bucketNumbers.size(); ++bucketNumberIndex) { if (bucketSizes[bucketNumbers[bucketNumberIndex]] >= minInputCount) { break; } } if (bucketNumberIndex == bucketNumbers.size()) { return {}; } size_t selectedBucket = bucketNumbers[bucketNumberIndex]; assert(selectedBucket < std::numeric_limits<uint64_t>::digits10 + 1); assert(bucketSizes[selectedBucket] >= minInputCount); uint64_t lowerBound = 1; for (size_t i = 0; i < selectedBucket; ++i) { lowerBound *= 10; } uint64_t upperBound = selectedBucket == std::numeric_limits<uint64_t>::digits10 ? UINT64_MAX : lowerBound * 10; std::vector<WalletGreen::OutputToTransfer> selectedOuts; selectedOuts.reserve(bucketSizes[selectedBucket]); for (size_t outIndex = 0; outIndex < allFusionReadyOuts.size(); ++outIndex) { if (allFusionReadyOuts[outIndex].out.amount >= lowerBound && allFusionReadyOuts[outIndex].out.amount < upperBound) { selectedOuts.push_back(std::move(allFusionReadyOuts[outIndex])); } } assert(selectedOuts.size() >= minInputCount); auto outputsSortingFunction = [](const OutputToTransfer &l, const OutputToTransfer &r) { return l.out.amount < r.out.amount; }; if (selectedOuts.size() <= maxInputCount) { std::sort(selectedOuts.begin(), selectedOuts.end(), outputsSortingFunction); return selectedOuts; } ShuffleGenerator<size_t, crypto::random_engine<size_t>> generator(selectedOuts.size()); std::vector<WalletGreen::OutputToTransfer> trimmedSelectedOuts; trimmedSelectedOuts.reserve(maxInputCount); for (size_t i = 0; i < maxInputCount; ++i) { trimmedSelectedOuts.push_back(std::move(selectedOuts[generator()])); } std::sort(trimmedSelectedOuts.begin(), trimmedSelectedOuts.end(), outputsSortingFunction); return trimmedSelectedOuts; } std::vector<DepositsInBlockInfo> WalletGreen::getDepositsInBlocks(uint32_t blockIndex, size_t count) const { if (count == 0) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS), "blocks count must be greater than zero"); } std::vector<DepositsInBlockInfo> result; if (blockIndex >= m_blockchain.size()) { return result; } auto &blockHeightIndex = m_deposits.get<BlockHeightIndex>(); uint32_t stopIndex = static_cast<uint32_t>(std::min(m_blockchain.size(), blockIndex + count)); for (uint32_t height = blockIndex; height < stopIndex; ++height) { DepositsInBlockInfo info; info.blockHash = m_blockchain[height]; auto lowerBound = blockHeightIndex.lower_bound(height); auto upperBound = blockHeightIndex.upper_bound(height); for (auto it = lowerBound; it != upperBound; ++it) { Deposit deposit; deposit = *it; info.deposits.emplace_back(std::move(deposit)); } result.emplace_back(std::move(info)); } return result; } std::vector<TransactionsInBlockInfo> WalletGreen::getTransactionsInBlocks(uint32_t blockIndex, size_t count) const { if (count == 0) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS), "blocks count must be greater than zero"); } std::vector<TransactionsInBlockInfo> result; if (blockIndex >= m_blockchain.size()) { return result; } auto &blockHeightIndex = m_transactions.get<BlockHeightIndex>(); uint32_t stopIndex = static_cast<uint32_t>(std::min(m_blockchain.size(), blockIndex + count)); for (uint32_t height = blockIndex; height < stopIndex; ++height) { TransactionsInBlockInfo info; info.blockHash = m_blockchain[height]; auto lowerBound = blockHeightIndex.lower_bound(height); auto upperBound = blockHeightIndex.upper_bound(height); for (auto it = lowerBound; it != upperBound; ++it) { if (it->state != WalletTransactionState::SUCCEEDED) { continue; } WalletTransactionWithTransfers transaction; transaction.transaction = *it; transaction.transfers = getTransactionTransfers(*it); info.transactions.emplace_back(std::move(transaction)); } result.emplace_back(std::move(info)); } return result; } crypto::Hash WalletGreen::getBlockHashByIndex(uint32_t blockIndex) const { assert(blockIndex < m_blockchain.size()); return m_blockchain.get<BlockHeightIndex>()[blockIndex]; } std::vector<WalletTransfer> WalletGreen::getTransactionTransfers(const WalletTransaction &transaction) const { auto &transactionIdIndex = m_transactions.get<RandomAccessIndex>(); auto it = transactionIdIndex.iterator_to(transaction); assert(it != transactionIdIndex.end()); size_t transactionId = std::distance(transactionIdIndex.begin(), it); size_t transfersCount = getTransactionTransferCount(transactionId); std::vector<WalletTransfer> result; result.reserve(transfersCount); for (size_t transferId = 0; transferId < transfersCount; ++transferId) { result.push_back(getTransactionTransfer(transactionId, transferId)); } return result; } void WalletGreen::filterOutTransactions(WalletTransactions &transactions, WalletTransfers &transfers, std::function<bool(const WalletTransaction &)> &&pred) const { size_t cancelledTransactions = 0; transactions.reserve(m_transactions.size()); transfers.reserve(m_transfers.size()); auto &index = m_transactions.get<RandomAccessIndex>(); size_t transferIdx = 0; for (size_t i = 0; i < m_transactions.size(); ++i) { const WalletTransaction &transaction = index[i]; if (pred(transaction)) { ++cancelledTransactions; while (transferIdx < m_transfers.size() && m_transfers[transferIdx].first == i) { ++transferIdx; } } else { transactions.emplace_back(transaction); while (transferIdx < m_transfers.size() && m_transfers[transferIdx].first == i) { transfers.emplace_back(i - cancelledTransactions, m_transfers[transferIdx].second); ++transferIdx; } } } } void WalletGreen::getViewKeyKnownBlocks(const crypto::PublicKey &viewPublicKey) { std::vector<crypto::Hash> blockchain = m_synchronizer.getViewKeyKnownBlocks(m_viewPublicKey); m_blockchain.insert(m_blockchain.end(), blockchain.begin(), blockchain.end()); } ///pre: changeDestinationAddress belongs to current container ///pre: source address belongs to current container cn::AccountPublicAddress WalletGreen::getChangeDestination(const std::string &changeDestinationAddress, const std::vector<std::string> &sourceAddresses) const { if (!changeDestinationAddress.empty()) { return parseAccountAddressString(changeDestinationAddress, m_currency); } if (m_walletsContainer.size() == 1) { return AccountPublicAddress{m_walletsContainer.get<RandomAccessIndex>()[0].spendPublicKey, m_viewPublicKey}; } assert(sourceAddresses.size() == 1 && isMyAddress(sourceAddresses[0])); return parseAccountAddressString(sourceAddresses[0], m_currency); } bool WalletGreen::isMyAddress(const std::string &addressString) const { cn::AccountPublicAddress address = parseAccountAddressString(addressString, m_currency); return m_viewPublicKey == address.viewPublicKey && m_walletsContainer.get<KeysIndex>().count(address.spendPublicKey) != 0; } void WalletGreen::deleteContainerFromUnlockTransactionJobs(const ITransfersContainer *container) { for (auto it = m_unlockTransactionsJob.begin(); it != m_unlockTransactionsJob.end();) { if (it->container == container) { it = m_unlockTransactionsJob.erase(it); } else { ++it; } } } std::vector<size_t> WalletGreen::deleteTransfersForAddress(const std::string &address, std::vector<size_t> &deletedTransactions) { assert(!address.empty()); int64_t deletedInputs = 0; int64_t deletedOutputs = 0; int64_t unknownInputs = 0; bool transfersLeft = false; size_t firstTransactionTransfer = 0; std::vector<size_t> updatedTransactions; for (size_t i = 0; i < m_transfers.size(); ++i) { WalletTransfer &transfer = m_transfers[i].second; if (transfer.address == address) { if (transfer.amount >= 0) { deletedOutputs += transfer.amount; } else { deletedInputs += transfer.amount; transfer.address = ""; } } else if (transfer.address.empty()) { if (transfer.amount < 0) { unknownInputs += transfer.amount; } } else if (isMyAddress(transfer.address)) { transfersLeft = true; } size_t transactionId = m_transfers[i].first; if ((i == m_transfers.size() - 1) || (transactionId != m_transfers[i + 1].first)) { //the last transfer for current transaction size_t transfersBeforeMerge = m_transfers.size(); if (deletedInputs != 0) { adjustTransfer(transactionId, firstTransactionTransfer, "", deletedInputs + unknownInputs); } assert(transfersBeforeMerge >= m_transfers.size()); i -= transfersBeforeMerge - m_transfers.size(); auto &randomIndex = m_transactions.get<RandomAccessIndex>(); randomIndex.modify(std::next(randomIndex.begin(), transactionId), [transfersLeft, deletedInputs, deletedOutputs](WalletTransaction &transaction) { transaction.totalAmount -= deletedInputs + deletedOutputs; if (!transfersLeft) { transaction.state = WalletTransactionState::DELETED; } }); if (!transfersLeft) { deletedTransactions.push_back(transactionId); } if (deletedInputs != 0 || deletedOutputs != 0) { updatedTransactions.push_back(transactionId); } //reset values for next transaction deletedInputs = 0; deletedOutputs = 0; unknownInputs = 0; transfersLeft = false; firstTransactionTransfer = i + 1; } } return updatedTransactions; } size_t WalletGreen::getTxSize(const TransactionParameters &sendingTransaction) { platform_system::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); cn::AccountPublicAddress changeDestination = getChangeDestination(sendingTransaction.changeDestination, sendingTransaction.sourceAddresses); std::vector<WalletOuts> wallets; if (!sendingTransaction.sourceAddresses.empty()) { wallets = pickWallets(sendingTransaction.sourceAddresses); } else { wallets = pickWalletsWithMoney(); } PreparedTransaction preparedTransaction; crypto::SecretKey txSecretKey; prepareTransaction( std::move(wallets), sendingTransaction.destinations, sendingTransaction.messages, sendingTransaction.fee, sendingTransaction.mixIn, sendingTransaction.extra, sendingTransaction.unlockTimestamp, sendingTransaction.donation, changeDestination, preparedTransaction, txSecretKey); BinaryArray transactionData = preparedTransaction.transaction->getTransactionData(); return transactionData.size(); } void WalletGreen::deleteFromUncommitedTransactions(const std::vector<size_t> &deletedTransactions) { for (auto transactionId : deletedTransactions) { m_uncommitedTransactions.erase(transactionId); } } void WalletGreen::clearCacheAndShutdown() { if (m_walletsContainer.size() != 0) { m_synchronizer.unsubscribeConsumerNotifications(m_viewPublicKey, this); } stopBlockchainSynchronizer(); m_blockchainSynchronizer.removeObserver(this); clearCaches(true, true); m_walletsContainer.clear(); shutdown(); } } //namespace cn
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef MODULES_UTIL_OPDATA_UTF8_H #define MODULES_UTIL_OPDATA_UTF8_H #include "modules/opdata/OpData.h" #include "modules/opdata/UniString.h" #include "modules/unicode/utf8.h" /** Convert a UTF-8 encoded OpData string to or from a UTF-16 encoded UniString. * * Example: * \code * UniString foo_uni; * RETURN_IF_ERROR(foo_uni.SetConstData(UNI_L("foo"))); * OpData foo_utf8; * RETURN_IF_ERROR(UTF8OpData::FromUniString(foo_uni, foo_utf8)); * \endcode */ class UTF8OpData { public: /** Converts the specified \c source from UTF-8 encoding to the specified * UniString \c dest. * * @param source is the OpData that contains a UTF-8 encoded string. * @param dest receives the UTF-16 encoded string. Note that this operation * appends the \c source to \c dest. So it is possible to append * several UTF-8 encoded OpData strings to one UniString by calling * this method several times on the same \c dest. * @retval OpStatus::OK on success. * @retval OpStatus::ERR_NO_MEMORY if there was not enough memory to * complete the operation. In this case dest may contain a partially * converted string. * @retval OpStatus::ERR_OUT_OF_RANGE if the specified source string did not * contain a valid UTF-8 string. This can happen, if the string * ends in the middle of a multi-byte sequence. */ static OP_STATUS ToUniString(const OpData& source, UniString& dest); /** Converts the specified UniString \c source to a UTF-8 encoded string in * the specified OpData \c dest. * * @param source is the UniString to convert to UTF-8 encoding. * @param dest receives the UTF-8 encoded string. Note that this operation * appends the \c source to \c dest. So it is possible to append * several UniString instances to one UTF-8 encoded OpData string by * calling this method several times on the same \c dest. * @retval OpStatus::OK on success. * @retval OpStatus::ERR_NO_MEMORY if there was not enough memory to * complete the operation. In this case dest may contain a partially * converted string. */ static OP_STATUS FromUniString(const UniString& source, OpData& dest); /** Compares the specified OpData UTF-8 encoded string with the specified * UniString \c other. * * @param utf8 contains a UTF-8 encoded string. * @param other is the UniString to compare \c utf8 with. * @retval OpBoolean::IS_TRUE if both strings are equal. * @retval OpBoolean::IS_FALSE if the strings differ. * @retval OpStatus::ERR_OUT_OF_RANGE if the specified source string did not * contain a valid UTF-8 string. This can happen, if the string * ends in the middle of a multi-byte sequence. * @retval OpStatus::ERR_NO_MEMORY if there was not enough memory to convert * the strings, so we could not decide if both strings are equal. */ static OP_BOOLEAN CompareWith(OpData utf8, UniString other); }; #endif // MODULES_UTIL_OPDATA_UTF8_H
#include "myUtils.h" #include<iostream> #ifdef _WIN32 #include <direct.h> #include <conio.h> #define GetCurrentDir _getcwd #else #include<dirent.h> #include <unistd.h> #define GetCurrentDir getcwd #include "patch_namespace.h" #endif #include "Mat_to_binary.h" #include "dirent.h" extern string Sys_language; namespace myUtils { // su windows non server xkè il comando system pausecambia da solo in base alla lingua... void getSysLanguage(string& Sys_language) { char lang[10]; char* p; p = lang; //cout<<setlocale(LC_CTYPE, "")<<endl; for (int i = 0; i<5;i++) { p[i] = setlocale(LC_CTYPE, "")[i]; //cout<<p[i]; }//cout<<endl; string L = lang; //L=L.substr(0,L.length()-1); std::transform(L.begin(), L.end(), L.begin(), ::toupper); L = L.substr(0, 2); //cout<<L<<endl; if (L == "IT") Sys_language = "IT"; else Sys_language = "EN"; //cout<<"sys: "<<Sys_language<<endl; } void system_pause(){ #ifndef WIN32_ // Considero solo italiano e inglese //cout<<"lang: "<<Sys_language<<endl; if(Sys_language=="IT"){ //std::cin.ignore(1024, '\n'); cout << "Premere invio per continuare..."; std::cin.get(); }else{ cout << "Press enter to continue..."; std::cin.get(); } #else system("pause"); #endif } #ifdef WIN32 void MyEntry() { // customized starting point printf("Premere un tasto per iniziare:\n"); _getch(); } void MyQuit() // customized ending point { printf("Premere un tasto per terminare:\n"); _getch(); _getch(); } void myExit_Error() { printf("Esecuziona terminata con errore. Permi un tasto per uscire immediatamente.\n"); _getch(); } #endif void DeleteSeveralFile(string FILE_LQP, string out) { //thesis::delete_file(cluCetenter.c_str()); thesis::delete_file(FILE_LQP.c_str()); thesis::delete_file(out.c_str()); } void CleanDirectory(string directory, string directory_database) { bool c = thesis::isDirectory(directory); if (c == 0) thesis::make_dir(directory.c_str()); else { // delete_file mi cancella solo i file in una cartella se i file sono contenuti in una cartella non li cancella, allora la cancello tutta e la ricreo vuota thesis::delete_folder(directory.c_str()); thesis::make_dir(directory.c_str()); } //vector<cv::Mat> featureMaps; //vector<float> featureVector; // controlla se esiste o meno la directory in cui salvare le immagini, se non esiste la crea... c = thesis::isDirectory(directory_database); if (c == 0) thesis::make_dir(directory_database.c_str()); else // cancella tutti i file nella directory... thesis::delete_file(directory_database.c_str()); } #ifdef WIN32 bool timeData(string& Time, string& Data, int Time_calc, int Data_calc) { time_t rawtime; struct tm * timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "%d-%m-%Y_%I_%M_%S", timeinfo); std::string time(buffer); if (Time_calc == 1 && Data_calc == 1) { // crea le folder solo se devo calcolare la data Data = time.substr(0, time.find('_')); //cout << data << endl; if (thesis::isDirectory("Database_Normalized") == 0) { //if (thesis::isDirectory("Database\\") == 0) thesis::make_dir("Database_Normalized"); Time = time.substr(time.find('_') + 1, time.length()); return false; } if (thesis::isDirectory(("Database_Normalized\\" + Data + "\\").c_str()) == 0) { // if (thesis::isDirectory(("Database\\" + Data + "\\").c_str()) == 0) //thesis::make_dir(("Database\\" + Data + "\\").c_str()); Time = time.substr(time.find('_') + 1, time.length()); //return false; } //mkdir(("frames/"+data).c_str()); //system(("mkdir -p /frames/" + data).c_str()); Time = time.substr(time.find('_') + 1, time.length()); } else if (Time_calc == 1 && Data_calc == 0) Time = time.substr(time.find('_') + 1, time.length()); else if (Time_calc == 0 && Data_calc == 1) { Data = time.substr(0, time.find('_')); if (thesis::isDirectory(("frames" + Data + "\\").c_str()) == 0) //if (thesis::isDirectory(("frames\\" + Data + "\\").c_str()) == 0) thesis::make_dir(("frames\\" + Data + "\\").c_str()); // thesis::make_dir(("frames\\" + Data + "\\").c_str()); } } #else bool timeData(string& Time, string& Data, int Time_calc, int Data_calc) { time_t rawtime; struct tm * timeinfo; char buffer[80]; time(&rawtime); timeinfo = localtime(&rawtime); strftime(buffer, 80, "%d-%m-%Y_%I_%M_%S", timeinfo); std::string time(buffer); if (Time_calc == 1 && Data_calc == 1) { // crea le folder solo se devo calcolare la data Data = time.substr(0, time.find('_')); //cout << data << endl; if (thesis::isDirectory("Database_Normalized") == 0){ //if (thesis::isDirectory("Database\\") == 0) thesis::make_dir("Database_Normalized"); Time = time.substr(time.find('_') + 1, time.length()); return false; } if (thesis::isDirectory(("Database_Normalized/" + Data + "/").c_str()) == 0){ // if (thesis::isDirectory(("Database\\" + Data + "\\").c_str()) == 0) //thesis::make_dir(("Database_Normalized/" + Data + "/").c_str()); //thesis::make_dir(("Database\\" + Data + "\\").c_str()); Time = time.substr(time.find('_') + 1, time.length()); //return false; } //mkdir(("frames/"+data).c_str()); //system(("mkdir -p /frames/" + data).c_str()); Time = time.substr(time.find('_') + 1, time.length()); } else if (Time_calc == 1 && Data_calc == 0) Time = time.substr(time.find('_') + 1, time.length()); else if (Time_calc == 0 && Data_calc == 1) { Data = time.substr(0, time.find('_')); if (thesis::isDirectory(("frames" + Data + "/").c_str()) == 0) //if (thesis::isDirectory(("frames\\" + Data + "\\").c_str()) == 0) thesis::make_dir(("frames/" + Data + "/").c_str()); // thesis::make_dir(("frames\\" + Data + "\\").c_str()); } return true; } #endif #ifdef WIN32 #pragma comment(lib, "Winmm.lib") // for the sound... void playSound(string file) { char file_to_play[200]; sprintf(file_to_play, "resources\\sounds\\%s", file.c_str()); PlaySound(file_to_play, NULL, SND_FILENAME); //SND_FILENAME or SND_LOOP } #else void playSound(string file) { char file_to_play[200]; sprintf(file_to_play, "aplay resources/sounds/%s --quiet",file.c_str()); //cout<<file_to_play<<endl; system(file_to_play); //system("aplay resources/sounds/camera_shutter_cutted.wav --quiet"); } #endif cv::Mat LoadMatrix(string B, int colNum, int rowNum) { ifstream input; input.open(B.c_str()); float *Data_array = new float[rowNum*colNum]; //float sum1 = 0.0; for (int row = 0; row < rowNum; row++) { for (int col = 0; col < colNum; col++) { input >> *(Data_array + colNum * row + col); //sum1 = sum1 + *(Data_array + colNum * row + col); //cout << *(Data_array + colNum * row + col) <<" "; } } //cout << "SUM1 --- : " << sum1 << endl; //system("pause"); input.close(); cv::Mat Matrix = cv::Mat(1, rowNum*colNum, CV_32FC1, Data_array); delete[] Data_array; return Matrix; } void CleanActions(string directory) { bool c = thesis::isDirectory(directory); if (c == 1) { // delete_file mi cancella solo i file in una cartella se i file sono contenuti in una cartella non li cancella, allora la cancello tutta e la ricreo vuota thesis::delete_folder(directory.c_str()); thesis::make_dir(directory.c_str()); } myUtils::DeleteSeveralFile("LQP_features.txt", "LQP_feautures_Backup.txt"); } void copyFile(string file_toCopy, string file_whereCopyFile1) { fstream stream1("LQP_features.txt"); ofstream stream2("LQP_feautures_Backup.txt", ios::app); stream2 << stream1.rdbuf(); //out << stream1.rdbuf(); stream1.close(), stream2.close(); } std::vector<float> loadVectorKnownSize(std::ifstream& in, int size) { Mat MeanV=Mat(); bool c = readMatBinary(in, MeanV); in.close(); //MeanV=MeanV.reshape(1, 20); cout << "MeanV size: "<< MeanV.size() << endl; std::vector<float> newVector(size); float* k; k= &MeanV.at<float>(0); for (int i=0; i<size; i++) newVector[i] = k[i]; //cout << "VEC size: " << newVector.size() << endl; //for (int i = 0; i < newVector.size(); i++) //cout << newVector[i]<<" "; return newVector; } std::vector<float> loadVector(string nameFileToSaveAsVector) { std::ifstream in; in.open(nameFileToSaveAsVector.c_str(), std::ios_base::binary); Mat MeanV = Mat(); bool c = readMatBinary(in, MeanV); in.close(); //MeanV=MeanV.reshape(1, 20); //cout << "MeanV size: "<< MeanV.size() << endl; std::vector<float> newVector; float* k; k = &MeanV.at<float>(0); //for (int i=0; i<4; i++) int i = 0; while (1) { newVector.push_back(k[i]); i++; if (k[i] == NULL) break; } //cout << "VEC size: " << newVector.size() << endl; //for (int i = 0; i < newVector.size(); i++) //cout << newVector[i]<<" "; return newVector; } void saveVector(string nameFileToSaveAsVector, std::vector<float> myVector) { // ANDREBBE FATTO UN TEMPLATE..... Mat V = Mat(myVector, 1); std::ofstream infile; infile.open(nameFileToSaveAsVector.c_str(), std::ios_base::binary); bool c = SaveMatBinary_2(infile, V); infile.close(); } bool fexists(string filename) { ifstream ifile(filename); return (bool)ifile; } void AdjustPath(string &cascade_face, string &cascade_eye_left, string &cascade_eye_right) { #ifdef WIN32 char cCurrentPath[FILENAME_MAX]; GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)); #else cout << "ATTENZIONE: Su sistema LINUX spostare la cartella resources nel path corrente" << endl; std::cin.get(); char cCurrentPath[FILENAME_MAX]; getcwd(cCurrentPath, sizeof(cCurrentPath)); //string current_path = cCurrentPath; //exit(-1); #endif string g = cCurrentPath; int pos = g.find('x') - 1; string p = g.substr(0, pos); int pos2 = p.find_last_of('\\'); if (pos > 0) { //cout << endl << pos << endl; //cout << "pos2: " << pos2 << endl; string pp = g.substr(pos2, pos - pos2 + 1); string path = p + pp; //cout << "pp: " << pp << endl; //cout << "path: " << path << endl; cascade_face = path + cascade_face; cascade_eye_left = path + cascade_eye_left; cascade_eye_right = path + cascade_eye_right; } } #ifdef WIN32 // Get the horizontal and vertical screen sizes in pixel void GetDesktopResolution(int& horizontal, int& vertical) { RECT desktop; // Get a handle to the desktop window const HWND hDesktop = GetDesktopWindow(); // Get the size of screen to the variable desktop GetWindowRect(hDesktop, &desktop); // The top left corner will have coordinates (0,0) // and the bottom right corner will have coordinates // (horizontal, vertical) horizontal = desktop.right; vertical = desktop.bottom; } #endif #ifdef WIN32 void copyDirectory(string DirToCopy, string DirWhereToCopy) { SHFILEOPSTRUCT sf; memset(&sf, 0, sizeof(sf)); sf.hwnd = 0; sf.wFunc = FO_COPY; string ss = DirToCopy; string st = DirWhereToCopy; //cout << ss << endl; //cout << st << endl; sf.pFrom = ss.c_str(); sf.pTo = st.c_str(); sf.fFlags = FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_NOERRORUI; int n = SHFileOperation(&sf); if (n == 0) { //cout << "Success\n"; ShowWindow(GetConsoleWindow(), SW_HIDE); system("cls"); MessageBox(NULL, "\tPROCESSO TERMINATO!\n\tDIRECTORY COPIATA CON SUCCESSO!\n", "Operazione di background!", MB_ICONINFORMATION | MB_OK); ShowWindow(GetConsoleWindow(), SW_RESTORE); } else { //cout << "Failed\n"; system("cls"); ShowWindow(GetConsoleWindow(), SW_HIDE); MessageBox(NULL, "\tPROCESSO TERMINATO!\n\tDIRECTORY COPIATA NON RIUSCITA!\n", "Operazione di background!", MB_ICONERROR | MB_OK); ShowWindow(GetConsoleWindow(), SW_RESTORE); } } #endif int numDirectoryList(string path, int &numDir, std::vector<string> &dirList) { DIR *dir; string folder = ""; struct dirent *ent; numDir = 0; // le prime due solo folder di sistema... /* open directory stream */ dir = opendir(path.c_str()); if (dir != NULL) { /* print all the files and directories within directory */ while ((ent = readdir(dir)) != NULL) { if (ent->d_type == DT_DIR) { folder = ent->d_name; //cout << ent->d_name << endl; //cout << folder << endl; numDir++; dirList.push_back(folder); } } closedir(dir); } else { /* could not open directory */ perror(""); return EXIT_FAILURE; } return numDir; } int numFileListInDirectory(string folderPath) { vector<string>fileVec; glob(folderPath, fileVec); //cout << "size: "<<fileVec.size() << endl; return fileVec.size(); } unsigned GetNumberOfDigits(unsigned i) // Calcola numero d cifre di un intero { return i > 0 ? (int)log10((double)i) + 1 : 1; } #ifdef WIN32 void DataAdjust(string current_path, string& Data, string& path_init_Norm) { // Solo giorno e mese... string year = "-2017"; int mouth_digit; string Data_2 = Data; int posMouth = Data_2.find_first_of('-') + 1; string mouth = Data.substr(posMouth, posMouth - 1); //cout << mouth << endl; if (stoi(Data.substr(posMouth, posMouth - 1).c_str()) == 0) { //cout << "substr 1 : " << Data.substr(posMouth, posMouth - 1) << endl; mouth_digit = stoi(Data.substr(posMouth, posMouth - 1).c_str()); } else { //cout << "substr: " << Data.substr(posMouth, posMouth - 1) << endl; mouth_digit = stoi(Data.substr(posMouth, posMouth - 1).c_str()); } //cout << "mouth_digit "<<mouth_digit << endl; int numMouth = mouth_digit; int mouth_digit_init = mouth_digit; int pos = Data_2.find_first_of('-'); Data_2 = Data_2.substr(0, pos); //string Data_3; Data_3 = Data.substr(pos+1, Data.find_last_of('-')); mouth = Data.substr(posMouth - 1, posMouth); //cout << "mouth: "<<mouth << endl; //system("pause"); int digit = stoi(Data_2.c_str()); int digit_init = digit; //digit--; Data = to_string(digit) + mouth + year; //cout << Data << endl; //system("pause"); path_init_Norm = current_path + "\\Database_Normalized\\" + Data + "\\"; mouth_digit++; while (!thesis::isDirectory(path_init_Norm)) { digit = 31; mouth_digit--; //cout << mouth_digit << endl; if (GetNumberOfDigits(mouth_digit) == 1) mouth = "-0" + to_string(mouth_digit); else mouth = "-" + to_string(mouth_digit); Data = to_string(digit) + mouth + year; path_init_Norm = current_path + "\\Database_Normalized\\" + Data + "\\"; //cout << "path: "<<Data << endl; if (!thesis::isDirectory(path_init_Norm)) { //mouth_digit = mouth_digit_init; for (int i = 0; i < 31;i++) { if (GetNumberOfDigits(digit) == 2) Data = to_string(digit) + mouth + year; else Data = "0" + to_string(digit) + mouth + year; //cout << "DATA------- " << Data << endl; path_init_Norm = current_path + "\\Database_Normalized\\" + Data + "\\"; if (thesis::isDirectory(path_init_Norm)) break; else digit--; //system("pause"); } } else break; } } #else void DataAdjust(string current_path, string& Data, string& path_init_Norm){ // Solo giorno e mese... // controlla se la cartella non è vuota (prima di usare il classifcatore va effettuato l'addestramento...) //int numDirNorm = myUtils::numDirectoryList(path_init_Norm); //cout<<"NUM: "<<numDirNorm<<endl; //myUtils::system_pause(); string year = "-2017"; int mouth_digit; string Data_2 = Data; int posMouth= Data_2.find_first_of('-')+1; string mouth = Data.substr(posMouth, posMouth-1); //cout << mouth << endl; // stoi dovrebbe funzionare anche se da errore eclipse... if (stoi(Data.substr(posMouth, posMouth - 1).c_str()) == 0) { //cout << "substr 1 : " << Data.substr(posMouth, posMouth - 1) << endl; mouth_digit = stoi(Data.substr(posMouth, posMouth - 1).c_str()) ; } else { //cout << "substr: " << Data.substr(posMouth, posMouth - 1) << endl; mouth_digit = stoi(Data.substr(posMouth, posMouth - 1).c_str()) ; } //cout << "mouth_digit "<<mouth_digit << endl; int numMouth=mouth_digit; int mouth_digit_init=mouth_digit; int pos = Data_2.find_first_of('-'); Data_2 = Data_2.substr(0, pos); //string Data_3; Data_3 = Data.substr(pos+1, Data.find_last_of('-')); mouth = Data.substr(posMouth-1, posMouth); //cout << "mouth: "<<mouth << endl; //system("pause"); int digit = stoi(Data_2.c_str()); int digit_init = digit; //digit--; Data = patch::to_string(digit) + mouth + year; //cout << Data << endl; //system("pause"); path_init_Norm = current_path + "/Database_Normalized/" + Data + "/"; mouth_digit++; while (!thesis::isDirectory(path_init_Norm)) { digit = 31; mouth_digit--; //cout << mouth_digit << endl; if (GetNumberOfDigits(mouth_digit) == 1) mouth = "-0" + to_string(mouth_digit); else mouth = "-" + to_string(mouth_digit); Data = to_string(digit) + mouth + year; path_init_Norm = current_path + "/Database_Normalized/" + Data + "/"; //cout << "path: " << Data << endl; if (!thesis::isDirectory(path_init_Norm)) { //mouth_digit = mouth_digit_init; for (int i = 0; i < 31;i++) { if (GetNumberOfDigits(digit) == 2) Data = to_string(digit) + mouth + year; else Data = "0" + to_string(digit) + mouth + year; //cout << "DATA------- " << Data << endl; path_init_Norm = current_path + "/Database_Normalized/" + Data + "/"; if (thesis::isDirectory(path_init_Norm)) break; else digit--; //system("pause"); } } else break; } } #endif #ifdef WIN32 #include <stdexcept> void SetConsoleWindowSize(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); if (h == INVALID_HANDLE_VALUE) throw std::runtime_error("Unable to get stdout handle."); // If either dimension is greater than the largest console window we can have, // there is no point in attempting the change. { COORD largestSize = GetLargestConsoleWindowSize(h); if (x > largestSize.X) throw std::invalid_argument("The x dimension is too large."); if (y > largestSize.Y) throw std::invalid_argument("The y dimension is too large."); } CONSOLE_SCREEN_BUFFER_INFO bufferInfo; if (!GetConsoleScreenBufferInfo(h, &bufferInfo)) throw std::runtime_error("Unable to retrieve screen buffer info."); SMALL_RECT& winInfo = bufferInfo.srWindow; COORD windowSize = { winInfo.Right - winInfo.Left + 1, winInfo.Bottom - winInfo.Top + 1 }; if (windowSize.X > x || windowSize.Y > y) { // window size needs to be adjusted before the buffer size can be reduced. SMALL_RECT info = { 0, 0, x < windowSize.X ? x - 1 : windowSize.X - 1, y < windowSize.Y ? y - 1 : windowSize.Y - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) throw std::runtime_error("Unable to resize window before resizing buffer."); } COORD size = { x, y }; if (!SetConsoleScreenBufferSize(h, size)) throw std::runtime_error("Unable to resize screen buffer."); SMALL_RECT info = { 0, 0, x - 1, y - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) throw std::runtime_error("Unable to resize window after resizing buffer."); } void ShowLastSystemError() { LPSTR messageBuffer; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, // source GetLastError(), 0, // lang (LPSTR)&messageBuffer, 0, NULL); std::cerr << messageBuffer << '\n'; LocalFree(messageBuffer); } /* COORD QueryUserForConsoleSize() { COORD size = { 0, 0 }; //std::cout << "New console size: "; //std::cin >> size.X >> size.Y; return size; } */ void ConsolResize(int X,int Y, int horizontal, int vertical) { HWND hwnd = GetConsoleWindow(); MoveWindow(hwnd, (int)(vertical - (int)(horizontal*0.5) / 2), (int)(vertical/ 2)-Y*10, -1, -1, FALSE); COORD consoleSize; consoleSize.X = X; consoleSize.Y = Y; //std::cout << "An x or y size of 0 will terminate the program\n"; // while (consoleSize = QueryUserForConsoleSize(),consoleSize.X && consoleSize.Y) // { try { SetConsoleWindowSize(consoleSize.X, consoleSize.Y); } catch (std::logic_error& ex) { std::cerr << ex.what() << '\n'; } catch (std::exception& ex) { std::cerr << ex.what() << "\nSystem error: "; ShowLastSystemError(); } //} } #endif void modifyDrawnRect(cv::Mat &frame, cv::Rect r, cv::Scalar Color, int TickSize) { cv::line(frame, cv::Point(r.x, r.y), cv::Point(r.x + r.width*0.35, r.y ), Color, TickSize); cv::line(frame, cv::Point(r.x, r.y), cv::Point(r.x, r.y + r.height*0.35), Color, TickSize); cv::line(frame, cv::Point(r.x, r.y+r.height), cv::Point(r.x + r.width*0.35, r.y+r.height), Color, TickSize); cv::line(frame, cv::Point(r.x, r.y + r.height), cv::Point(r.x, r.y + r.height - r.height*0.35), Color, TickSize); cv::line(frame, cv::Point(r.x+r.width, r.y), cv::Point(r.x + r.width - r.width*0.35, r.y), Color, TickSize); cv::line(frame, cv::Point(r.x + r.width, r.y), cv::Point(r.x+r.width, r.y + r.height*0.35), Color, TickSize); cv::line(frame, cv::Point(r.x + r.width, r.y+r.height), cv::Point(r.x + r.width - r.width*0.35, r.y + r.height), Color, TickSize); cv::line(frame, cv::Point(r.x + r.width, r.y + r.height), cv::Point(r.x + r.width, r.y + r.height -r.height*0.35), Color, TickSize); cv::line(frame,cv::Point(r.x + r.width/2, r.y-r.height*0.025), cv::Point(r.x + r.width / 2, r.y + r.height*0.025),Color,2); // lato sup cv::line(frame, cv::Point(r.x -r.width*0.025, r.y +r.height/2), cv::Point(r.x + r.width*0.025, r.y + r.height / 2), Color, 2); // lato sx cv::line(frame, cv::Point(r.x + r.width / 2, r.y +r.height - r.height*0.025), cv::Point(r.x + r.width / 2, r.y + r.height + r.height*0.025), Color, 2); // lato inf cv::line(frame, cv::Point(r.x + r.width - r.width*0.025, r.y + r.height / 2), cv::Point(r.x + r.width + r.width*0.025, r.y + r.height / 2), Color, 2); // lato dx // mirino centrale //cv::line(frame, cv::Point(r.x + r.width/2 - r.width*0.025, r.y + r.height / 2), cv::Point(r.x + r.width/2 + r.width*0.025, r.y + r.height / 2), Color, 2); // lato dx //cv::line(frame, cv::Point(r.x + r.width / 2, r.y + r.height / 2 - r.height*0.025), cv::Point(r.x + r.width / 2, r.y + r.height / 2 + r.height*0.025), Color, 2); // lato dx } void modifyDrawnCircle(cv::Mat &frame, cv::Point centre, int radius,cv::Scalar Color, int TickSize) { cv::line(frame, cv::Point(centre.x, centre.y - radius -radius*0.15), cv::Point(centre.x, centre.y - radius +radius*0.35), Color, 5); // lato sup cv::line(frame, cv::Point(centre.x - radius- radius*0.15, centre.y ), cv::Point(centre.x -radius + radius*0.35, centre.y), Color, 5); // lato sx cv::line(frame, cv::Point(centre.x, centre.y + radius - radius*0.35), cv::Point(centre.x, centre.y + radius + radius*0.15), Color, 5); // lato inf cv::line(frame, cv::Point(centre.x + radius - radius*0.35, centre.y ), cv::Point(centre.x + radius + radius*0.15, centre.y), Color, 5); // lato dx // mirino centrale //cv::line(frame, cv::Point(r.x + r.width/2 - r.width*0.025, r.y + r.height / 2), cv::Point(r.x + r.width/2 + r.width*0.025, r.y + r.height / 2), Color, 2); // lato dx //cv::line(frame, cv::Point(r.x + r.width / 2, r.y + r.height / 2 - r.height*0.025), cv::Point(r.x + r.width / 2, r.y + r.height / 2 + r.height*0.025), Color, 2); // lato dx } void writeMatrix(Mat Data, string fileWhereTSave) { std::ofstream fout(fileWhereTSave.c_str()); float *ptr; for (int i = 0; i < Data.rows; i++) { ptr = &Data.at<float>(i); for (int j = 0; j < Data.cols; j++) { fout << ptr[j] << " "; } fout << endl; } fout.close(); } void writefloat(float v, FILE *f) { fwrite((void*)(&v), sizeof(v), 1, f); } float readfloat(FILE *f) { float v; fread((void*)(&v), sizeof(v), 1, f); return v; } /***************************************************************************************************** * Script di calcolo del "TanTriggs Preprocessing process" per la normalizzazione della luminosit�. * * Fonte: * * * * Tan, X., and Triggs, B. "Enhanced local texture feature sets for face * * recognition under difficult lighting conditions.". IEEE Transactions * * on Image Processing 19 (2010), 1635�650. * * * ******************************************************************************************************/ Mat Norm_lum(InputArray src, float alpha, float tau, float gamma, int sigma0, int sigma1) { // Conversione in floating point: Mat X = src.getMat(); X.convertTo(X, CV_32FC1); Mat I; pow(X, gamma, I); // Calcola la DOG Image: { Mat gaussian0, gaussian1; // Kernel Size: int kernel_sz0 = (3 * sigma0); int kernel_sz1 = (3 * sigma1); // algoritmo kernel_sz0 += ((kernel_sz0 % 2) == 0) ? 1 : 0; kernel_sz1 += ((kernel_sz1 % 2) == 0) ? 1 : 0; GaussianBlur(I, gaussian0, Size(kernel_sz0, kernel_sz0), sigma0, sigma0, BORDER_REPLICATE); GaussianBlur(I, gaussian1, Size(kernel_sz1, kernel_sz1), sigma1, sigma1, BORDER_REPLICATE); subtract(gaussian0, gaussian1, I); } { double meanI = 0.0; { Mat tmp; pow(abs(I), alpha, tmp); meanI = mean(tmp).val[0]; } I = I / pow(meanI, 1.0 / alpha); } { double meanI = 0.0; { Mat tmp; //float c=abs(I); c=min(c,tau); cout<<pow(c,alpha,tmp)<<endl; Mat c=abs(I); pow(min(c, tau), alpha, tmp); meanI = mean(tmp).val[0]; } I = I / pow(meanI, 1.0 / alpha); } { Mat exp_x, exp_negx; exp(I / tau, exp_x); exp(-I / tau, exp_negx); divide(exp_x - exp_negx, exp_x + exp_negx, I); I = tau * I; } return I; } // Normalizes a given image into a value range between 0 and 255. Mat norm_0_255(const Mat& src) { // Create and return normalized image: Mat dst; switch (src.channels()) { case 1: cv::normalize(src, dst, 0, 255, NORM_MINMAX, CV_8UC1); break; case 3: cv::normalize(src, dst, 0, 255, NORM_MINMAX, CV_8UC3); break; default: src.copyTo(dst); break; } return dst; } void DigitalZoom(cv::Mat& img_src, float zoom) { //float zoom = 1; float deltaZoom = 0.1; int interpolation_type = CV_INTER_LINEAR; // zoom region to zoom in on within the image //Mat img_src = imread("Last.bmp"); Mat img_zoomed; //imshow("ORIGINAL", img_src); waitKey(0); // while (zoom != -1) { // calculate a zoom sub-region (in the centre of the image) int x = cvFloor((((img_src.cols / zoom) * (zoom / 2.0)) - ((img_src.cols / zoom) / 2.0))); int y = cvFloor((((img_src.rows / zoom) * (zoom / 2.0)) - ((img_src.rows / zoom) / 2.0))); //system("pause"); int width = cvFloor((img_src.cols / zoom)); int height = cvFloor((img_src.rows / zoom)); // use ROI settings to zoom into it Rect roi(x, y, width, height); //cout << roi << endl; Mat image_roi = img_src(roi); resize(image_roi, img_zoomed, img_src.size()); //imshow("ZOOMED", img_zoomed); waitKey(0); /* if (cv::waitKey(1) == 27) // tasto esc zoom = -1; else if ((char)cv::waitKey(1) == '+') { zoom = zoom + deltaZoom; cout << "zoomed-in at: " << zoom << endl; } else if ((char)cv::waitKey(1) == '-') { zoom = zoom - deltaZoom; cout << "zoomed-out at: " << zoom << endl; } */ //} img_zoomed.copyTo(img_src); } void DigitalZoom_FC(cv::Mat& img_src, cv::Point face, float zoom) { // Face Centered //float zoom = 1; float deltaZoom = 0.1; int interpolation_type = CV_INTER_LINEAR; // zoom region to zoom in on within the image //Mat img_src = imread("Last.bmp"); Mat img_zoomed; //imshow("ORIGINAL", img_src); waitKey(0); // while (zoom != -1) { // calculate a zoom sub-region (in the centre of the image) int x = cvFloor((((face.x / zoom) * (zoom / 2.0)) - ((face.x / zoom) / 2.0))); int y = cvFloor((((face.y / zoom) * (zoom / 2.0)) - ((face.y / zoom) / 2.0))); //system("pause"); int width = cvFloor((img_src.cols / zoom)); int height = cvFloor((img_src.rows / zoom)); // use ROI settings to zoom into it Rect roi(x, y, width, height); //cout << roi << endl; Mat image_roi = img_src(roi); resize(image_roi, img_zoomed, img_src.size()); //imshow("ZOOMED", img_zoomed); waitKey(0); /* if (cv::waitKey(1) == 27) // tasto esc zoom = -1; else if ((char)cv::waitKey(1) == '+') { zoom = zoom + deltaZoom; cout << "zoomed-in at: " << zoom << endl; } else if ((char)cv::waitKey(1) == '-') { zoom = zoom - deltaZoom; cout << "zoomed-out at: " << zoom << endl; } */ //} img_zoomed.copyTo(img_src); } };
#pragma once #define _USE_MATH_DEFINES #include <cmath> #define M_PI 3.14159265358979323846 namespace LAB33 { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Сводка для MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: MyForm(void) { InitializeComponent(); // //TODO: добавьте код конструктора // } protected: /// <summary> /// Освободить все используемые ресурсы. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Windows::Forms::PictureBox^ pictureBox1; private: System::Windows::Forms::Timer^ timer1; private: System::Windows::Forms::Timer^ timer2; private: System::ComponentModel::IContainer^ components; private: /// <summary> /// Обязательная переменная конструктора. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Требуемый метод для поддержки конструктора — не изменяйте /// содержимое этого метода с помощью редактора кода. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); this->timer1 = (gcnew System::Windows::Forms::Timer(this->components)); this->timer2 = (gcnew System::Windows::Forms::Timer(this->components)); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit(); this->SuspendLayout(); // // pictureBox1 // this->pictureBox1->Location = System::Drawing::Point(4, 4); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(562, 413); this->pictureBox1->TabIndex = 0; this->pictureBox1->TabStop = false; this->pictureBox1->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MyForm::pictureBox1_Paint); // // timer1 // this->timer1->Tick += gcnew System::EventHandler(this, &MyForm::timer1_Tick); // // timer2 // this->timer2->Tick += gcnew System::EventHandler(this, &MyForm::timer2_Tick); // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(570, 421); this->Controls->Add(this->pictureBox1); this->Name = L"MyForm"; this->Padding = System::Windows::Forms::Padding(1); this->Text = L"Task 3"; this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit(); this->ResumeLayout(false); } #pragma endregion ref class ball { public: int y, x, width, xrt, yrt, xlb, ylb, xrb, yrb; ball() { y = x = width = xrt = yrt = xlb = ylb = xrb = yrb = 0; } void recalculate() { xrt = x + width; yrt = y; xlb = x; ylb = y - width; xrb = x + width; yrb = y - width; } }; array<ball^>^ b; int point; int max = 100; private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) { b = gcnew array<ball^>(max); for (int i = 0; i < max; i++) b[i] = gcnew ball; point = 0; timer1->Interval = 20; timer2->Interval = 20; timer1->Start(); timer2->Start(); } private: System::Void pictureBox1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { int pw = pictureBox1->Width, ph = pictureBox1->Height; for (int i = 0; i < point; i++) if (b[i]->y + ph < 0) { b[i]->y = 0; b[i]->width = 1; b[i]->recalculate(); } for (int i = 0; i < point; i++) for (int j = i + 1; j < point; j++) { if ( (b[i]->xlb == b[j]->x && b[i]->ylb >= b[j]->y && b[i]->xrb == b[j]->xrt && b[i]->yrb >= b[j]->yrt) || //bottom (b[i]->x == b[j]->xlb && b[i]->y <= b[j]->ylb && b[i]->xrt == b[j]->xrb && b[i]->yrt <= b[j]->yrb) || //top (b[i]->x <= b[j]->xrt && b[i]->y == b[j]->yrt && b[i]->xlb <= b[j]->xrb && b[i]->ylb == b[j]->yrb) || //left (b[i]->xrt >= b[j]->x && b[i]->yrt == b[j]->y && b[i]->xrb >= b[j]->xlb && b[i]->yrb == b[j]->ylb) || //right (b[i]->xrb > b[j]->x && b[i]->yrb > b[j]->y && b[i]->xrb < b[j]->xrt && b[i]->yrb > b[j]->yrt) || //bottom right (b[i]->xlb < b[j]->xrt && b[i]->ylb > b[j]->yrt && b[i]->xlb > b[j]->x && b[i]->ylb > b[j]->y) || //bottom left (b[i]->x > b[j]->x && b[i]->y > b[j]->y && b[i]->x < b[j]->xrt && b[i]->y > b[j]->yrt) || //top left (b[i]->xrt > b[j]->xlb && b[i]->yrt < b[j]->ylb && b[i]->xrt < b[j]->xrb && b[i]->yrt < b[j]->yrb) //top right ) { ball^ tmp=gcnew ball; tmp->x = (b[i]->x + b[j]->x) / 2; tmp->y = (b[i]->y + b[j]->y) / 2; tmp->width = (b[i]->width + b[j]->width) / 2; //tmp->width = Math::Sqrt(b[i]->width + b[j]->width); tmp->recalculate(); b[i] = b[j] = tmp; } } for (int i = 0; i < point; i++) e->Graphics->DrawEllipse(Pens::Black, b[i]->x, b[i]->y + ph, b[i]->width, b[i]->width); } private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) { Random^ rnd = gcnew Random; int pw = pictureBox1->Width, ph = pictureBox1->Height; int k = rnd->Next() % 2; for (int i = 0; i < k && point < max; i++) { b[point]->width = 1; b[point]->y = 0; b[point]->x += rnd->Next() % pw; b[point]->recalculate(); point++; } pictureBox1->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MyForm::pictureBox1_Paint); } private: System::Void timer2_Tick(System::Object^ sender, System::EventArgs^ e) { Random^ rnd = gcnew Random; for (int i = 0; i < point; i++) { b[i]->y -= rnd->Next() % 10; b[i]->width += rnd->Next() % 2; b[i]->recalculate(); } pictureBox1->Invalidate(); } }; }
/* Demo_03_Main.cpp */ #include <boost/mpi.hpp> #include "repast_hpc/RepastProcess.h" #include "Model.h" int main(int argc, char** argv){ std::string configFile = argv[1]; // The name of the configuration file is Arg 1 std::string propsFile = argv[2]; // The name of the properties file is Arg 2 //std::cout<<"ggggggg"; boost::mpi::environment env(argc, argv); //Creates MPI Enviroment boost::mpi::communicator world; //Creates a world repast::RepastProcess::init(configFile); //Initialises repast Process AnsaziModel* model = new AnsaziModel(propsFile, argc, argv, &world); //Initialises the model repast::ScheduleRunner& runner = repast::RepastProcess::instance()->getScheduleRunner(); //Creates the schedule runner model->initAgents(); //Initialise Agents model->initSchedule(runner); //Initialise Scheduler runner.run(); //Run model delete model; repast::RepastProcess::instance()->done(); //Shut of Simulation }
#include "util.h" #include <set> #include <string> #include <iostream> int main(int argc, char *argv[]) { std::cout << "Hello!" << std::endl; std::string test = "data"; std::cout << test << std::endl; std::cout << test.length() << std::endl; std::set<std::string> subWords = parseStringToWords(test); std::cout << "# of subwords: " << subWords.size() << std::endl; for (std::set<std::string>::iterator it=subWords.begin(); it!=subWords.end(); ++it) { std::cout << ' ' << *it << std::endl; } return 0; }
#include "afxwin.h" #include<map> #include<vector> #include<string> #define BUFFER_LENGTH 1024 #define DB_LENGTH 50 #define MSG_LOGIN 0//登陆 #define MSG_LOGIN_RP 1//登陆回复 #define MSG_SEARCH 2//查找会话目标ID是否存在 #define MSG_SEARCH_RP 3 #define MSG_SEARCH_ERROR 4//无 #define MSG_ABROAD 5//无 #define MSG_ABROAD_RP //无 #define MSG_FILE 7//文件本体消息 #define MSG_FILETYPE 8//文件类型:名字,大小 #define MSG_FILEEND 9//文件结束 #define MSG_FILE_RP 10//无 #define MSG_LOGOUT 11//注销 #define MSG_LOGOUT_RP 12 #define MSG_BROADCAST 13//查找所有的注册用户 #define MSG_BROADCAST_RP 14 #define MSG_TEXT 15//一对一文本消息 #define MSG_ACK 100//////////////////无 #define MSG_SIGNUP 16//注册 #define MSG_SIGNUP_RP 17 #define MSG_CHATROOM 18//建立聊天室 #define MSG_CHATROOM_RP 19 #define MSG_ADDONECHAT 20//添加聊天室成员 #define MSG_ADDONECHAT_RP 21 #define MSG_DELETEONECHAT 22//删除聊天室成员 #define MSG_DELETEONECHAT_RP 23 #define MSG_CHATTXT 24//聊天文本消息 #define MSG_CHATFILETYPE 25//聊天室文件类型 #define MSG_CHATFILEEND 26//聊天室文件结束 #define MSG_CHATBROADCAST 27//查询当前参与的所有聊天室 #define MSG_CHATBROADCAST_RP 28 #define MSG_SEARCHCHAT 29 #define MSG_SEARCHCHAT_RP 30 #define MSG_RECVFILE 31 #define MSG_CANCELFILE 32 #define MSG_NEXTTIME 33 #define MSG_RECVCHATFILE 34 #define MSG_CANCELCHATFILE 35 #define TIMERBROAD (WM_USER+101) #define WM_RecvMsg (WM_USER+102)//需要建立一对一聊天对话框 #define WM_RecvChatMsg (WM_USER+103)//需要建立聊天室对话框 #define WM_RecvFileSave (WM_USER+104)//需要建立文件接收对话框 static UINT WM_SendMsg = RegisterWindowMessage(_T("UserText"));//发送121文本消息 static UINT WM_SendFile = RegisterWindowMessage(_T("UserFile"));//发送121文件 static UINT WM_CloseMsg = RegisterWindowMessage(_T("UserClose"));//关闭对话框 static UINT WM_Signup = RegisterWindowMessage(_T("UserSignup"));//注册 static UINT WM_AddOne = RegisterWindowMessage(_T("AddOne"));//添加一个聊天室成员 static UINT WM_DelOne = RegisterWindowMessage(_T("DeleteOne"));//删除一个聊天室成员 static UINT WM_SendChatMsg = RegisterWindowMessage(_T("SendChatMsg"));//发送聊天室文本消息 static UINT WM_SendChatFile = RegisterWindowMessage(_T("SendChatFile"));//发送聊天室文件消息 static UINT WM_RecvFile = RegisterWindowMessage(_T("RecvFile"));//接收文件消息 static UINT WM_CancelFile = RegisterWindowMessage(_T("CancelFile"));//取消接收文件消息 static UINT WM_RecvChatFile = RegisterWindowMessage(_T("RecvChatFile"));//接收聊天室文件消息 static UINT WM_CancelChatFile = RegisterWindowMessage(_T("CancelChatFile"));//接收聊天室文件消息 #define ERRORMSG {LPVOID lpMsgBuf;\ FormatMessage(\ FORMAT_MESSAGE_ALLOCATE_BUFFER |\ FORMAT_MESSAGE_FROM_SYSTEM |\ FORMAT_MESSAGE_IGNORE_INSERTS,\ NULL,\ GetLastError(),\ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \ (LPTSTR) &lpMsgBuf,\ 0,\ NULL\ );\ AfxMessageBox((LPCTSTR)lpMsgBuf, MB_OK|MB_ICONEXCLAMATION);\ LocalFree( lpMsgBuf );} using namespace std; //无 struct IP_PORT{ DWORD m_ip; USHORT m_port; }; //服务器和客户端通信的主体结构 struct MSG0{ unsigned short m_msgType;//消息类型 char m_text[BUFFER_LENGTH];//消息内容 }; struct TMSG{//一对一文件/文本消息 unsigned int m_idFrom;//一对一对话中的发送人Id char m_name[DB_LENGTH];//发送人的昵称 unsigned int m_id;//消息要发送给的对方 char m_text[BUFFER_LENGTH - DB_LENGTH - 2*sizeof(unsigned int)];//消息内容 }; struct LTMSG{//一对一文件类型消息 unsigned int m_idFrom;//一对一对话中的发送人Id char m_name[DB_LENGTH];//发送人的昵称 unsigned int m_id;//消息要发送给的对方 long long m_fileLength;//文件大小 char m_text[BUFFER_LENGTH - DB_LENGTH - 2*sizeof(unsigned int) - sizeof(long long)];//文件名字 }; struct LCTMSG{//聊天室文件类型消息 unsigned int m_idFrom;//发送人Id unsigned int m_cId;//聊天室的ID unsigned int m_ownerId;//聊天室的建立者ID char m_name[DB_LENGTH];//发送人的昵称 long long m_fileLength;//文件大小 char m_text[BUFFER_LENGTH - DB_LENGTH - 3*sizeof( unsigned int) - sizeof(long long)];//文件名字 }; struct CTMSG{//聊天室文本/文件消息 unsigned int m_idFrom;//发送人Id unsigned int m_cId;//聊天室的ID unsigned int m_ownerId;//聊天室的建立者ID char m_name[DB_LENGTH];//发送人的昵称 char m_text[BUFFER_LENGTH - DB_LENGTH - 3*sizeof( unsigned int)];//消息内容or文件名字 }; struct FMSG{//一对一文件消息 char m_filename[DB_LENGTH];//发送文件名称 char m_text[BUFFER_LENGTH -DB_LENGTH ];//消息内容 }; //struct LF{ // long long m_fileLength;//文件changdu // char m_filename[DB_LENGTH];//文件名字 //}; struct USER_INFO{//注册使用 char m_name[DB_LENGTH]; char m_pwd[DB_LENGTH]; }; struct USER_LOGIN{ int m_id;//用户ID char m_pwd[DB_LENGTH];//用户的密码或者昵称 };
#pragma once #include "Keng/Core/System.h" #include "Keng/Graphics/IGraphicsSystem.h" #include "Keng/WindowSystem/IWindowSystem.h" #include "Keng/ResourceSystem/IResourceSystem.h" namespace simple_quad_sample { class SimpleQuadSystem : public keng::core::System< keng::core::ISystem, SimpleQuadSystem, keng::resource::IResourceSystem, keng::graphics::IGraphicsSystem, keng::window_system::IWindowSystem> { public: SimpleQuadSystem(); ~SimpleQuadSystem(); // ISystem static const char* SystemName() { return "SimpleQuadSystem"; } virtual void OnSystemEvent(const keng::core::IApplicationPtr&, const keng::core::SystemEvent& e) override final; private: void Initialize(const keng::core::IApplicationPtr& app); bool Update(); void Shutdown(); private: keng::graphics::IEffectPtr m_effect; keng::graphics::gpu::IDeviceBufferPtr m_constantBuffer; keng::graphics::gpu::IDeviceBufferPtr m_vertexBuffer; keng::graphics::gpu::ITextureRenderTargetPtr m_textureRT; keng::graphics::gpu::IDepthStencilPtr m_depthStencil; keng::graphics::gpu::IWindowRenderTargetPtr m_windowRT; keng::graphics::gpu::IAnnotationPtr m_annotation; }; }
#include "TestsService.h" #include <QJsonArray> #include <QJsonValue> #include "Entities/ShortTestInfo/ShortTestInfo.h" #include "Entities/Test/Test.h" #include "Requester/Requester.h" #include "JsonArraySerialization.h" // :: Constants :: const QString GET_TESTS_API = "tests"; const QString GET_TEST_API = "tests/with-scales/%1"; const QString DELETE_TEST_API = "tests/%1"; // :: Lifeccyle :: TestsService::TestsService(QObject *parent/*= nullptr*/) : BaseService(parent) {} // :: Public methods :: void TestsService::getTests() const { auto requester = makeRequesterWithDefaultErrorOutput(); connect(requester, SIGNAL(success(QJsonArray)), SLOT(jsonTestsGot(QJsonArray))); requester->sendRequest(GET_TESTS_API); } void TestsService::getTest(int id) const { auto requester = makeRequesterWithDefaultErrorOutput(); connect(requester, SIGNAL(success(QJsonObject)), SLOT(jsonTestGot(QJsonObject))); requester->sendRequest(GET_TEST_API.arg(id)); } void TestsService::removeTest(int id) const { auto requester = makeRequester(); connect(requester, SIGNAL(success()), SIGNAL(testDeleted())); connect(requester, &Requester::failure, this, &TestsService::testIsUsed); requester->sendRequest(DELETE_TEST_API.arg(id), RequestType::DELET); } // :: Private slots :: void TestsService::jsonTestsGot(const QJsonArray &jsonArray) { auto tests = serializableObjectsFromJsonArray<QList, ShortTestInfo>(jsonArray); emit testsGot(tests); } void TestsService::jsonTestGot(const QJsonObject &jsonObject) { auto test = makeWithJsonObject<Test>(jsonObject); emit testGot(test); }
int i=0; void setup() { Serial.begin(57600); } void loop(){ Serial.println("Teste Formula SAE UFPB"); Serial.println(i); i++; delay(50); }
// Open-closed Principle // entities should be open for extension, but closed for modification #include <iostream> #include <string> #include <vector> enum class Color { Red, Green, Blue }; enum class Size { Small, Medium, Large }; struct Product { std::string name; Color color; Size size; }; typedef std::vector<Product> ProductList; // This is how not to do it. // To add new criteria you have to go into this class again and change and also test it. // Violates the Open-closed Principle. struct ProductFilter { static ProductList by_color(ProductList items, Color color) { ProductList result; for (auto& item : items) if (item.color == color) result.push_back(item); return result; } static ProductList by_size(ProductList items, Size Size) { ProductList result; for (auto& i : items) if (i.size == Size) result.push_back(i); return result; } // Not scalable !!! // We'd need all combinations of possible filter criteria. static ProductList by_color_and_size(ProductList items, Color color, Size size) { ProductList result; for (auto& item : items) if (item.color == color && item.size == size) result.push_back(item); return result; } }; // Better: Generalize with interfaces // Specification pattern. Not a GoF pattern but extensively used. // Reminds of generative programming (GP). // it's an interface = class with virtual functions // generic specification template <typename T> struct ISpecification { virtual bool is_satisfied(T item) = 0; }; // we can combine specifications template <typename T> struct AndSpecification : ISpecification<T> { ISpecification<T>& first; ISpecification<T>& second; AndSpecification(ISpecification<T>& first, ISpecification<T>& second) : first{first}, second{second} {} bool is_satisfied(T item) override { return first.is_satisfied(item) && second.is_satisfied(item); } }; // ColorSpecification is a product specification struct ColorSpecification : ISpecification<Product> { Color color; explicit ColorSpecification(const Color color) : color{color} {} bool is_satisfied(Product item) override { return item.color == color; } }; // SizeSpecification is a product specification struct SizeSpecification : ISpecification<Product> { Size size; explicit SizeSpecification(const Size size) : size{size} {} bool is_satisfied(Product item) override { return item.size == size; } }; // another interface that uses the specification interface // generic filter template <typename T> struct IFilter { // try to pass spec by value and you end up in OO hell! virtual ProductList filter(ProductList& items, ISpecification<T>& spec) = 0; }; // BetterFilter is a product filter struct BetterFilter : IFilter<Product> { ProductList filter(ProductList& items, ISpecification<Product>& spec) override { ProductList result; for (auto& productItem : items) if (spec.is_satisfied(productItem)) result.push_back(productItem); return result; } }; int main() { Product apple{"Apple", Color::Green, Size::Small}; Product tree{"Tree", Color::Green, Size::Large}; Product house{"House", Color::Blue, Size::Large}; ProductList all{apple, tree, house}; BetterFilter bf; ColorSpecification green(Color::Green); auto green_things = bf.filter(all, green); for (auto& product : green_things) std::cout << product.name << " is green" << std::endl; SizeSpecification big(Size::Large); // green_and_big is a product specification AndSpecification<Product> green_and_big{big, green}; auto green_big_things = bf.filter(all, green_and_big); for (auto& product : green_big_things) std::cout << product.name << " is green and big" << std::endl; return 0; }
#include<stdio.h> #include <malloc.h> #include<conio.h> struct node { int num; struct node *next; }; void display(struct node *p) { struct node *q; q = p; while (q != NULL) { printf("%d \n", q->num); q = q->next; //count++; } } void append(struct node **q, int num) { struct node *temp, *r; if (*q == NULL) { temp = (struct node *)malloc(sizeof(struct node)); temp->num = num; temp->next = NULL; *q = temp; } else { temp = *q; while (temp->next != NULL) temp = temp->next; r = (struct node *)malloc(sizeof(struct node)); r->num = num; r->next = NULL; temp->next = r; } } void Reversell(struct node **head_ref); void main(){ struct node *head1 = NULL; struct node *head2 = NULL; // change the code to insert last printf("enter the first LL"); for (int i = 0; i < 3; i++){ int d; scanf_s("%d", &d); append(&head1, d); } Reversell(&head1); display(head1); _getch(); } void Reversell(struct node **head_ref) { struct node* first; struct node* rest; if (*head_ref == NULL) return; first = *head_ref; rest = first->next; if (rest == NULL) return; Reversell(&rest); first->next->next = first; first->next = NULL; *head_ref = rest; } /*struct node* Reversell(struct node *l1){ if (l1 == NULL) return NULL; if (l1->next == NULL) { return NULL; } else{ struct node *second = l1->next; l1->next = NULL; struct node *reverse = Reversell(second); second->next = l1; return reverse; } }*/
#pragma once #include "MySqlDBAccess.h" class MySqlDBAccessMgr { public: MySqlDBAccessMgr(); ~MySqlDBAccessMgr(); void Init(); MySqlDBAccess* DBMaster(); MySqlDBAccess* DBSlave(); MySqlDBAccess* DBRouting(); private: //std::map <std::string, MySqlDBAccess*> m_db_access_map; MySqlDBAccess *m_db_master_conn; MySqlDBAccess *m_db_slave_conn; MySqlDBAccess *m_db_routing_conn; std::map<int , int> specialSitemid; };
#include "CQEnum_Pch.hpp" #include "CQEnum.hpp" namespace CQSL { namespace CQEnum { // // Gets the next token and makes sure it's the indicated value. Can either throw or // return false if not found. If it indicates there must be an equal sign, then we // always throw if we find the token but not the equals. // bool InputSrc::bCheckNextId(const std::string_view& svCheck , const char* const pszFailMsg , const bool bWithEquals , const bool bThrowIfIfNot) { if ((eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Identifier) || (m_strTmpToken != svCheck)) { if (bThrowIfIfNot) { ThrowParseErr(pszFailMsg); } // Push the characters back PushBack(m_strTmpToken); return false; } if (bWithEquals) { if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Equals) { ThrowParseErr("Expected an equal sign here"); } } return true; } // // When running through a parent block we are always lookging for either // a child block or the end of the parent block. This returns true if a // child block or false if the end of the parent. Throws if not one of those. // // We assume the child block also includes an equal sign. // bool InputSrc::bNextChildOrEnd( const char* const pszBlock , const char* const pszEndBlock) { // The next token must be an id if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Identifier) { ThrowParseErr("Expected an id here"); } // If it's the child block, check the equal sign bool bRes = false; if (m_strTmpToken == pszBlock) { // We have to have an equal sign if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Equals) { ThrowParseErr("Expected an equal sign following start of block"); } bRes = true; } else if (m_strTmpToken == pszEndBlock) { // Just fall through with false return } else { std::string strErrMsg("Expected a '"); strErrMsg.append(pszBlock); strErrMsg.append("' child block or the end of the '"); strErrMsg.append(pszEndBlock); strErrMsg.append("' parent block"); ThrowParseErr(strErrMsg); } return bRes; } // Checks for the end line for a block, throws if not void InputSrc::CheckBlockEnd(const char* const pszCheck) { m_strTmpTest = "End"; m_strTmpTest.append(pszCheck); bCheckNextId(m_strTmpTest, "Expected end of current block", false, true); } // Makes sure the next token is a colon void InputSrc::CheckColon() { if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Colon) { ThrowParseErr("Expected a colon here"); } } // Makes sure the next token is a comma void InputSrc::CheckComma() { if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Comma) { ThrowParseErr("Expected a comma here"); } } // Makes sure the next token is an equal sign void InputSrc::CheckEqualSign() { if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Equals) { ThrowParseErr("Expected a equals sign here"); } } // // Makes sure the next token seen is an (optionally signed) numeric value. If not // it throw. // int32_t InputSrc::iCheckSignedValue(const char* const pszCheck , const char* const pszFailMsg) { // Has to start wtih xxx= bCheckNextId(pszCheck, pszFailMsg, true, true); // And next we should get a number token if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Number) { ThrowParseErr("Expected a signed number here"); } // Convert first to 64 bit so we can test limits size_t szEnd = 0; int64_t iRet = std::stoll(m_strTmpToken, &szEnd, 16); if (szEnd != m_strTmpToken.length()) { ThrowParseErr(pszFailMsg); } if ((iRet < std::numeric_limits<int32_t>::min()) || (iRet > std::numeric_limits<int32_t>::max())) { ThrowParseErr("Expected a number in the int32_t range"); } return static_cast<int32_t>(iRet); } // Gets the next token and insures it's a numeric value, throws if not int32_t InputSrc::iGetSignedToken(const char* const pszFailMsg) { // And next we should get a number token if (eGetNextToken(m_strTmpToken) != CQEnum::ETokens::Number) { ThrowParseErr("Expected a signed number here"); } // Figure out radix uint32_t radix = 10; if (m_strTmpToken.find("0x", 0) != std::string::npos) { m_strTmpToken.erase(0, 2); radix = 16; } // Convert first to 64 bit so we can test limits size_t szEnd = 0; int64_t iRet = std::stoll(m_strTmpToken, &szEnd, radix); if (szEnd != m_strTmpToken.length()) { ThrowParseErr(pszFailMsg); } if ((iRet < std::numeric_limits<int32_t>::min()) || (iRet > std::numeric_limits<int32_t>::max())) { ThrowParseErr(pszFailMsg); } return static_cast<int32_t>(iRet); } // Reads the rest of the current line void InputSrc::GetLineRemainder(std::string& strToFill) { strToFill.clear(); // Rmemeber this as the position of this 'token' m_uLastTokenCol = m_uColNum; m_uLastTokenLine = m_uLineNum; char chCur = chGetNext(false); while (chCur != 0xA) { strToFill.push_back(chCur); chCur = chGetNext(false); } } // Get the next token and validates that it's an id type void InputSrc::GetIdToken(const char* const pszFailMsg, std::string& strToFill) { if (eGetNextToken(strToFill) != ETokens::Identifier) { ThrowParseErr(pszFailMsg); } } // Reads the rest of the line as a set of space separated tokens void InputSrc::GetSpacedValues(std::vector<std::string>& vToFill) { vToFill.clear(); // Rmemeber this as the position of this 'token' m_uLastTokenCol = m_uColNum; m_uLastTokenLine = m_uLineNum; m_strTmpToken.clear(); bool bInToken = false; while (true) { const char chCur = chGetNext(false); const bool bIsWS = bIsSpace(chCur); if (bInToken) { // If we hit a space, then the end, else accumulate if (bIsWS) { if (!m_strTmpToken.empty()) { vToFill.push_back(m_strTmpToken); } m_strTmpToken.clear(); bInToken = false; } else { m_strTmpToken.push_back(chCur); } } else { // Ignore spaces, wait for start of a new token if (!bIsWS) { m_strTmpToken.clear(); m_strTmpToken.push_back(chCur); bInToken = true; } } // If we hit the end of the line, we are done if (chCur == 0xA) { break; } } } // Reads the rest of the line as a set of comma separated tokens, no leading/trailing space void InputSrc::GetCommaSepValues(std::vector<std::string>& vToFill) { vToFill.clear(); // Rmemeber this as the position of this 'token' m_uLastTokenCol = m_uColNum; m_uLastTokenLine = m_uLineNum; m_strTmpToken.clear(); bool bInToken = false; while (true) { const char chCur = chGetNext(false); const bool bIsWS = bIsSpace(chCur); if (bInToken) { // If we hit a comma, then the end, else accumulate if (chCur == ',') { // Get rid of any trailing white space while (!m_strTmpToken.empty() && std::isspace(m_strTmpToken.back())) { m_strTmpToken.pop_back(); } if (!m_strTmpToken.empty()) { vToFill.push_back(m_strTmpToken); } m_strTmpToken.clear(); bInToken = false; } else { m_strTmpToken.push_back(chCur); } } else { // Ignore spaces, wait for start of a new token if (!bIsWS) { // If it's a comma, then we had an empty token if (chCur == ',') { m_strTmpToken.clear(); vToFill.push_back(m_strTmpToken); } else { m_strTmpToken.clear(); m_strTmpToken.push_back(chCur); bInToken = true; } } } // // If we hit the end of the line, we are done, but we have to // deal with a trailing token. // if (chCur == 0xA) { if (bInToken) { // Get rid of any trailing white space while (!m_strTmpToken.empty() && std::isspace(m_strTmpToken.back())) { m_strTmpToken.pop_back(); } if (!m_strTmpToken.empty()) { vToFill.push_back(m_strTmpToken); } } break; } } } // Get the next token and validates that it's a quoted string type std::string InputSrc::strGetToken(const char* const pszFailMsg) { std::string strRet; if (eGetNextToken(strRet) != ETokens::String) { ThrowParseErr(pszFailMsg); } return strRet; } // Get the next lexical token from the input stream ETokens InputSrc::eGetNextToken(std::string& strText) { strText.clear(); // The first character tells us what we are looking at, ignore space char chCur = chGetNext(true); if (!chCur) return ETokens::End; // // Remember this as the last token position. Sub one from the column because // we just ate one above. This cannot underflow since we have to have just // eaten at least one character on the current line. // m_uLastTokenCol = m_uColNum - 1; m_uLastTokenLine = m_uLineNum; ETokens eRet = ETokens::Identifier; if (chCur == ',') { eRet = ETokens::Comma; } else if (chCur == ':') { eRet = ETokens::Colon; } else if (chCur == '=') { eRet = ETokens::Equals; } else if (chCur == '"') { eRet = ETokens::String; // Gather up until the closing quote while (m_strmSrc) { // Can't ignore white space in this case chCur = chGetNext(false); if (chCur == 0) { // Illegal end of file ThrowParseErr("Illegal end of file inside quoted string"); } else if (chCur == 0x0A) { ThrowParseErr("String literal crossed a line boundary"); } // Break out if the end, else add to the string if (chCur == '"') break; strText.push_back(chCur); } } else if (bIsDigit(chCur, false) || (chCur == '+') || (chCur == '-')) { eRet = ETokens::Number; // Eat characters until we get an end separator character strText.push_back(chCur); while (m_strmSrc) { chCur = chGetNext(false); if (bIsEndSep(chCur)) { // If not space, push it back if (!bIsSpace(chCur)) { PushBack(chCur); } break; } strText.push_back(chCur); } // // Try to convert the value to a number. If it starts with 0x, // then strip that off and parse as a hex number // uint32_t radix = 10; if ((strText.length() >= 2) && (std::strncmp(strText.c_str(), "0x", 2) == 0)) { strText.erase(0, 2); radix = 16; } char* pszEnd; int64_t iVal = std::strtol(strText.c_str(), &pszEnd, radix); // If the end isn't pointing at a null, then it's bad if (*pszEnd) { ThrowParseErr("Could not convert to a number"); } // If hex, put the hex prefix back if (radix == 16) { strText.insert(0, "0x"); } } else if (bIsIdChar(chCur, true)) { eRet = ETokens::Identifier; // It's a token, so we read until we hit an end sep char strText.push_back(chCur); while (m_strmSrc) { // Can't ignore white space in this case chCur = chGetNext(false); if (bIsEndSep(chCur)) { // If not space, push it back if (!bIsSpace(chCur)) { PushBack(chCur); } break; } strText.push_back(chCur); } } else { ThrowParseErr("Expected a valid id, number or special character"); } return eRet; } bool InputSrc::bIsDigit(const char chTest, const bool bHex) const noexcept { if (bHex) return std::isxdigit(static_cast<unsigned char>(chTest)); return std::isdigit(static_cast<unsigned char>(chTest)); } bool InputSrc::bIsIdChar(const char chTest, const bool first) const noexcept { const bool bIsAlpha = std::isalpha(chTest); // If the first char it has to be alpha if (first) return bIsAlpha; // Else it can be alphanum, underscore or hyphen return bIsAlpha || bIsDigit(chTest, true) || (chTest == '_') || (chTest == '-'); } // // We can legally end ids and numbers and such either on white space or one // of the separator characters. It can be an LF character if the thing being // consumed is at the end of the line, but that will count as space so we get // that naturally. // bool InputSrc::bIsEndSep(const char chTest) const noexcept { return ( (chTest == ')') || (chTest == ',') || (chTest == '=') || (chTest == ':') || bIsSpace(chTest) ); } bool InputSrc::bIsSpace(const char chTest) const noexcept { return std::isspace(static_cast<unsigned char>(chTest)); } // Builds up an error message that includes the last token position info std::string InputSrc::BuildErrMsg(const std::string_view& svMsg) const { std::string strFullMsg = "(Line="; strFullMsg.append(std::to_string(m_uLastTokenLine)); strFullMsg.append("/Col="); strFullMsg.append(std::to_string(m_uLastTokenCol)); strFullMsg.append(") - "); strFullMsg.append(svMsg); return strFullMsg; } // Return the next character, optionally ignoring white space char InputSrc::chGetNext(const bool ignoreWS) { char chRet = 0; while (m_strmSrc) { m_strmSrc.get(chRet); if (!bIsSpace(chRet)) { m_uColNum++; // // If this is the first non-space of this line and it's a semi-colon, // it's a comment so we need to eat the rest of the line and then // continue. // if (m_bFirstLineChar && (chRet == ';')) { while (m_strmSrc) { m_strmSrc.get(chRet); if ((chRet == 0x0A) || (chRet == 0x0D)) { // This character will be processed below break; } } if (!m_strmSrc) { // Return a zero to indicate end of input chRet = 0; break; } } else { // Nothing special, so break out with this character m_bFirstLineChar = false; break; } } // Handle newlines specially if ((chRet == 0x0D) || (chRet == 0x0A)) { // If a CR, see if there's a subsequent LF. If not put it back if (chRet == 0xD) { char chTmp; m_strmSrc.get(chTmp); if (chTmp != 0x0A) m_strmSrc.putback(chTmp); } m_bFirstLineChar = true; m_uLineNum++; m_uColNum = 1; } else { m_uColNum++; } // If not ignoring white space, break out if (!ignoreWS) { break; } } return chRet; } // // The main program calls this to get us to open the source stream and prepare // to parse. // void InputSrc::Open(const std::string& strSrcFile) { m_strmSrc.open(strSrcFile, std::ifstream::in); if (!m_strmSrc) { throw std::runtime_error("The input file could not be opened"); } m_bFirstLineChar = true; m_uColNum = 1; m_uLineNum = 1; m_uLastTokenCol = 1; m_uLastTokenLine = 1; } // Push back a single character to the stream void InputSrc::PushBack(const char chToPush) { m_strmSrc.putback(chToPush); // We should never push back over a new line if (!m_uColNum) { ThrowParseErr("Pushback column underflow error!"); } m_uColNum--; } // Push back a string to the stream void InputSrc::PushBack(const std::string& strToPush) { std::string::const_reverse_iterator rit = strToPush.rbegin(); while (rit != strToPush.rend()) { m_strmSrc.putback(*rit); // We should never push back over a new line if (!m_uColNum) { ThrowParseErr("Pushback column underflow error!"); } ++rit; } } }};
// Gaddis 1009-1010 #include <iostream> #include <cstdlib> #include <memory> using namespace std; // Exception for index out of range struct IndexOutOfRangeException { const int index; IndexOutOfRangeException(int ix) : index(ix) {} }; template <class T> class SimpleVector { unique_ptr<T[]> aptr; int arraySize; public: SimpleVector(int); SimpleVector(const SimpleVector &); int size() const { return arraySize; } T &operator[](int); // Overloaded[] operator void print() const; // Outputs the array elements }; // Constructor template <class T> SimpleVector<T>::SimpleVector(int s) { arraySize = s; aptr = make_unique<T[]>(s); for (int count = 0; count < arraySize; count++) aptr[count] = T(); } // Copy constructor template <class T> SimpleVector<T>::SimpleVector(const SimpleVector &obj) { arraySize = obj.arraySize; aptr = make_unique<T[]>(arraySize); for (int count = 0; count < arraySize; count++) aptr[count] = obj[count]; } // Overloaded [] template <class T> T &SimpleVector<T>::operator[](int sub) { if (sub < 0 || sub >= arraySize) throw IndexOutOfRangeException(sub); return aptr[sub]; } // Print all entries template <class T> void SimpleVector<T>::print() const { for (int k = 0; k < arraySize; k++) cout << aptr[k] << " "; cout << endl; }
//=========================================================================== //! @file model_obj.cpp //=========================================================================== // 解決シダいけす void ObjModel::tmpInitialize(Vertex* vertices, u32* indices, u32 verticesCount, u32 indicesCount) { //------------------------------------------------------------- // 頂点データ(入力レイアウトと同じメンバ変数レイアウトの構造体の配列) //------------------------------------------------------------- vertexBuffer_.initialize(sizeof(Vertex) * verticesCount, D3D11_USAGE_IMMUTABLE, D3D11_BIND_VERTEX_BUFFER, vertices); pointCount_ = verticesCount; //---- インデックスバッファの作成 indexBuffer_.initialize(sizeof(u32) * indicesCount, D3D11_USAGE_IMMUTABLE, D3D11_BIND_INDEX_BUFFER, indices); indexCount_ = indicesCount; } //---------------------------------------------------------- //! 初期化() //---------------------------------------------------------- bool ObjModel::load(Vertex* vertices, u32* indices, u32 verticesCount, u32 indicesCount, const char* texturePath) { tmpInitialize(vertices, indices, verticesCount, indicesCount); if(texturePath) { texture0_.reset(gpu::createTexture(texturePath)); if(!texture0_) return false; } #if 0 // ファイルを開く FILE * fp; if (fopen_s(&fp, filePath.c_str(), "rt") != 0) { GM_ASSERT_MESSAGE(false, "model_obj.cpp 83"); return false; } // 頂点座標読み込み loadPoint(fp); // 頂点番号読み込み //loadIndex(fp); // 法線読み込み fclose(fp); #endif return true; } //---------------------------------------------------------- //! 初期化(読み込み) //---------------------------------------------------------- bool ObjModel::load(const std::string& filePath) { //tmpInitialize(); #if 0 // ファイルを開く FILE* fp; if (fopen_s(&fp, filePath.c_str(), "rt") != 0) { GM_ASSERT_MESSAGE(false, "model_obj.cpp 83"); return false; } // 頂点座標読み込み loadPoint(fp); // 頂点番号読み込み //loadIndex(fp); // 法線読み込み fclose(fp); #endif return true; } //---------------------------------------------------------- //! 描画 //---------------------------------------------------------- void ObjModel::render() { // 定数バッファ更新 auto cbModel = cbModel_.begin(); cbModel->matWorld_ = Matrix::translate(position_); cbModel->position_ = position_; cbModel_.end(); gpu::setConstantBuffer(1, cbModel_); gpu::setVertexBuffer(&vertexBuffer_, sizeof(Vertex)); gpu::setIndexBuffer(&indexBuffer_); if(texture0_) gpu::setTexture(0, texture0_); gpu::drawIndexed(PT_TRIANGLES, indexCount_ /*static_cast<u32>(indices_.size())*/); gpu::setTexture(0, nullptr); } //---------------------------------------------------------- //! 解放 //---------------------------------------------------------- void ObjModel::cleanup() { } //---------------------------------------------------------- //! 頂点座標読み込み //---------------------------------------------------------- void ObjModel::loadPoint(FILE* fp) { Vector3 point(Vector3::ZERO); //u32 loadCount = 0; u32 v1 = 0, v2 = 0, v3 = 0; u32 vn1 = 0, vn2 = 0, vn3 = 0; char str[128]; while(fgets(str, sizeof(str), fp)) { if(strstr(str, "v") != nullptr) { sscanf_s(str, "%f %f %f", &point.x_, &point.y_, &point.z_); //points_[loadCount++] = point; point.x_ = -point.x_; points_.emplace_back(point); } else if(strstr(str, "f") != nullptr) { sscanf_s(str, "%d//%d %d//%d %d//%d", &v1, &vn1, &v2, &vn2, &v3, &vn3); //indices_[loadCount * 3] = v1 - 1; //!< OBJファイルはインデックスが1から始まるからずらす //indices_[loadCount * 3 + 1] = v2 - 1; //indices_[loadCount * 3 + 2] = v3 - 1; indices_.emplace_back(v1 - 1); indices_.emplace_back(v2 - 1); indices_.emplace_back(v3 - 1); //++loadCount; } } } //---------------------------------------------------------- //! 頂点番号読み込み //---------------------------------------------------------- void ObjModel::loadIndex(FILE* fp) { //u32 loadCount = 0; //char str[128]; // //while(fgets(str, sizeof(str), fp)) { //} } //---------------------------------------------------------- //! 法線読み込み //---------------------------------------------------------- void ObjModel::loadNroaml() { }
#include <iostream> #include <string> #include <algorithm> #include <functional> #include <vector> #include <stack> #include <queue> #include <map> #include <set> #include <tuple> #include <numeric> #include <cmath> #include <iomanip> #include <climits> #include <sstream> #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define all(x) (x).begin(),(x).end() #define rall(x) (x).rbegin(),(x).rend() #define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() ); template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; using ll = long long; int main() { int a, b, c, d; cin >> a >> b >> c >> d; auto solve = [&]() -> int { int p = abs(a - c); int q = abs(b - d); if (p == 0 && q == 0) return 0; if (p == q || p + q <= 3) return 1; if ((p + q) % 2 == 0 || p + q <= 6 || abs(p - q) <= 3) return 2; return 3; }; cout << solve() << endl; }
/* ======================================================================== DEVise Data Visualization Software (c) Copyright 1992-1996 By the DEVise Development Group Madison, Wisconsin All Rights Reserved. ======================================================================== Under no circumstances is this software to be copied, distributed, or altered in any way without prior permission from the DEVise Development Group. */ /* $Id: TDataAppend.c,v 1.4 1996/06/21 19:33:20 jussi Exp $ $Log: TDataAppend.c,v $ Revision 1.4 1996/06/21 19:33:20 jussi Replaced MinMax calls with MIN() and MAX(). Revision 1.3 1996/01/12 15:24:21 jussi Replaced libc.h with stdlib.h. Revision 1.2 1995/09/05 22:15:47 jussi Added CVS header. */ /* Append-only Textual Data */ #include <stdio.h> #include <stdlib.h> #include "Exit.h" #include "TDataAppend.h" #include "BufMgr.h" #include "PageFile.h" /******************************************************************** Constructors ********************************************************************/ TDataAppend::TDataAppend(char *name, BufMgr *mgr, int recSize){ Initialize(name, mgr, recSize); } TDataAppend::TDataAppend(char *name, int recSize){ Initialize(name, NULL, recSize); } /************************************************************** Initialization for constructors ***************************************************************/ void TDataAppend::Initialize(char *name, BufMgr *mgr, int recSize){ _name = name; /* Get memory for returning records */ _createdMgr = false; if ((_mgr=mgr) == NULL){ _createdMgr = true; _mgr = new BufMgr(); } _pfile = new PageFile(name, _mgr); if (_pfile->NumPages() == 0){ /* a newly created file */ _header.numRecs = 0; _header.recSize = recSize; } else { /* Read header from file */ _pfile->ReadHeader(&_header, sizeof(_header)); if (_header.recSize != recSize){ fprintf(stderr,"TDataAppend::TDataAppend(%s,,%d):recSize shoudl be %d\n", name, recSize, _header.recSize); Exit::DoExit(1); } } _lastGetPageNum = -1; _returnRecs = new (void *[RecordsPerPage()]); } /********************************************************************** Destructor ***********************************************************************/ TDataAppend::~TDataAppend(){ /* printf("TDataAppend: destructor\n"); */ /* Write header back */ _pfile->WriteHeader(&_header, sizeof(_header)); /* delete the page file */ delete _pfile; if (_createdMgr) /* delete the buffer manager */ delete _mgr; delete _returnRecs; } /****************************************************************** Return # of pages ******************************************************************/ int TDataAppend::NumPages(){ return _header.numRecs / RecordsPerPage() + ( (_header.numRecs % RecordsPerPage()) == 0? 0 : 1); } /***************************************************************** Return page number of 1st page *******************************************************************/ int TDataAppend::FirstPage(){ return 1;} /****************************************************************** Return page number of last page *******************************************************************/ int TDataAppend::LastPage() { return NumPages(); }; /*********************************************************************** Get page numbers of pages currently in memory ***********************************************************************/ void TDataAppend::PagesInMem(int &numPages, int *&pageNums){ /* Report all pages except page 0 */ _pfile->PagesInMem(numPages, pageNums); } /********************************************************************* Fetch page in mem and return all records **********************************************************************/ void TDataAppend::GetPage(int pageNum, int &numRecs, RecId &startRid, void **&recs, Boolean isPrefetch){ if (pageNum < 1 || pageNum > NumPages()){ fprintf(stderr, "TDataAppend::GetPage: invalid page number %d\n", pageNum); Exit::DoExit(1); } BufPage *bpage = _pfile->GetPage(pageNum, isPrefetch); RecId firstRid = MakeRecId(pageNum, 0); numRecs = MIN(RecordsPerPage(), (int)(_header.numRecs - firstRid)); RecId lastRid = firstRid+numRecs-1; /* set return params */ startRid = firstRid; int i; char *ptr = (char *)bpage->PageData(); for (i=0; i < numRecs; i++){ _returnRecs[i] = ptr; ptr += _header.recSize; } recs = _returnRecs; _lastGetPageNum = pageNum; _lastGetPageBuf = bpage; } /********************************************************************* Return true if page in mem **********************************************************************/ Boolean TDataAppend::PageInMem(int pageNum){ return _pfile->PageInMem(pageNum); } /********************************************************************* Fetch the page containing the specified record id. Returns: pageNum: page number of the page rec: pointer to record data. FreePage() must be called to free the page ************************************************************************/ void TDataAppend::GetRecPage(RecId recId, int &pageNum, void *&rec, Boolean isPrefetch){ CheckRecId(recId); pageNum = PageNum(recId); BufPage *bpage = _pfile->GetPage(pageNum, isPrefetch); _lastGetPageNum = pageNum; _lastGetPageBuf = bpage; rec = RecordAddress(recId, bpage->PageData()); } /******************************************************************* Free page, called when page is no longer needed. *********************************************************************/ void TDataAppend::FreePage(int pageNum, BufHint hint){ if (pageNum == _lastGetPageNum){ /* free last page we got */ _pfile->UnfixPage(_lastGetPageBuf, hint); _lastGetPageNum = -1; /* page no longer cached */ } else { /* get the page back. Free it twice: once for when we got it last time. Once for now.*/ BufPage *bpage = _pfile->GetPage(pageNum); _pfile->UnfixPage(bpage, hint); _pfile->UnfixPage(bpage, hint); } } /********************************************************************** Record Oriented Interface **********************************************************************/ /**************************************************************** Return # of records *****************************************************************/ int TDataAppend::NumRecords(){ return _header.numRecs; } /***************************************************************** Return record size ********************************************************************/ int TDataAppend::RecSize(){ return _header.recSize; } /********************************************************************* Insert a new record **********************************************************************/ void TDataAppend::InsertRec(void *data){ /* update record Id */ int recId = _header.numRecs++; /* Read page from page file */ int page = PageNum(recId); BufPage *bpage; int temp; if (page > _pfile->NumPages()) /* Create a new page */ bpage = _pfile->CreatePage(temp); else /* read an existing page */ bpage = _pfile->GetPage(page); /* Write the new record onto disk */ char *recAddr = RecordAddress(recId, bpage->PageData()); bcopy((char *)data, recAddr, _header.recSize); /* mark page dirty and no longer needed */ _pfile->DirtyPage(bpage); _pfile->UnfixPage(bpage, Stay); /* Report insertion of new record */ TData::ReportNewRec(recId); } /********************************************************************** Check record id ***********************************************************************/ void TDataAppend::CheckRecId(RecId id){ if (id < 0 ||id >= _header.numRecs){ fprintf(stderr,"TDataAppend::invalid recId %d, only %d recs\n", id, _header.numRecs); Exit::DoExit(1); } }
#ifndef __QUEUE_H__ #define __QUEUE_H__ /* =============================================================================== Queue template =============================================================================== */ template< class type, int nextOffset > class idQueueTemplate { public: idQueueTemplate( void ); void Add( type *element ); type * Get( void ); private: type * first; type * last; }; #define QUEUE_NEXT_PTR( element ) (*((type**)(((byte*)element)+nextOffset))) template< class type, int nextOffset > idQueueTemplate<type,nextOffset>::idQueueTemplate( void ) { first = last = NULL; } template< class type, int nextOffset > void idQueueTemplate<type,nextOffset>::Add( type *element ) { QUEUE_NEXT_PTR(element) = NULL; if ( last ) { QUEUE_NEXT_PTR(last) = element; } else { first = element; } last = element; } template< class type, int nextOffset > type *idQueueTemplate<type,nextOffset>::Get( void ) { type *element; element = first; if ( element ) { first = QUEUE_NEXT_PTR(first); if ( last == element ) { last = NULL; } QUEUE_NEXT_PTR(element) = NULL; } return element; } /* =============================================================================== Raven Queue template =============================================================================== */ template<class TYPE, int CAPACITY> class rvQueue { TYPE mData[CAPACITY]; // Total capacity of the queue int mNewest; // Head int mOldest; // Tail int mSize; // Size... yes, this could be calculated... public: rvQueue() {clear();} int size() {return mSize;} bool empty() {return mSize==0;} bool full() {return mSize>=CAPACITY;} int begin() {return (full())?(mOldest+1):(mOldest);} int end() {return mNewest-1;} void clear() {mNewest = mOldest = mSize = 0;} bool valid(int i) {return ((mNewest>=mOldest)?(i>=mOldest && i<mNewest):(!(i>=mNewest && i<mOldest)));} void inc(int& i) {i = (i>=(CAPACITY-1))?(0):(i+1);} TYPE& first() {assert(!empty()); return mData[mOldest];} TYPE& last() {assert(!empty()); return mData[mNewest-1];} TYPE& operator[] (int i) {assert(valid(i)); return mData[i];} int push(const TYPE& value) {assert(!full()); mData[mNewest]=value; inc(mNewest); return (mSize++);} int pop() {assert(!empty()); inc(mOldest); return (mSize--);} }; /* =============================================================================== Raven Bit Vector Template =============================================================================== */ template<int CAPACITY> class rvBits { enum { BITS_SHIFT = 5, // 5. Such A Nice Number BITS_INT_SIZE = 32, // Size Of A Single Word BITS_AND = (BITS_INT_SIZE - 1), // Used For And Operation ARRAY_SIZE = ((CAPACITY + BITS_AND)/(BITS_INT_SIZE)), // Num Words Used DATA_BYTE_SIZE = (ARRAY_SIZE*sizeof(unsigned int)), // Num Bytes Used }; unsigned int mData[ARRAY_SIZE]; public: rvBits() {clear();} void clear() {memset(mData, 0, (size_t)(ARRAY_SIZE * sizeof( unsigned int )));} bool valid(const int i) {return (i>=0 && i<CAPACITY);} void unset(const int i) {assert(valid(i)); mData[i>>BITS_SHIFT] &= ~(1<<(i&BITS_AND));} void set(const int i) {assert(valid(i)); mData[i>>BITS_SHIFT] |= (1<<(i&BITS_AND));} bool operator[](const int i) {assert(valid(i)); return (mData[i>>BITS_SHIFT] & (1<<(i&BITS_AND)))!=0;} }; /* =============================================================================== Raven Pool =============================================================================== */ template<class TYPE, int CAPACITY> class rvPool { TYPE mData[CAPACITY]; TYPE* mFree[CAPACITY]; int mSize; public: rvPool() {clear();} int size() {return mSize;} bool empty() {return mSize==0;} bool full() {return mSize>=CAPACITY;} void clear() {mSize=0; for (int i=0; i<CAPACITY; i++) mFree[i]=&mData[i];} void free(TYPE* t) {assert(!empty()); mSize--; mFree[mSize]=t;} TYPE* alloc() {assert(!full()); mSize++; return mFree[mSize-1];} }; /* =============================================================================== Raven Index Pool =============================================================================== */ template<class TYPE, int CAPACITY, int INDEXNUM> class rvIndexPool { TYPE mData[CAPACITY]; TYPE* mFree[CAPACITY]; TYPE* mIndx[INDEXNUM]; int mSize; public: rvIndexPool() {clear();} int size() {return mSize;} bool empty() {return mSize==0;} bool full() {return mSize>=CAPACITY;} void clear() {mSize=0; for (int i=0; i<CAPACITY; i++) mFree[i]=&mData[i]; memset(mIndx, 0, sizeof(mIndx));} bool valid(int i) {return (i>=0 && i<INDEXNUM && mIndx[i]);} TYPE* operator[](int i) {assert(valid(i)); return mIndx[i];} TYPE* alloc(int i) {assert(!full()); mSize++; mIndx[i]=mFree[mSize-1]; return mFree[mSize-1];} void free(int i) {assert(valid(i)); mSize--; mFree[mSize]=mIndx[i]; mIndx[i]=NULL;} }; #endif /* !__QUEUE_H__ */
#include <iostream> using namespace std; #define row 10 #define col 10 #define agent 3 int shiljuuleh(int x, int y, int a[row][col]){ //4 tal niilber oloh int x1,maxs=0,max2=0; int y1=y,shilj1=-10; if(x>0){ x1=x-1; } //cout<<"x1ni "<<x1<<endl; for(int i=0; i<2; i++){ if(y1>0 && y==y1){ y1=y1-1; } if(x1>0){ x1--; }else{ break; } } //cout<<"Z shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; for(int i=y1; i<=y1+2; i++){ if(i==row){ break; } for(int j=x1;j<=j+2;j++){ if(j>x-1){ break; } maxs=maxs+a[i][j]; } } //cout<<"niilber"<<maxs<<endl; if(y>0){ y1--; } x1=x; int shilj2=-1;//(0,-1) for(int i=0; i<2; i++){ if(x1>0 && x==x1){ x1=x1-1; } if(y1>0){ y1--; } } //cout<<"Top shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; for(int i=y1; i<=y1+2; i++){ if(i==y){ break; } for(int j=x1;j<=x1+2;j++){ if(j==col){ break; } max2=max2+a[i][j]; //cout<<"niilber: "<<max2<<endl; } } //cout<<"niilber"<<max2<<endl; if(maxs<max2){ shilj1=shilj2; maxs=max2; } //right if(x+1<=col){ x1=x+1; shilj2=10;//(1,0) }else{ shilj2=0; } y1=y; max2=0; if(shilj2!=0){ if(y1-1>=0){ y1=y1-1; } } //cout<<"Right shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; for(int i=y1; i<=y1+2; i++){ if(i==row){ break; } for(int j=x1;j<=x1+2;j++){ if(j==col){ break; } max2=max2+a[i][j]; //cout<<"niilber: "<<max2<<endl; } } //cout<<"niilber"<<max2<<endl; if(maxs<max2){ shilj1=shilj2; maxs=max2; } //Bottom if(y+1<row){ y1=y+1; shilj2=1;//(0,1) }else{ shilj2=0; } x1=x; max2=0; if(shilj2!=0){ if(x1-1>=0){ x1=x1-1; } } //cout<<"Bottom shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; for(int i=y1; i<=y1+2; i++){ if(i==row){ break; } for(int j=x1;j<=x1+2;j++){ if(j==col){ break; } max2=max2+a[i][j]; //cout<<"niilber: "<<max2<<endl; } } //cout<<"niilber"<<max2<<endl; if(maxs<max2){ shilj1=shilj2; maxs=max2; } //Zuun deed if(y-1>=0&&x-1>=0){ y1=y-1; x1=x-1; shilj2=-2;//(-1,-1) }else{ shilj2=0; } for(int i=0;i<2;i++){ if(y1-1>=0&&x1-1>=0){ y1--; x1--; } } max2=0; //cout<<"zuunDeed shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; if(shilj2!=0) for(int i=y1; i<=y1+2; i++){ if(i==y){ break; } for(int j=x1;j<=x1+2;j++){ if(j==x){ break; } max2=max2+a[i][j]; //cout<<"niilber: "<<max2<<endl; } } //cout<<"niilber"<<max2<<endl; if(maxs<max2){ shilj1=shilj2; maxs=max2; } //Baruun deed if(y-1>=0&&x+1<col){ y1=y-1; x1=x+1; shilj2=-2;//(-1,-1) }else{ shilj2=0; } for(int i=0;i<2;i++){ if(y1-1>=0&&x1+1<col){ y1--; x1++; } } max2=0; //cout<<"baruunDeed shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; if(shilj2!=0) for(int i=y1; i<=y1+2; i++){ if(i==y){ break; } for(int j=x1;j<=x1+2;j++){ if(j==col){ break; } max2=max2+a[i][j]; //cout<<"niilber: "<<max2<<endl; } } //cout<<"niilber"<<max2<<endl; if(maxs<max2){ shilj1=shilj2; maxs=max2; } //Baruun dood if(y+1<row&&x+1<col){ y1=y+1; x1=x+1; shilj2=11;//(1,1) }else{ shilj2=0; } for(int i=0;i<2;i++){ if(y1+1<row&&x1+1<col){ y1++; x1++; } } max2=0; //cout<<"baruunDood shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; if(shilj2!=0) for(int i=y1; i<=y1+2; i++){ if(i==row){ break; } for(int j=x1;j<=x1+2;j++){ if(j==col){ break; } max2=max2+a[i][j]; //cout<<"niilber: "<<max2<<endl; } } //cout<<"niilber"<<max2<<endl; if(maxs<max2){ shilj1=shilj2; maxs=max2; } //Zuun dood if(y+1<row&&x-1>=0){ y1=y+1; x1=x-1; shilj2=2;//(1,-1) }else{ shilj2=0; } for(int i=0;i<2;i++){ if(y1+1<row&&x1-1>=0){ y1++; x1--; } } max2=0; //cout<<"zuunDood shalgah: "<<x1<<" "<<y1<<" "<<a[y1][x1]<<endl; if(shilj2!=0) for(int i=y1; i<=y1+2; i++){ if(i==row){ break; } for(int j=x1;j<=x1+2;j++){ if(j<0){ break; } max2=max2+a[i][j]; //cout<<"niilber: "<<max2<<endl; } } //cout<<"niilber"<<max2<<endl; if(maxs<max2){ shilj1=shilj2; maxs=max2; } //cout<<"ilgeeh "<<shilj1<<endl; return shilj1; } void shiljih(int l){ switch(l){ case 1: cout<<"0 "<<"1\n"; break; case -1: cout<<"0 "<<"-1\n"; break; case 0: //cout<<"0 "<<"0\n"; break; case 10: cout<<"1 "<<"0\n"; break; case -10: cout<<"-1 "<<"0\n"; break; case -11: cout<<"-1 "<<"1\n"; break; case -2: cout<<"-1 "<<"-1\n"; break; case 2: cout<<"1 "<<"-1\n"; break; case 11: cout<<"1 "<<"1\n"; break; default: break; } } int maxn(int x, int y, int a[10][10]){ int b1=x, b2=y, q1,q2,max; max=a[b1-1][b2-1]; q1=-1;q2=-1; if(max<a[b1][b2-1]){ max=a[b1][b2-1]; q1=0;q2=-1; } if(max<a[b1+1][b2-1]){ max=a[b1+1][b2-1]; q1=1;q2=-1; } if(max<a[b1+1][b2]){ max=a[b1+1][b2]; q1=1;q2=0; } if(max<a[b1+1][b2+1]){ max=a[b1+1][b2+1]; q1=1;q2=1; } if(max<a[b1][b2+1]){ max=a[b1][b2+1]; q1=0;q2=+1; } if(max<a[b1-1][b2+1]){ max=a[b1-1][b2+1]; q1=-1;q2=1; } if(max<a[b1-1][b2]){ max=a[b1-1][b2]; q1=-1;q2=0; } if(b1+q1==col){ q1=q1-1; }else if(b1+q1<0){ q1=q1+1; } if(b2+q2==row){ q2=q2-1; }else if(b2+q2<0){ q2=q2+1; }; return q1; cout<<q1<<" "<<q2<<endl; } int maxy(int x, int y, int a[10][10]){ int b1=x, b2=y, q1,q2,max; max=a[b1-1][b2-1]; q1=-1;q2=-1; if(max<a[b1][b2-1]){ max=a[b1][b2-1]; q1=0;q2=-1; } if(max<a[b1+1][b2-1]){ max=a[b1+1][b2-1]; q1=1;q2=-1; } if(max<a[b1+1][b2]){ max=a[b1+1][b2]; q1=1;q2=0; } if(max<a[b1+1][b2+1]){ max=a[b1+1][b2+1]; q1=1;q2=1; } if(max<a[b1][b2+1]){ max=a[b1][b2+1]; q1=0;q2=+1; } if(max<a[b1-1][b2+1]){ max=a[b1-1][b2+1]; q1=-1;q2=1; } if(max<a[b1-1][b2]){ max=a[b1-1][b2]; q1=-1;q2=0; } if(b1+q1==col){ q1=q1-1; }else if(b1+q1<0){ q1=q1+1; } if(b2+q2==row){ q2=q2-1; }else if(b2+q2<0){ q2=q2+1; }; return q2; } class point { public: int x; int y; int tolow;//0-uyd ezlegdeegui 1-uyd ezlegdsen point(){ tolow=0; } }; main(){ point pnt; int a[row][col]={ {4, 3, 7, 2, -2, -2, 2, 7, 3, 4}, {1, -5, -1, 3, -8, -8, 3, -1, -5, 1}, {8, 4, 2, -1, 5, 5, -1, 2, 4, 8}, {-4, 1, 1, 0, 4, 4, 0, 1, 1, -4}, {6, -2, -6, 3, -3, -3, 3, -6, -2, 6}, {6, -2, -6, 3, -3, -3, 3, -6, -2, 6}, {-4, 1, 1, 0, 4, 4, 0, 1, 1, -4}, {8, 4, 2, -1, 5, 5, -1, 2, 4, 8}, {1, -5, -1, 3, -8, -8, 3, -1, -5, 1}, {4, 3, 7, 2, -2, -2, 2, 7, 3, 4} }; int i,j,max; cout<<"\t"; for(i=0;i<row;i++) cout<<"x-"<<i<<"\t"; cout<<endl<<"\n"; for(i=0;i<row;i++){ cout<<"y-"<<i<<"\t"; for(j=0;j<col;j++){ cout<<a[i][j]<<"\t"; } cout<<endl; } int x1,y1,l,max2; cout<<"Odoo baigaa bairlal\n"; cout<<"\nx1: "; cin>>x1; cout<<"ny2: ";c cin>>y1; int b1,b2,q1,q2,p[100],c[100],op=0; for(i=1;i<=30;i++){ q1=0; q2=0; b1=x1; b2=y1; cout<<"Tolgoi"<<a[y1][x1]<<endl; a[y1][x1]=0; p[op]=y1; c[op]=x1; op++; l=shiljuuleh(x1,y1,a); cout<<"l ni "<<l<<endl; shiljih(l); switch(l){ case 1: y1=y1+1; break; case -1: y1=y1-1; break; case 0: q1=maxn(x1,y1,a); q2=maxy(x1,y1,a); x1=x1+q1; y1=y1+q2; break; case 10: x1++;//cout<<"1 "<<"0\n"; break; case -10: x1--;//cout<<"-1 "<<"0\n"; break; case -11: x1--;y1++;//cout<<"-1 "<<"1\n"; break; case -2: x1--; y1--;//cout<<"-1 "<<"-1\n"; break; case 2: x1++;y1--;//cout<<"1 "<<"-1\n"; break; case 11: x1++; y1++;//cout<<"1 "<<"1\n"; break; default: break; } } }
#ifndef BIDIRECTIONAL_IMPL_H #define BIDIRECTIONAL_IMPL_H #include "bidirectionallist.h" template<> inline void BidirectionalList::push_back(const int & val) { ListItem * item = new IntegerListItem(val); push_back_impl(item); } template<> inline void BidirectionalList::push_back(const float & val) { ListItem * item = new FloatListItem(val); push_back_impl(item); } template<> inline void BidirectionalList::push_back(const std::string & val) { ListItem * item = new StringListItem(val); push_back_impl(item); } template<> inline void BidirectionalList::push_front(const int & val) { ListItem * item = new IntegerListItem(val); push_front_impl(item); } template<> inline void BidirectionalList::push_front(const float & val) { ListItem * item = new FloatListItem(val); push_front_impl(item); } template<> inline void BidirectionalList::push_front(const std::string & val) { ListItem * item = new StringListItem(val); push_front_impl(item); } namespace { template<class T> inline BidirectionalList::const_iterator insertBoundary(BidirectionalList & list, BidirectionalList::const_iterator pos, const T & val) { BidirectionalList::const_iterator res; BidirectionalList::const_iterator itBeg = list.begin(); BidirectionalList::const_iterator itEnd = list.end(); if (pos == itBeg) { list.push_front(val); res = itBeg; } else if (pos == itEnd) { list.push_back(val); res = --itEnd; } return res; } } template<> inline BidirectionalList::const_iterator BidirectionalList::insert(BidirectionalList::const_iterator pos, const int & val) { if (pos == begin() || pos == end()) return insertBoundary(*this, pos, val); else { ListItem * item = new IntegerListItem(val); return insert_impl(item, pos); } } template<> inline BidirectionalList::const_iterator BidirectionalList::insert(BidirectionalList::const_iterator pos, const float & val) { if (pos == begin() || pos == end()) return insertBoundary(*this, pos, val); else { ListItem * item = new FloatListItem(val); return insert_impl(item, pos); } } template<> inline BidirectionalList::const_iterator BidirectionalList::insert(BidirectionalList::const_iterator pos, const std::string & val) { if (pos == begin() || pos == end()) return insertBoundary(*this, pos, val); else { ListItem * item = new StringListItem(val); return insert_impl(item, pos); } } #endif // BIDIRECTIONAL_IMPL_H
#pragma once #include <stdint.h> #include <memory> #include "MPGUID.h" class MatchUser { public: MatchUser(double fRating = 1500.0f); virtual ~MatchUser(); public: double RoundRating(double places); double GetRating()const; void SetRating(double fRate); private: MPGUID m_uid; double m_fRating; }; typedef std::shared_ptr<MatchUser> MatchUserPtr;
#include<iostream> #include<string> #include<stdio.h> #include<stdlib.h> using namespace std; //ham kiem tra string bool kiemtra(string chuoi) { int length=chuoi.length(); for(int i=0;i<length;i++) { if(chuoi[i]>'9'||chuoi[i]=='.') { return false; break; } } return true; } //ham age int age(int tuoi) { return 2018-tuoi; } // ham tinh Tong-Hieu-Tich Thuong int sum(int a,int b) { return a+b; } int branf(int a,int b) { return a-b; } int Accomplishments(int a,int b) { return a*b; } float division(int a,int b) { return (float)a/b; } // ham san pham ,so luong -don gia string ten(string t) { return t; } int soluong(int a,int b) { return Accomplishments(a,b); } int main() { int Tuoi; vuongmin: do { string tuoi; cout<<"\n nhap Nam Sinh :\t"; getline(cin,tuoi); int check=kiemtra(tuoi); if(check==false) { cout<<"\n ban nhap sai kieu du lieu! vui long kiem tra lai."; goto vuongmin; } else { Tuoi=atof((char *)tuoi.c_str()); if(Tuoi<0) { cout<<"\n ban nhap sai tuoi!"; } } }while(Tuoi<0); cout<<"\n Tuoi ="<<age(Tuoi); int a,b; cout<<"\n nhap a:\t"; cin>>a; cout<<"\n nhap b:\t"; cin>>b; int tong=sum(a,b); int hieu=branf(a,b); int tich=Accomplishments(a,b); float thuong=division(a,b); cout<<"\n Tong ="<<tong; cout<<"\n Hieu ="<<hieu; cout<<"\n Tich ="<<tich; cout<<"\nThuong ="<<thuong; //san pham string Ten; fflush(stdin); cout<<"\n nhap Ten:\t"; getline(cin,Ten); cout<<"\n Ten = "<<ten(Ten); int sl,dg; cout<<"\n nhap vao so luong:\t"; cin>>sl; cout<<"\n nhap DON Gia:\t"; cin>>dg; int so=soluong(sl,dg); cout<<"\n Tien ="<<so; float Thue=(float)so*0.1; cout<<"\n Thue ="<<Thue; return 0; } //#include<iostream> //#include<string> //#include<stdio.h> //#include<stdlib.h> //using namespace std; ///*NHậP NăM SINH CủA MộT NGườI. //TíNH TUổI NGườI đó.*/ //int age(int &tuoi) //{ // cout<<"\n nhap vao nam sinh:\t"; // cin>>tuoi; // // // // // return 2018-tuoi; //} ///*Nhập 2 số a và b. //Tính tổng, hiệu, tính và thương của hai số đó.*/ //void calculate(int &a,int &b) //{ // cout<<"\n nhap a:\t"; // cin>>a; // cout<<"\n nhap b:\t"; // cin>>b; // cout<<"\n Tong =\t"<<a+b; // cout<<"\n Hieu =\t"<<a-b; // cout<<"\n Tich =\t"<<a*b; // cout<<"\n Thuong =\t"<<(float)a/b; // //} ///*Nhập tên sản phẩm, số lượng và đơn giá. //Tính tiền và thuế giá trị gia tăng phải trả, biết: //a. tiền = số lượng * đơn giá //b. thuế giá trị gia tăng = 10% tiền*/ // //void product(string &sp,int &sl,int &dg) //{ // fflush(stdin); // cout<<"\n nhap ten san pham:\t"; // getline(cin,sp); // // cout<<"\n nhap vao so luong:\t"; // cin>>sl; // cout<<"\n nhap vao don gia:\t"; // cin>>dg; // int tien=sl*dg; // double thue=(double)tien*0.1; // cout<<"\n Ten San Pham :\t"<<sp; // cout<<"\n Tien ="<<tien<<"\t Thue Gia Tang = "<< thue; //} ///*Nhập điểm thi và hệ số 3 môn Toán, Lý, Hóa //của một học sinh. Tính điểm trung bình của //học sinh đó*/ // float dtb(float toan,float ly,float hoa) // { // return (toan+ly+hoa)/3; // } // /*Nhập vào số xe của bạn (gồm tối đa 5 chữ số). //Cho biết số xe của bạn được mấy nút?*/ //int soxe(int &so) //{ // cout<<"\n nhap so xe:\t"; // cin>>so; // //4520 // int a=so/1000;//4 // int a1=so%1000;//520 // int b=a1/100;//5 // int b1=a1%100;//20 // int c=b1/10;//2 // int c1=b1%10; // return (a+b+c+c1)%10; // // //} ////tim min max bang thuat toan ngoi 3 ////vi cai ham int main ko co cin a,b nen moi co the lam duoc nhu vay ////vi cac ham tren deu nhay tham chieu trong ham het roi do! //int max(int a,int b) //{ // return a>b?a:b; // //} //int min(int a,int b) //{ // return a<b?a:b; //} // //int main() //{ string c; // int t=age(t),a,b; // float toan,ly,hoa; // cout<<"\n tuoi :\t"<<t; // cout<<"\n ------Tong -Hieu-Tich -THuong------ "; // calculate(a,b); // product(c,b,t); // cout<<"\n nhap Toan:\t"; // cin>>toan; // cout<<"\n nhap Ly:\t"; // cin>>ly; // cout<<"\n nhap Hoa:\t"; // cin>>hoa; // cout<<"\n Diem Tb =\t"<<dtb(toan,ly,hoa); // cout<<"\n so xe ="<<soxe(a); // cout<<"\n max ---- min\n"; // cout<<" \n max ="<<max(6,9); // cout<<"\n min =\t"<<min(6,9); // // return 0; //}
#include "Spaceship.h" #include "Definitions.h" #include "audio/include/SimpleAudioEngine.h" using namespace CocosDenshion; USING_NS_CC; // Initialize instance (sprite) bool Spaceship::init() { // Super init first if (!Sprite::initWithFile("Spaceship.png")) return false; this->setPosition(ORIGIN.x + V_SIZE.width * SPACESHIP_X_POS, CENTER_Y); // Start applying gravity // We delay it by the scene transition time to avoid teleports at the start of the game this->schedule(schedule_selector(Spaceship::fall), PHYSICS_UPDATE_INTERVAL, CC_REPEAT_FOREVER, SCENE_TRANSITION_TIME); return true; } // Spaceship's "jump" void Spaceship::boost() { if (!isControllable_) return; SimpleAudioEngine::getInstance()->playEffect(BOOST_SOUND_EFFECT); currentSpeed_ = BOOSTER_SPEED; } // Plays basic animation void Spaceship::onCrash() { if (!isControllable_) return; isControllable_ = false; SimpleAudioEngine::getInstance()->playEffect(CRASH_SOUND_EFFECT); // Moves left and rotates this->runAction(RepeatForever::create(MoveBy::create(1, Vec2(-(PILLAR_SPEED * V_SIZE.width) * CRASH_SPEED_K, 0)))); this->runAction(RepeatForever::create(RotateBy::create(1, -CRASH_ROTATION_SPEED))); } // Movement affected by gravity void Spaceship::fall(float dT) { this->setPositionY(this->getPositionY() + currentSpeed_ * dT); currentSpeed_ -= GRAVITY_FORCE * dT; if (isControllable_) this->setRotation(currentSpeed_ * SPEED_TO_ANGLE); }
/**************************************************************************************************************** ** Created: June 21st 2020 * ** Author: Sysadmin * ** How much will I earn in a year depending on what happens. * ** 1) Monthly earnings - fixed income 4500 USD - normal distribution * ** 2) Monthly expenses - distribution by interval - Gaussian distribution, average value 2000, deviation 1500 * ** 3) Termination of the employment contract - discrete distribution * ** 4) Additional salary - on call (business phone from work in case of emergency * ** - taking action e.g. at night or at the weekend), overtime - a discrete distribution * ** 5) Change of the job - low probability (large earnings in the current company) / large change in salary, * ** when it changes - 9000 USD - discrete distribution. * ** 6) Change of the department in current work - high probability 5000 USD - discrete distribution * ** 7) Graduation - very high probability - discrete distribution * ** 8) Bank loan - average probability - discrete distribution * ** 9) Jackpot win - low probability - discrete distribution * ** Time: 12 months = 1 year * ** Measurements are made for 5000 samples. * ** Maximum earnings are calculated for a value less than the minimum jackpot win. * ** Classes quantity = 30 * ****************************************************************************************************************/ #include <iostream> /** #include <stdio.h> /// standard input/output in linux. **/ #include <cstdlib> #include <cmath> #include <fstream> int change_of_department=0; int change_of_the_job=0; double probability_of_department_change=0.2; double probability_of_graduation=0.9; double probability_of_loan=0.5; bool change1=false; double Generator(); double MonthlyEarnings(int month); ///point number 1 double MonthlyExpenses(); ///point number 2 double ContractTermination(); ///point number 3 double AdditionalSalary(); ///point number 4 bool JobChange(); ///point number 5 bool DepartmentChange(); ///point number 6 bool Graduation(); ///point number 7 bool BankLoan(); ///point number 8 double JackpotWin(); ///point number 9 double GaussDistribution(double AverageEarnings, double deviation); int main() { int ClassesQuantity=30; double ClassesWidth; int l; int quantity[30]; double Earnings[5000]; for (int i=0; i<5000; i++) { change_of_department=0; change_of_the_job=0; probability_of_department_change=0.2; probability_of_graduation=0.9; probability_of_loan=0.5; Earnings[i]=Generator(); std::cout<<"My earnings after a year: "<<Earnings[i]<<std::endl; } double minimum = Earnings[0]; double maximum = Earnings[0]; for(int i=1;i<5000;i++) { if(minimum>Earnings[i]) minimum = Earnings[i]; if(maximum<Earnings[i]&&Earnings[i]<5000000.0) maximum = Earnings[i]; } ClassesWidth=(maximum-minimum)/ClassesQuantity; for (int j=0;j<5000; j++) { if (Earnings[j]<5000000.0) { l=int((Earnings[j]-minimum)/ClassesWidth); quantity[l]++; } else { quantity[30]++; } } std::ofstream file("results.csv", std::ofstream::out); for (int t=0; t<30; t++) { file<<"Class: "<<t<<"; "<<quantity[t]<<std::endl; std::cout<<"Class: "<<t<<" quantity: "<<quantity[t]<<std::endl; } std::cout <<"The End."<<std::endl; std::cout<<"File results.csv contains simulated quantity of numbers in each class."<<std::endl; return 0; } double Generator () { double Earnings=0.0; for (int i=0; i<12; i++) { Earnings=Earnings+MonthlyEarnings(i)+AdditionalSalary()+Graduation(); Earnings=Earnings-MonthlyExpenses()-ContractTermination()-BankLoan(); for (int j=0; j<4; j++) { Earnings=Earnings+JackpotWin(); } } return Earnings; } ///point number 1 double MonthlyEarnings(int month) { double salary=4500.0+2000.0*change_of_department+5000.0*change_of_the_job; if(month%12==0 && month>0){ bool change=true; if(change==true) { change1=JobChange(); if(change1==true) { change=false; change_of_the_job++; change_of_department=0; } } if(DepartmentChange()==true&&change==true) { change_of_department++; } } return salary; } ///point number 2 double MonthlyExpenses() { double expenses=GaussDistribution(2000.0,1500.0); return expenses; } ///point number 3 double ContractTermination() { double contract_termination=0.0; double probability_of_termination=0.6; double r1=0.0; r1=rand()/double(RAND_MAX); if(r1<probability_of_termination) { contract_termination=rand()/double(RAND_MAX)*(4500.0-600.0)+600.0; } return contract_termination; } ///point number 4 double AdditionalSalary() { double onCall=0.0; double probability_of_additional_salary=0.3; double r2=0.0; r2=rand()/double(RAND_MAX); if(r2<probability_of_additional_salary) { onCall=rand()/double(RAND_MAX)*(2500.0-1200.0)+1200.0; } return onCall; } ///point number 5 bool JobChange() { bool JobChange=false; double probability_of_change=0.01; double r3=0.0; r3=rand()/double(RAND_MAX); if(r3<probability_of_change) { JobChange=true; } return JobChange; } ///point number 6 bool DepartmentChange() { bool change_of_the_department=false; double r4=0.0; r4=rand()/double(RAND_MAX); if(r4<probability_of_department_change) { probability_of_department_change=0.2; change_of_the_department=true; } else { probability_of_department_change=probability_of_department_change+0.1; } return change_of_the_department; } ///point number 7 bool Graduation() { bool Graduation=false; double r5=0.0; r5=rand()/double(RAND_MAX); if(r5<probability_of_graduation) { probability_of_graduation=0.9; Graduation=true; } else { probability_of_graduation=probability_of_graduation+0.1; } return Graduation; } ///point number 8 bool BankLoan() { bool loan=false; double r6=0.0; r6=rand()/double(RAND_MAX); if(r6<probability_of_loan) { probability_of_loan=0.5; loan=true; } else { probability_of_loan=probability_of_loan+0.1; } return loan; } ///point number 9 double JackpotWin() { double win=0.0; double probability_of_win=0.000001; double r7=0.0; r7=rand()/double(RAND_MAX); if(r7<probability_of_win) { win=rand()/double(RAND_MAX)*(15000000.0-5000000.0)+5000000.0; } return win; } double GaussDistribution(double AverageEarnings, double deviation) { double pii=3.1415927; double r_max=RAND_MAX; return (double)round(deviation*sqrt(-2.0*log((rand()+1.0)/r_max))*sin(2.0*pii*rand()/r_max)+AverageEarnings); }