text
stringlengths
8
6.88M
/* ID: stevenh6 TASK: zerosum LANG: C++ */ #include <fstream> #include <iostream> #include <string> using namespace std; ofstream fout ("zerosum.out"); ifstream fin ("zerosum.in"); int n; int oset[10] = {0}; void check() { int sign = 1; int r = 0; int oper = 0; for (int i = 1; i <= n - 1; ++i) { oper = oper * 10 + i; if (oset[i] == 1) { r += oper * sign; oper = 0; sign = 1; } else if (oset[i] == 2) { r += oper * sign; oper = 0; sign = -1; } } oper = oper * 10 + n; r += oper * sign; if (r != 0) { return; } for (int i = 1; i <= n - 1; ++i) { fout << i; if (oset[i] == 1) { fout << "+"; } else if (oset[i] == 2) { fout << "-"; } else if (oset[i] == 0) { fout << " "; } } fout << n << endl; } void search(int pos) { if (pos >= n) { check(); return; } for (int i = 0; i < 3; i++) { oset[pos] = i; search(pos + 1); } } int main() { fin >> n; search(1); }
/** ( ( )\ ) ( )\ (()/( ( ) ( ( ( ( )((_) /(_)) ))\( /( )( ( )\ ( )\))( ((_)_ (_)) /((_)(_)|()\ )\ |(_) )\ )((_))\ / _ \ | | (_))((_)_ ((_)_(_/((_)_(_/( (()(_) | (_) | | |__/ -_) _` | '_| ' \)) | ' \)) _` | \__\_\ |____\___\__,_|_| |_||_||_|_||_|\__, | |___/ Refer to Watkins, Christopher JCH, and Peter Dayan. "Q-learning." Machine learning 8. 3-4 (1992): 279-292 for a detailed discussion on Q Learning */ #include "CQLearningController.h" #include <vector> #include <iostream> using namespace std; CQLearningController::CQLearningController(HWND hwndMain): CDiscController(hwndMain), _grid_size_x(CParams::WindowWidth / CParams::iGridCellDim + 1), _grid_size_y(CParams::WindowHeight / CParams::iGridCellDim + 1) { } /** The update method should allocate a Q table for each sweeper (this can be allocated in one shot - use an offset to store the tables one after the other) You can also use a boost multiarray if you wish Initialises a 2d vector of states with 4 action per state with values of 0.0 */ void CQLearningController::InitializeLearningAlgorithm(void) { for (uint i = 0; i < _grid_size_x; i++) { vector<vector<double> > temp; for (uint j = 0; j < _grid_size_y; j++) { vector<double> temp2(4, 0.0); temp.push_back(temp2); } Qmatrix.push_back(temp); } resetDeadQ(); } /** The immediate reward function. This computes a reward upon achieving the goal state of collecting all the mines on the field. It may also penalize movement to encourage exploring all directions and of course for hitting supermines/rocks! */ double CQLearningController::R(uint x,uint y, uint sweeper_no){ double reward = 0.0; int found = ((m_vecSweepers[sweeper_no])->CheckForObject(m_vecObjects, CParams::dMineScale)); if (found >= 0) { switch (m_vecObjects[found]->getType()) { case CDiscCollisionObject::Mine: { if (!m_vecObjects[found]->isDead()) { //If we hit a mine, return a nice positve reward reward = 100.0; } break; } case CDiscCollisionObject::Rock: { //we hit a rock and died, so return a negative reward reward = -100.0; break; } case CDiscCollisionObject::SuperMine: { //we hit a supermine and died, returna negative reward reward = -100.0; break; } } } return reward; } /** The update method. Main loop body of our Q Learning implementation See: Watkins, Christopher JCH, and Peter Dayan. "Q-learning." Machine learning 8. 3-4 (1992): 279-292 */ bool CQLearningController::Update(void) { // Writes out data to a file to be used in the report if (m_iterations > 50) { ofstream out; out.open("output.txt"); double tGathered = 0; double tDeaths = 0; int highestGathered = 0; for (int i = 0; i < 50; i++) { tGathered += m_vecMostMinesGathered[i]; tDeaths += m_vecDeaths[i]; if (m_vecAvMinesGathered[i] > highestGathered) highestGathered = m_vecAvMinesGathered[i]; } out << "Most mines gathered: " << highestGathered << endl; out << "Average mines gathered: " << double(tGathered / 50) << endl; out << "Average mines deaths: " << double(tDeaths / 50) << endl; out.close(); } //m_vecSweepers is the array of minesweepers //everything you need will be m_[something] ;) uint cDead = std::count_if(m_vecSweepers.begin(), m_vecSweepers.end(), [](CDiscMinesweeper * s)->bool{ return s->isDead(); }); if (cDead == CParams::iNumSweepers){ printf("All dead ... skipping to next iteration\n"); m_iTicks = CParams::iNumTicks; epsilon -= 0.01; learning_rate -= 0.02; resetDeadQ(); m_iterations++; } for (uint sw = 0; sw < CParams::iNumSweepers; ++sw) { if (m_vecSweepers[sw]->isDead()) continue; //1:::Observe the current state: SVector2D<int> position = m_vecSweepers[sw]->Position(); position /= CParams::iGridCellDim; //2:::Select action with highest historic return: // Epsilon Greedy Strategy was used here double r = RandFloat(); // Exploration is chosen if (r < epsilon) { double highest = Qmatrix[position.x][position.y][0]; for (uint i = 1; i < 4; i++) { if (highest < Qmatrix[position.x][position.y][i]) highest = Qmatrix[position.x][position.y][i]; } vector<int> duplicates; for (uint i = 0; i < 4; i++) { if (highest == Qmatrix[position.x][position.y][i]) duplicates.push_back(i); } int randaction = RandInt(0, duplicates.size() - 1); m_vecSweepers[sw]->setRotation((ROTATION_DIRECTION)duplicates[randaction]); } // Exploitation is chosen else { double highest = Qmatrix[position.x][position.y][0]; for (uint i = 1; i < 4; i++) { if (highest < Qmatrix[position.x][position.y][i]) highest = i; } int action = (int)highest; m_vecSweepers[sw]->setRotation((ROTATION_DIRECTION)action); } } //now call the parents update, so all the sweepers fulfill their chosen action CDiscController::Update(); //call the parent's class update. Do not delete this. for (uint sw = 0; sw < CParams::iNumSweepers; ++sw){ if (m_vecSweepers[sw]->isDead() && dead_Q[sw]) continue; //TODO:compute your indexes.. it may also be necessary to keep track of the previous state // Allows a sweeper that has hit a mine to still run its iteration and update its reward else if (m_vecSweepers[sw]->isDead()) dead_Q[sw] = true; //3:::Observe new state: SVector2D<int> prev = m_vecSweepers[sw]->PrevPosition(); prev /= CParams::iGridCellDim; SVector2D<int> current = m_vecSweepers[sw]->Position(); current /= CParams::iGridCellDim; int action = (int)m_vecSweepers[sw]->getRotation(); //4:::Update _Q_s_a accordingly: // Finds the action with the highest value in the specific position double highest = Qmatrix[current.x][current.y][0]; for (uint i = 1; i < 4; i++) { if (highest < Qmatrix[current.x][current.y][i]) highest = Qmatrix[current.x][current.y][i]; } Qmatrix[prev.x][prev.y][action] += learning_rate * (R(current.x, current.y, sw) + (discount_factor * highest) - Qmatrix[prev.x][prev.y][action]); } // Changes the values and resets the Q dead matrix every iteration if (m_iTicks == CParams::iNumTicks) { resetDeadQ(); epsilon -= 0.01; learning_rate -= 0.02; m_iterations++; } return true; } /* Initialises the dead_Q table to falses so that when it checks in the update function, it allows it to iterate and update the Q value with a negative reward */ void CQLearningController::resetDeadQ() { dead_Q.clear(); for (int i = 0; i < CParams::iNumSweepers; i++) { dead_Q.push_back(false); } } CQLearningController::~CQLearningController(void) { //TODO: dealloc stuff here if you need to }
#pragma once #include "baseview.hpp" #include "mapview.hpp" struct MainView : BaseView { MainView(struct ViewStack* vs, struct City* c); virtual void render_body(Graphics& g, render_box const& pos) override; virtual void handle_keypress(KeyboardKey ks) override; struct HelpView* hview; struct UnitView* uview; struct AnnounceView* aview; struct DesignView* dview; struct City* city; MapView mv; };
#include <iostream> #include <fstream> using namespace std; int a[100][100], n, m; void bf(int start) { int vizitat[n + 1] = {0}; int prim, ultim; // prim si ultim reprezinta prima, respectiv ultima pozitie din coada prim = ultim = 1; // la inceput coada este goala, deci prima pozitia este egala cu ultima pozitie (=1) int c[n + 1]; // coada c[ultim] = start; // adaugam nodul de inceput in coada vizitat[start] = 1; // marcam nodul de start ca vizitat cout << start << " "; while (prim <= ultim) // conditia care ne spune daca coada este vida sau nu ( este vida cand prim > ultim ) { int curent = c[prim]; // extragem primul nod din coada si ii vom cauta vecinii nevizitati for (int i = 1; i <= n; i++) // parcurgem toate nodurile grafului { if (a[curent][i] == 1) // daca i este vecin al nodului curent if (vizitat[i] == 0) // daca i este un vecin nevizitat al nodului curent { ultim++; // marim coada c[ultim] = i; // il adaugam pe i in coada vizitat[i] = 1; // il marcam pe i ca vizitat cout << i << " "; } } prim++; // trecem la urmatoarea pozitie in coada (adica ignoram elementele deja parcurse ca sa nu le parcurgem iar) } cout << endl; } int main() { ifstream f("fis.in"); f >> n >> m; for (int i = 0; i < m; i++) { int x, y; f >> x >> y; a[x][y] = a[y][x] = 1; } int start; cout << "Introduceti nodul de start: "; cin >> start; bf(start); f.close(); return 0; }
// Copyright 2012 Yandex #include <cmath> #include "ltr/density_estimators/non_linear_discriminant.h" #include "ltr/utility/eigen_converters.h" using ltr::NonLinearDiscriminant; using ltr::utility::InitEigenMatrix; using ltr::utility::InitEigenVector; namespace ltr { double NonLinearDiscriminant::estimate(const Object& object, const double label) { VectorXd features(object.feature_count()); InitEigenVector(&features); for (int feature_index = 0; feature_index < object.feature_count(); ++feature_index) { features[feature_index] = object[feature_index]; } int feature_count = object.feature_count(); double result = log(pow(M_PI, - feature_count / 2.0) * pow(covariance_matrix_[label].determinant(), -0.5)); result -= 0.5 * (features - mean_[label]).transpose() * covariance_matrix_[label].inverse() * (features - mean_[label]); return result; } };
/*! * \file mpredelegate.h * \author Simon Coakley * \date 2012 * \copyright Copyright (c) 2012 University of Sheffield * \brief Header file for mpre delegate */ #ifndef MPREDELEGATE_H_ #define MPREDELEGATE_H_ #include <QItemDelegate> #include <QModelIndex> #include <QObject> #include <QSize> #include <QSpinBox> #include <QDoubleSpinBox> #include <QComboBox> #include "./memorymodel.h" #include "./machine.h" #include "./communication.h" class MpreDelegate : public QItemDelegate { Q_OBJECT public: MpreDelegate(Machine * machine, Communication * comm = 0, QObject *parent = 0); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const; void setEditorData(QWidget *editor, const QModelIndex &index) const; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const; /*void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const;*/ private slots: void commitAndCloseEditor(); private: MemoryModel * memory; Machine * machine; Communication * communication; }; #endif // MPREDELEGATE_H_
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <Wire.h> #include <VL6180X.h> char ssid[] = "FIT5140"; char pass[] = "fit5140password"; ESP8266WebServer server(80); VL6180X sensor; String webString = ""; uint8_t distance; void setup(void) { Serial.begin(115200); WiFi.begin(ssid, pass); Serial.println("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(WiFi.localIP()); Wire.begin(4, 5); sensor.init(); sensor.configureDefault(); sensor.setTimeout(500); server.on("/", [](){ distance = sensor.readRangeSingleMillimeters(); Serial.println(distance); if (distance > 100) webString = "OPEN"; else webString = "CLOSED"; server.send(200, "text/plain", webString); }); server.begin(); Serial.println("HTTP server started!"); } void loop(void) { server.handleClient(); }
#include"conio.h" #include"stdio.h" void main(void) { int a,x=0; clrscr(); printf("Enter value: "); scanf("%d",&a); for(int i=1; i<=a; i++){ x+=(a%i==0); if(x>2) break; } if(x==2) printf("%d, is Prime No.",a); else printf("%d is Not Prime No.",a); getch(); }
#include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define sful(a) scanf("%llu",&a); #define sfulul(a,b) scanf("%llu %llu",&a,&b); #define sful2(a,b) scanf("%llu %llu",&a,&b); // A little different #define sfc(a) scanf("%c",&a); #define sfs(a) scanf("%s",a); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define vi vector<int> #define vll vector<ll> #define mii map<int,int> #define mlli map<ll,int> #define mib map<int,bool> #define fs first #define sc second #define CASE(t) printf("Case %d:\n",++t) // t initialized 0 #define cCASE(t) cout<<"Case "<<++t<<": "; #define D(v,status) cout<<status<<" "<<v<<endl; #define INF 10000000000 //10e9 #define EPS 1e-9 #define flc fflush(stdout); //For interactive programs , flush while using pf (that's why __c ) #define CONTEST 1 using namespace std; ll arr[107]; ll revarr[107]; int main() { //write(); int tc,cas =0; sfi(tc); while(tc--) { int n,m; sfii(n,m); loop(i,1,n) sfl(arr[i]); loop(i,1,m) { char qt; cin>>qt; int A,B; if(qt=='S') { sfi(A); loop(i,1,n) { arr[i]+=A; } } else if(qt=='M') { sfi(A); loop(i,1,n) { arr[i]*=A; } } else if(qt=='D') { sfi(A); loop(i,1,n) { arr[i]/=A; } } else if(qt=='R') { loop(i,1,n) { revarr[n-i+1] = arr[i]; } loop(i,1,n) { arr[i] = revarr[i]; } } else if(qt=='P') { sfii(A,B); A++; B++; ll tmp = arr[A]; arr[A] = arr[B]; arr[B] = tmp; } //cout<<arr[8]<<endl; //Caused some problems for mixing up ll //and int } CASE(cas); loop(i,1,n-1) { pf("%d ",arr[i]); } pf("%d\n",arr[n]); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2011-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef __OP_RESOURCE_IMPL_H__ #define __OP_RESOURCE_IMPL_H__ #include "modules/network/op_resource.h" #include "modules/url/tools/url_util.h" #include "modules/cache/cache_exporter.h" #ifdef HAVE_DISK class OpResourceImpl; /** Convenience class to encapsulate SaveAsFile functionality */ class OpResourceSaveFileHandler : public OpRequestListener #ifdef PI_ASYNC_FILE_OP , public AsyncExporterListener #endif { private: OpResourceSaveFileHandler(OpResourceImpl *resource); ~OpResourceSaveFileHandler(); OP_STATUS SaveAsFile(const OpStringC &file_name, OpResourceSaveFileListener *listener, BOOL delete_if_error); #ifdef PI_ASYNC_FILE_OP // AsyncExporterListener implementation void NotifyStart(OpFileLength length, URL_Rep *rep, const OpStringC &name, UINT32 param) {} void NotifyProgress(OpFileLength bytes_saved, OpFileLength length, URL_Rep *rep, const OpStringC &name, UINT32 param); void NotifyEnd(OP_STATUS ops, OpFileLength bytes_saved, OpFileLength length, URL_Rep *rep, const OpStringC &name, UINT32 param); #endif // OpRequestListener implementation void OnResponseDataLoaded(OpRequest *req, OpResponse *res); void OnResponseFinished(OpRequest *req, OpResponse *res); void OnRequestFailed(OpRequest *req, OpResponse *res, Str::LocaleString error); OpResourceImpl *m_resource; OpResourceSaveFileListener *m_save_file_listener; friend class OpResourceImpl; friend class OpResourceSaveFileListener; }; #endif // HAVE_DISK class OpResourceImpl: public OpResource { public: OpResourceImpl(URL &url, OpRequest *request); virtual ~OpResourceImpl(); static BOOL QuickLoad(OpResource *&resource, OpURL url, BOOL guess_content_type); URLCacheType GetCacheType() const { return (URLCacheType) m_url.GetAttribute(URL::KCacheType); } virtual URL_Resumable_Status GetResumeSupported() const { return (URL_Resumable_Status) m_url.GetAttribute(URL::KResumeSupported); } OP_STATUS SetLocalTimeLoaded(const time_t &value) { return m_url.SetAttribute(URL::KVLocalTimeLoaded, (const void *)&value); } time_t GetLocalTimeLoaded() const { time_t local_time_loaded; m_url.GetAttribute(URL::KVLocalTimeLoaded, &local_time_loaded); return local_time_loaded; } UINT32 GetResourceId() const { return (UINT32) m_url.GetAttribute(URL::KStorageId); } URL_CONTEXT_ID GetContextId() const { return m_url.GetContextId(); } OP_STATUS SetHTTPPragma(const OpStringC8 &value) { return m_url.SetAttribute(URL::KHTTPPragma, value); } OP_STATUS SetHTTPCacheControl(const OpStringC8 &value) { return m_url.SetAttribute(URL::KHTTPCacheControl, value); } OP_STATUS SetHTTPExpires(const OpStringC8 &value) { return m_url.SetAttribute(URL::KHTTPExpires, value); } OP_STATUS SetHTTPEntityTag(const OpStringC8 &value) { return m_url.SetAttribute(URL::KHTTP_EntityTag, value); } void SetAccessed() { m_url.Access(FALSE); } OP_STATUS PrepareForViewing(RetrievalMode mode, BOOL force_to_file) { if (m_url.PrepareForViewing(FALSE, mode != DecompressAndCharsetConvert ? TRUE : FALSE, mode != Unprocessed? TRUE : FALSE, force_to_file) == 0) return OpStatus::OK; return OpStatus::ERR; } #if defined _LOCALHOST_SUPPORT_ || !defined RAMCACHE_ONLY OP_STATUS GetCacheFileFullName(OpString &value) const { OP_STATUS result=OpStatus::ERR; RETURN_IF_LEAVE(result = m_url.GetAttribute(URL::KFilePathName_L, value)); return result; } OP_STATUS GetCacheFileBaseName(OpString &value) const { return m_url.GetAttribute(URL::KFileName, value); } #endif OP_STATUS GetDataDescriptor(OpDataDescriptor *&dd, RetrievalMode mode, URLContentType override_content_type, unsigned short override_charset_id, BOOL get_original_content); void EvictFromCache() { m_url.SetAttribute(URL::KUnique, (UINT32) TRUE); } #ifdef TRUST_RATING OP_STATUS SetTrustRating(TrustRating value) { return m_url.SetAttribute(URL::KTrustRating, (UINT32) value);} TrustRating GetTrustRating() const { return (TrustRating) m_url.GetAttribute(URL::KTrustRating); } #endif #if defined HAVE_DISK && defined URL_ENABLE_ASSOCIATED_FILES OpFile *CreateAssociatedFile(OpResource::AssociatedFileType type) { return m_url.CreateAssociatedFile((URL::AssociatedFileType)type); } OpFile *OpenAssociatedFile(OpResource::AssociatedFileType type) { return m_url.OpenAssociatedFile((URL::AssociatedFileType)type); } #endif // HAVE_DISK && URL_ENABLE_ASSOCIATED_FILES #ifdef HAVE_DISK BOOL IsDownloadComplete() { return m_url.IsExportAllowed(); } OP_STATUS SaveAsFile(const OpStringC &file_name, OpResourceSaveFileListener *listener, BOOL delete_if_error) { return m_save_file_handler.SaveAsFile(file_name, listener, delete_if_error); } #endif // HAVE_DISK #ifdef _MIME_SUPPORT_ BOOL IsMHTML() const { return m_url.IsMHTML(); } OP_STATUS GetMHTMLRootPart(OpResponse *&root_part); #endif OP_STATUS GetBufferedRanges(OpAutoVector<StorageSegment> &segments) { return SquashStatus(m_url.GetSortedCoverage(segments), OpStatus::ERR_NO_MEMORY ); } private: URL m_url; OpRequest *m_request; class OpResponseImpl* m_multipart_related_root_part; #ifdef HAVE_DISK OpResourceSaveFileHandler m_save_file_handler; friend class OpResourceSaveFileListener; friend class OpResourceSaveFileHandler; #endif // HAVE_DISK }; #endif
#include "ManagerPull.h" #include "../classes/AppBill.h" ManagerPull::ManagerPull(string masterCS, string slaveCS) { part_size = 100; db_master.setCS(masterCS); db_slave.setCS(slaveCS); errors_count = 0; //bandwidth_limit_mbits = app().conf.db_bandwidth_limit_mbits; } void ManagerPull::add(BasePull * pull) { pull->setManager(this); pull->init(); pulls.insert(make_pair(pull->event, pull)); } bool ManagerPull::get_synclist() { string sql = "select name,key from event.syncparam where enabled"; BDbResult res = db_master.query(sql); if (res.size() == 0) return false; while (res.next()) { string name = res.get_s(0); string key = res.get_s(1); synclist.push_back(make_pair(name,key)); } return true; } //int ManagerPull::getInstanceId() { // // int instance_id=0; // string sql = "select value from vpbx.pg_server_settings where name='server_id'"; // BDbResult res = db_master.query(sql); // if (res.next()) { // // instance_id = res.get_i(0); // } // return instance_id; //} void ManagerPull::pull(int server_id) { string select_events_query = "select event, param, version from event.queue where server_id=" + to_string(server_id) + " order by version limit " + lexical_cast<string>(part_size); while (true) { BDbResult res = db_master.query(select_events_query); if (res.size() == 0) break; clearPulls(); while (res.next()) { string event = res.get_s(0); string id = res.get_s(1); map<string, BasePull *>::iterator it = pulls.find(event); if (it != pulls.end()) it->second->addId(id); else db_master.exec("delete from event.queue where server_id=" + to_string(server_id) + " and event = '" + event + "'"); } if (res.last()) { string version = res.get_s(2); for (auto it : pulls) { if (!it.second->need_pull) continue; try { db_master.exec("delete from event.queue where server_id=" + to_string(server_id) + " and event = '" + it.second->event + "' and version <= " + version); it.second->pull(); } catch (Exception &e) { e.addTrace("ManagerPull:pull"); Log::exception(e); errors_count += 1; } } } } } void ManagerPull::clearPulls() { for (auto it = pulls.cbegin(); it != pulls.cend(); ++it) { it->second->clear(); } } void ManagerPull::runPulls() { for (auto it = pulls.cbegin(); it != pulls.cend(); ++it) { it->second->pull(); } }
//给定一棵二叉搜索树,请找出其中的第k小的结点。 //例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 #include <iostream> #include <vector> #include "utils.h" using namespace std; class Solution { public: TreeNode* KthNode(TreeNode* pRoot, int k) { if (pRoot == nullptr) return nullptr; vector<int> res{}; __inOrder(pRoot, res); if ((int)res.size() < k || k < 1) return nullptr; return new TreeNode(res[k - 1]); } void __inOrder(TreeNode* pRoot, vector<int>& vec) { if (pRoot == nullptr) return; __inOrder(pRoot->left, vec); vec.emplace_back(pRoot->val); __inOrder(pRoot->right, vec); } }; class Solution2 { public: int cnt = 0; TreeNode* KthNode(TreeNode* pRoot, int k) { if (pRoot == nullptr) return nullptr; auto left = KthNode(pRoot->left, k); if (left != nullptr) return left; if (++cnt == k) return pRoot; auto right = KthNode(pRoot->right, k); if (right != nullptr) return right; } }; int main() { TreeNode* root = new TreeNode(5); root->left = new TreeNode(3); root->right = new TreeNode(7); root->left->left = new TreeNode(2); root->left->right = new TreeNode(4); root->right->left = new TreeNode(6); root->right->right = new TreeNode(8); cout << Solution().KthNode(root, 3)->val << endl; return 0; }
/* * This file contains all interrupt routines and their handling * * Creation date: 2019 06 16 * Author: Pascal Pfeiffer */ // includes #include "interruptRoutines.h" #include "PublicStructures.h" #include "protocol.h" #include "lidar.h" #include "lineTracking.h" #include "readSensors.h" #include <HCSR04P.h> #include <Arduino.h> #include "colorTracking.h" #include "location.h" // extern objects extern deviceConfig dC; extern lidar lidarSensors; extern lineTrackInterface lineSensorFrontLeft; extern lineTrackInterface lineSensorFrontRight; extern lineTrackInterface lineSensorBackLeft; extern lineTrackInterface lineSensorBackRight; extern HCSR04P ultraSonic; extern ColTrack colTrack; extern Location mylocation; // iterrupts markers volatile byte interruptCounterKey1 = 0; volatile byte interruptCounterKey2 = 0; volatile byte timer0State = 0; // create a hardware timer hw_timer_t * timer0 = NULL; // Critical section management portMUX_TYPE pinMux = portMUX_INITIALIZER_UNLOCKED; portMUX_TYPE timer0Mux = portMUX_INITIALIZER_UNLOCKED; // couter for 1 second byte secCounter = 0; /** * Interrupt Service Routine for Pin 19 */ void IRAM_ATTR handleInterruptP19() { portENTER_CRITICAL_ISR(&pinMux); interruptCounterKey1++; portEXIT_CRITICAL_ISR(&pinMux); } /** * Interrupt Service Routine for Pin 18 */ void IRAM_ATTR handleInterruptP18() { portENTER_CRITICAL_ISR(&pinMux); interruptCounterKey2++; portEXIT_CRITICAL_ISR(&pinMux); } /** * Timer0 ISR * ISR routine stored in IRAM */ void IRAM_ATTR onTimer0() { portENTER_CRITICAL(&timer0Mux); timer0State++; portEXIT_CRITICAL(&timer0Mux); } /** * Initialize Interrupts * Configure External Interrupt Pins and timer interrupts */ void interruptInitialization() { pinMode(KEY1, INPUT); pinMode(KEY2, INPUT); attachInterrupt(digitalPinToInterrupt(KEY1), handleInterruptP19, FALLING); attachInterrupt(digitalPinToInterrupt(KEY2), handleInterruptP18, FALLING); Serial.print("start timer0..."); // init timer0, prescaler = 80, countup = true timer0 = timerBegin(0, 80, true); // interrupt timer0, function = onTimer0, edge = true timerAttachInterrupt(timer0, &onTimer0, true); // counter timer0, value = 200000, relead after interrupt = true // timer interrupts programm every 200ms timerAlarmWrite(timer0, 200000, true); // enable the timer timerAlarmEnable(timer0); Serial.println("[OK]"); } /* void keyHandler() { if(interruptCounterKey1 > 0){ // disable interrupts on both CPU cores, and spinlock tasks on other CPU portENTER_CRITICAL(&pinMux); interruptCounterKey1 = 0; Serial.println("Key1 Pressed!"); // enable interrupts on both CPU cores, disable spinlock portEXIT_CRITICAL(&pinMux); } if(interruptCounterKey2 > 0){ // disable interrupts on both CPU cores, and spinlock tasks on other CPU portENTER_CRITICAL(&pinMux); Serial.println("Key2Pressed!"); interruptCounterKey2 = 0; // enable interrupts on both CPU cores, disable spinlock portEXIT_CRITICAL(&pinMux); } } */ /** * Do stuff that should be run if an Interrupt has occured * This function is OUTSIDE of the interrupt itself */ void interruptWorkers() { // keyHandler(); // this block is triggered every 200ms if(timer0State >= 1) { portENTER_CRITICAL(&timer0Mux); timer0State = 0; portEXIT_CRITICAL(&timer0Mux); portENTER_CRITICAL_ISR(&pinMux); // interruptCounterKey1 = Left speed sensor, interruptCounterKey2 = right speed sensor; mylocation.calculateSpeed(interruptCounterKey1, interruptCounterKey2); interruptCounterKey1 = 0; interruptCounterKey2 = 0; portEXIT_CRITICAL_ISR(&pinMux); // HIER SENSOR ZYKLISCH AUSLESEN UND GRAD BERECHNEN secCounter++; } // 1s intervall if(secCounter >= 5) { if(dC.wiFiNotificationSender == true) { wiFiNotificationSender(); } secCounter = 0; } yield(); } /** * This function is continuously called if the * dC.wiFiNotificationSender value is true * The function sends all recent sensor values * to the websocket client */ void wiFiNotificationSender() { // line tracking Sensors // 11 03 03 11 00 00 00 00 00 12 protocolSend(0x0, 0x11, 0x00, lineSensorFrontLeft.getColorCode()); protocolSend(0x0, 0x12, 0x00, lineSensorFrontRight.getColorCode()); protocolSend(0x0, 0x13, 0x00, lineSensorBackLeft.getColorCode()); protocolSend(0x0, 0x14, 0x00, lineSensorBackRight.getColorCode()); // lidar sensors protocolSend(0x0, 0x00, 0x00, lidarSensors.measureLidar[0].RangeMilliMeter); protocolSend(0x0, 0x01, 0x00, lidarSensors.measureLidar[1].RangeMilliMeter); protocolSend(0x0, 0x02, 0x00, lidarSensors.measureLidar[2].RangeMilliMeter); protocolSend(0x0, 0x03, 0x00, lidarSensors.measureLidar[3].RangeMilliMeter); protocolSend(0x0, 0x04, 0x00, lidarSensors.measureLidar[4].RangeMilliMeter); protocolSend(0x0, 0x05, 0x00, lidarSensors.measureLidar[5].RangeMilliMeter); protocolSend(0x0, 0x06, 0x00, lidarSensors.measureLidar[6].RangeMilliMeter); // ultrasonic protocolSend(0x0, 0x08, 0x00, ultraSonic.getDist()); // combined speed protocolSend(0x0, 0x19, 0x00, (float) mylocation.speedCombined2); }
//////////////////////////////////////////////////////////////////////////////// #include "Mesh3d.h" #include <cellogram/Mesh.h> #include <cellogram/State.h> #include <cellogram/remesh_adaptive.h> #include <polyfem/State.hpp> #include <polyfem/Mesh3D.hpp> #include <polyfem/MeshUtils.hpp> #include <igl/writeOBJ.h> #include <polyfem/PointBasedProblem.hpp> #include <igl/opengl/glfw/Viewer.h> #include <igl/copyleft/tetgen/tetrahedralize.h> #include <geogram/mesh/mesh_io.h> //////////////////////////////////////////////////////////////////////////////// namespace cellogram { namespace { nlohmann::json compute_analysis(const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &faces, const Eigen::MatrixXi &tets, const Mesh &mesh, float thickness, float E, float nu, const std::string &formulation, double scaling, Eigen::MatrixXd &vals, Eigen::MatrixXd &traction_forces) { //TODO //const std::string rbf_function = "gaussian"; const std::string rbf_function = "thin-plate"; // const std::string rbf_function = "cubic"; const double eps = 4; static const bool export_data = false; assert(tets.cols() == 4); assert(vertices.cols() == 3); GEO::Mesh M; M.vertices.create_vertices((int) vertices.rows()); for (int i = 0; i < (int) M.vertices.nb(); ++i) { GEO::vec3 &p = M.vertices.point(i); p[0] = vertices(i, 0); p[1] = vertices(i, 1); p[2] = vertices(i, 2); } M.cells.create_tets((int) tets.rows()); for (int c = 0; c < (int) M.cells.nb(); ++c) { for (int lv = 0; lv < tets.cols(); ++lv) { M.cells.set_vertex(c, lv, tets(c, lv)); } } M.cells.connect(); if(export_data){ GEO::mesh_save(M, "mesh.mesh"); GEO::mesh_load("mesh.mesh", M); } json j_args = { {"problem", "PointBasedTensor"}, {"normalize_mesh", false}, {"tensor_formulation", formulation}, {"discr_order", 1}, {"vismesh_rel_area", 1000}, {"solver_params", {"conv_tol", 1e-7, "max_iter", 2000}}, {"nl_solver_rhs_steps", 4}, {"n_boundary_samples", 3}, {"params", { {"E", E}, {"nu", nu}, }}, }; polyfem::State state; std::string log_file = ""; bool is_quiet = false; int log_level = 1; state.init_logger(log_file, log_level, is_quiet); state.init(j_args); state.load_mesh(M, [&](const polyfem::RowVectorNd &bary){ // top, Id = 1 if(std::abs(bary(2)) < 1e-6){ return 1; } //Bottom, Id = 3 if(std::abs(bary(2)- -thickness) < 1e-8){ return 3; } //any other return 2; }); // state.compute_mesh_stats(); polyfem::PointBasedTensorProblem &problem = *dynamic_cast<polyfem::PointBasedTensorProblem *>(state.problem.get()); Eigen::MatrixXd disp = (mesh.detected - mesh.points) * scaling; Eigen::MatrixXd pts = mesh.points * scaling; if(export_data){ GEO::mesh_save(M, "mesh.mesh"); { std::ofstream out("problem.json"); out.precision(100); out << j_args.dump(4) << std::endl; out.close(); } { std::ofstream out("fun.pts"); out.precision(100); out << pts << std::endl; out.close(); } { std::ofstream out("fun.tri"); out.precision(100); out << mesh.triangles << std::endl; out.close(); } { std::ofstream out("fun.txt"); out.precision(100); out << disp << std::endl; out.close(); } { std::ofstream out("tags.txt"); for(int i = 0; i < state.mesh->n_faces(); ++i) out << state.mesh->get_boundary_id(i) << std::endl; out.close(); } } //Id = 1, func, mesh, coord =2, means skip z for the interpolation Eigen::Matrix<bool, 3, 1> dirichet_dims; dirichet_dims(0) = dirichet_dims(1) = true; dirichet_dims(2) = false; // z is not dirichet problem.add_function(1, disp, pts, rbf_function, eps, 2, dirichet_dims); //Id = 3, zero Dirichelt problem.add_constant(3, Eigen::Vector3d(0,0,0)); // state.compute_mesh_stats(); state.build_basis(); // state.build_polygonal_basis(); state.assemble_rhs(); state.assemble_stiffness_mat(); state.solve_problem(); //true = compute average insteat of just integral // state.interpolate_boundary_function(vertices, faces, state.sol, true, vals); // state.interpolate_boundary_tensor_function(vertices, faces, state.sol, true, traction_forces); state.interpolate_boundary_function_at_vertices(vertices, faces, state.sol, vals); state.interpolate_boundary_tensor_function(vertices, faces, state.sol, vals, true, traction_forces); // vals = Eigen::Map<Eigen::MatrixXd>(state.sol.data(), 3, vertices.rows()); // vals = Eigen::Map<Eigen::MatrixXd>(state.rhs.data(), 3, vertices.rows()); // vals = vals.transpose().eval(); // std::cout<<vals<<std::endl; if(export_data) { std::ofstream out("sol.txt"); out.precision(100); out << state.sol << std::endl; out.close(); } if(export_data) { Eigen::MatrixXd nodes(state.n_bases, state.mesh->dimension()); for(const auto &eb : state.bases) { for(const auto &b : eb.bases) { for(const auto &lg : b.global()) { nodes.row(lg.index) = lg.node; } } } std::ofstream out("nodes.txt"); out.precision(100); out << nodes; out.close(); } nlohmann::json json; state.save_json(json); return json; // auto &tmp_mesh = *dynamic_cast<polyfem::Mesh3D *>(state.mesh.get()); // igl::opengl::glfw::Viewer viewer; // Eigen::MatrixXi asdT; // Eigen::MatrixXd asdP, asdC; // std::vector<int> asdR; // tmp_mesh.triangulate_faces(asdT,asdP,asdR); // asdC.resize(asdT.rows(), 3); // asdC.setZero(); // for(std::size_t i = 0; i < tmp_mesh.n_faces(); ++i) // { // const int a =tmp_mesh.get_boundary_id(i); // const auto bb = tmp_mesh.face_barycenter(i); // if(a == 1) // viewer.data().add_points(bb, Eigen::RowVector3d(1, 0, 0)); // else if(a == 3) // viewer.data().add_points(bb, Eigen::RowVector3d(0, 1, 0)); // else if(a == 2) // viewer.data().add_points(bb, Eigen::RowVector3d(0, 0, 1)); // } // viewer.data().set_mesh(asdP, asdT); // viewer.launch(); } } void Mesh3d::init_pillars(const Mesh &mesh, float eps, float I, float L, double scaling) { clear(); displacement = (mesh.detected - mesh.points) * scaling; V = mesh.points * scaling; const float bending_force = 3*eps * I /(L*L*L); traction_forces = bending_force * displacement; } bool Mesh3d::empty() { return V.size() == 0; } bool Mesh3d::analysed() { return traction_forces.size() > 0; } void Mesh3d::init_nano_dots(const Mesh &mesh, float padding_size, const float thickness, float E, float nu, double scaling, const std::string &formulation) { //Uncomment to used not adaptive tetgen mesher // clear(); // Eigen::Vector2d max_dim; // Eigen::Vector2d min_dim; // mesh.get_physical_bounding_box(min_dim, max_dim); // double xMin = min_dim(0) - padding_size; // double xMax = max_dim(0) + padding_size; // double yMin = min_dim(1) - padding_size; // double yMax = max_dim(1) + padding_size; // double zMin = -thickness; // double zMax = 0; // V.resize(8, 3); // V << xMin, yMin, zMin, // xMin, yMax, zMin, // xMax, yMax, zMin, // xMax, yMin, zMin, // //4 // xMin, yMin, zMax, // xMin, yMax, zMax, // xMax, yMax, zMax, // xMax, yMin, zMax; // F.resize(12, 3); // F << 1, 2, 0, // 0, 2, 3, // 5, 4, 6, // 4, 7, 6, // 1, 0, 4, // 1, 4, 5, // 2, 1, 5, // 2, 5, 6, // 3, 2, 6, // 3, 6, 7, // 0, 3, 7, // 0, 7, 4; // Eigen::MatrixXd TV; // Eigen::MatrixXi TT; // Eigen::MatrixXi TF; // #ifdef NDEBUG // igl::copyleft::tetgen::tetrahedralize(V, F, "Qpq1.414a100", TV, TT, TF); // #else // igl::copyleft::tetgen::tetrahedralize(V, F, "Qpq1.414a1000", TV, TT, TF); // #endif // V = TV; // F = TF; // T = TT; simulation_out = compute_analysis(V, F, T, mesh, thickness, E, nu, formulation, scaling, displacement, traction_forces); } void Mesh3d::clear() { F.resize(0, 0); V.resize(0, 0); T.resize(0, 0); displacement.resize(0, 0); traction_forces.resize(0, 0); simulation_out = nlohmann::json({}); } bool Mesh3d::load(const nlohmann::json & data) { read_json_mat(data["V"], V); read_json_mat(data["F"], F); //read_json_mat(data["T"], T); // maybe the Tets are unnecessary read_json_mat(data["displacement"], displacement); read_json_mat(data["traction_forces"], traction_forces); return true; } void Mesh3d::save_mesh(nlohmann::json & data) { data["V"] = json::object(); write_json_mat(V, data["V"]); data["F"] = json::object(); write_json_mat(F, data["F"]); //data["T"] = json::object(); //write_json_mat(T, data["T"]); data["displacement"] = json::object(); write_json_mat(displacement, data["displacement"]); } void Mesh3d::save_traction(nlohmann::json & data) { data["traction_forces"] = json::object(); write_json_mat(traction_forces, data["traction_forces"]); } }// namespace cellogram
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; int main(int argc, char const *argv[]) { Mat img = imread(argv[1], -1); if( img.empty() ) return -1; auto & data = img.data; for (uint i =0; i < img.cols * img.rows*3 ; i++) { std::cout << (int)(*(data + i)) << " "; } namedWindow("Example1", WINDOW_AUTOSIZE ); imshow("Example1", img); waitKey( 0 ); destroyWindow( "Example1" ); return 0; }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #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; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; LL solve(int* cnt, int m) { LL f[41][41]; memset(f, 0, sizeof(f)); f[0][0] = 1; for (int i = 0; i < 40; ++i) { for (int j = 0; j <= i; ++j) { f[i + 1][j] += f[i][j]; f[i + 1][j + 1] += f[i][j] * ((1ll << cnt[i + 1]) - 1); } } LL ans = 0; for (int j = m; j <= 40; ++j) ans += f[40][j]; return ans; } int main() { //freopen(".in", "r", stdin); //freopen(".out", "w", stdout); int T; scanf("%d", &T); while (T--) { int n, m, c[41], p[41], cnt[41] = {0}; scanf("%d%d", &n, &m); for (int i = 0; i < n; ++i) { scanf("%d%d", &c[i], &p[i]); ++cnt[c[i]]; } LL total = solve(cnt, m); LL ans = 0; for (int i = 0; i < n; ++i) { int t = cnt[c[i]]; cnt[c[i]] = 0; LL vars = solve(cnt, m - 1); cnt[c[i]] = t; vars *= (1ll << (cnt[c[i]] - 1)); ans += vars * p[i]; } printf("%.12lf\n", (double)ans / total); } return 0; }
#include "Bool.hpp" using namespace uipf; // returns the value of the boolean bool Bool::getContent() const { return b_; } // sets the value of the boolean /* b new boolean value */ void Bool::setContent(bool b) { b_ = b; } // returns the data type of this data object: in this case: BOOL Type Bool::getType() const { return BOOL; }
#include "Sphere.h" Sphere::Sphere() { radius = radius; xOrigin = 0; yOrigin = 0; zOrigin = 0; rgb.r = 0; rgb.g = 0; rgb.b = 0; tag = "none"; } Sphere::~Sphere() { delete material; } void Sphere::setMaterial(Material* mat) { material = mat; }; Material* Sphere::getMaterial() { return material; } void Sphere::setRadius(double r) { radius = r; } void Sphere::setOrigin(double x, double y, double z) { xOrigin = x; yOrigin = y; zOrigin = z; } void Sphere::setColor(double r, double g, double b) { rgb.r = r; rgb.g = g; rgb.b = b; }
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // Проверка корректности ввода логина и пароля // V 1.0 // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// #include <iostream> using namespace std; int main() { bool flag; cout << "Придумайте логин" << endl; string login = "user"; string username; cin >> username; cout << "Придумайте пароль: "; int password; cin >> password; while (flag != true) { cout << "Повторите логин" << endl; string repeatUserName; cin >> repeatUserName; cout << "Повторите пароль: "; int repeatPassword; cin >> repeatPassword; if (username == repeatUserName && password == repeatPassword) { cout << "Вам разрешен доступ" << "\n"; flag = true; } else { cout << "Доступ запрещён!" << "\n"; flag = false; } } return 0; } // Output: /* Придумайте пароль: 123 Повторите логин alex Повторите пароль: 321 Доступ запрещён! Повторите логин alex Повторите пароль: 123 Вам разрешен доступ */ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=// // END FILE // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// KC Text Adventure Framework - (c) Rachel J. Morris, 2012 - 2013. zlib license. Moosader.com #include "StateManager.h" StateManager::StateManager() { m_state = luaL_newstate(); luaL_openlibs( m_state ); // luabind::open( m_state ); Init(); } StateManager::~StateManager() { lua_close( m_state ); } void StateManager::Init() { m_menuState.Init( m_state ); m_gameState.Init( m_state ); m_currentState = &m_menuState; m_mission.Init( m_state ); m_menuState.SetMissionPtr( m_mission ); m_gameState.SetMissionPtr( m_mission ); } void StateManager::MainLoop() { bool playing = true; while ( playing ) { playing = m_currentState->MainLoop(); if ( playing && m_currentState->Name() == "Menu" ) { // Menu state has returned, go to game state now. // This could be handled better, but right now it's fine. m_currentState = &m_gameState; } } }
#ifndef _GAME_STATE_H_ #define _GAME_STATE_H_ #include <SFML\System\Export.hpp> #include <memory> #include <RenderAttributes.h> #include "Enums.h" class TestApp; class CAssetsDatabase; struct SRenderAttributes; class CTransition; struct InputsInfo; class CGameState { public: CGameState( TestApp* pApp, CAssetsDatabase* pDatabase, Transition::E init, Transition::E end ); virtual ~CGameState(); void OnInit( float fTransitionIn, float fTransitionOut ); void OnInputs( sf::Uint32& inputs, const InputsInfo& inputsInfo ); void OnUpdate(); void OnDraw(); void OnDestroy(); protected: void SetNextGameState( GameStates::E nextState ); void ChangeState( float fTransitionIn, float fTransitionOut ); virtual void Initialize() = 0; virtual void Inputs( sf::Uint32& inputs, const InputsInfo& inputsInfo ) = 0; virtual void Update() = 0; virtual void Draw( SRenderAttributes& renderAttribs ) = 0; virtual void RenderTargetDraw( SRenderAttributes& renderAttribs ); virtual void Destroy() = 0; protected: CAssetsDatabase* m_pDatabase; TestApp* m_pApp; SRenderAttributes m_renderAttribs; Camera m_camera; Light* m_lights; int m_nLights; DrawMode::E m_drawMode; private: void CreateTransition( std::unique_ptr<CTransition>& pTransition, Transition::E transitionType ); private: std::unique_ptr<CTransition> m_pStartTransition; std::unique_ptr<CTransition> m_pEndTransition; GameStates::E m_nextGameState; TransitionState::E m_transitionState; float m_fNextStateTransitionBeg; float m_fNextStateTransitionEnd; }; #endif //_GAME_STATE_H_
#pragma once #include "Engine/graphics/SpringCamera.h" class SpringCamera; class GameCamera :public GameObject { public: GameCamera(); ~GameCamera(); void Update(); void normal(); void focus(); void SetTarget(CVector3 tar) { m_target = tar; } void SetPosition(CVector3 pos) { m_pos = pos; } private: bool neko = false; CVector3 m_target = { 0.0f, 20.0f, 0.0f }; CVector3 m_pos = { 0.0f, 350.0f, 10000.0f }; //CVector3 m_toCameraPos = { 0.0f, 50.0f, 300.0f }; CVector3 m_toCameraPos = { 0.0f, 50.0f, 1000.0f }; SpringCamera m_Scamera; int m_inm = -1; bool m_first = true; float m_base = 0.f; };
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include "Buffer.h" #include "SoundContext.h" #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include <sound/SoundException.h> #include <sound/pcm/Pcm.h> #include <util/Exceptions.h> #include <android/asset_manager.h> #include <android_native_app_glue.h> #include <stdint.h> /****************************************************************************/ struct Buffer::Impl { Impl () : data (NULL), size (0) {}; std::string name; void *data; size_t size; }; /****************************************************************************/ Buffer::Buffer () { impl = new Impl; } /****************************************************************************/ Buffer::~Buffer () { free (impl->data); delete impl; } /****************************************************************************/ void Buffer::setLoad (std::string const &filename) { assert (device); Sound::load (filename.c_str (), &impl->data, &impl->size); } /****************************************************************************/ void Buffer::setName (std::string const &name) { impl->name = name; // assertThrow (device, "Buffer::setName : device must be set prior to calling this method."); // device->unregisterBuffer (name); // device->registerBuffer (name, this); } /****************************************************************************/ std::string const &Buffer::getName () const { return impl->name; } /****************************************************************************/ void const *Buffer::getData () const { return impl->data; } /****************************************************************************/ size_t Buffer::getSize () const { return impl->size; }
/* 2. Add Two Numbers Medium 7742 1986 Add to List Share You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. Accepted 1,331,488 Submissions 4,005,817 */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { int forward = 0; ListNode* pre_node = NULL; ListNode* head = NULL; while (l1 != NULL || l2 != NULL || forward != 0){ int val = 0; if (l1 != NULL) val += l1->val; if (l2 != NULL) val += l2->val; if (forward != 0) val += forward; forward = val/10; val = val%10; ListNode* cur = new ListNode(val); if (head == NULL){ head = cur; } if (pre_node == NULL){ pre_node = cur; } else{ pre_node->next = cur; } if (l1!= NULL) l1 = l1->next; if(l2 != NULL) l2 = l2->next; pre_node = cur; } return head; } };
#include "threadmanager.h" #include "ithread.h" #include "receiver/receiver.h" #include "port/serial.h" #include <unistd.h> #include <QThread> #include <QMap> #include <stdio.h> ThreadManager::ThreadManager() { // usart2 = USART2::getInstance(); // usart2->initSerialPort(Serial::DATABITS_EIGHT, Serial::PARITY_NO, Serial::STOPBITS_ONE, Serial::BAUD_115200); receiver = new Receiver; //receiver->init(Serial::DATABITS_EIGHT, Serial::PARITY_NO, Serial::STOPBITS_ONE, Serial::BAUD_115200); receiver->init(Serial::DATABITS_EIGHT, Serial::PARITY_EVENT, Serial::STOPBITS_TWO, Serial::BAUD_115200); startThreads(); } ThreadManager::~ThreadManager() { } void ThreadManager::startThreads(void) { QMap<QObject*, QThread*> *map = IThread::getMap(); for(QMap<QObject*, QThread*>::ConstIterator iter=map->constBegin(); iter!=map->constEnd(); ++iter){ QObject* obj = iter.key(); QThread* thread = iter.value(); obj->moveToThread(thread); thread->start(); } } void ThreadManager::stopAndDestroyThreads(void) { QMap<QObject*, QThread*> *map = IThread::getMap(); for(QMap<QObject*, QThread*>::ConstIterator iter=map->constBegin(); iter!=map->constEnd(); ++iter){ QObject* obj = iter.key(); QThread* thread = iter.value(); // obj->exit_enable(); usleep(1000*10); if (thread) { if (thread->isRunning()) { thread->quit(); thread->wait(); } // if (gpio) // { // disconnect(gpio_thread, SIGNAL(started()), gpio, SLOT(gpio_doOperation())); // disconnect(gpio_thread, SIGNAL(finished()), gpio, SLOT(gpio_postHandle())); // } delete thread; thread = NULL; } if (obj) { delete obj; obj = NULL; } } } void ThreadManager::parse(char*buf, int *result) { result[ 0] = (buf[ 1] | (buf[2] << 8)) &0x07ff; //!< Channel 0 result[ 1] = ((buf[ 2] >> 3) | (buf[3] << 5)) &0x07ff; //!< Channel 1 result[ 2] = ((buf[ 3] >> 6) | (buf[4] << 2) | (buf[5] << 10)) &0x07ff; //!< Channel 2 油门通道 result[ 3] = ((buf[ 5] >> 1) | (buf[6] << 7)) &0x07ff; //!< Channel 3 result[ 4] = ((buf[ 6] >> 4) | (buf[7] << 4)) &0x07ff; //!< Channel 4 result[ 5] = ((buf[ 7] >> 7) | (buf[8] << 1) | (buf[9] << 9)) &0x07ff; //!< Channel 5 result[ 6] = ((buf[ 9] >> 2) | (buf[10] << 6)) &0x07ff; //!< Channel 6 result[ 7] = ((buf[10] >> 5) | (buf[11] << 3)) &0x07ff; //!< Channel 7 result[ 8] = (buf[12] | (buf[13] << 8)) &0x07ff; //!< Channel 8 result[ 9] = ((buf[13] >> 3) | (buf[14] << 5)) &0x07ff; //!< Channel 9 result[10] = ((buf[14] >> 6) | (buf[15] << 2) | (buf[16] << 10)) &0x07ff;//!< Channel 10 result[11] = ((buf[16] >> 1) | (buf[17] << 7)) &0x07ff; //!< Channel 11 result[12] = ((buf[17] >> 4) | (buf[18] << 4)) &0x07ff; //!< Channel 12 result[13] = ((buf[18] >> 7) | (buf[19] << 1) | (buf[20] << 9)) &0x07ff; //!< Channel 13 result[14] = ((buf[20] >> 2) | (buf[21] << 6)) &0x07ff; //!< Channel 14 result[15] = ((buf[21] >> 5) | (buf[22] << 3)) &0x07ff; //!< Channel 15 for (int i = 0; i < 16; i++){ printf("%d ", result[i]); if (i == 7) printf("\n"); } printf("\n"); } void ThreadManager::doOperation(signal_data_t *sd) { Q_UNUSED(sd); qDebug("ThreadManager::doOperation"); // RX:0F E0 03 1F 58 C0 07 16 B0 80 05 2C 60 01 0B F8 C0 07 00 00 00 00 00 03 00 // CH: 992 992 352 992 352 352 352 352 352 352 992 992 000 000 000 000 // RX:0F 60 01 0B 58 C0 07 66 30 83 19 7C 60 06 1F F8 C0 07 00 00 00 00 00 03 00 // CH: 352 352 352 992 1632 1632 1632 992 1632 992 992 992 000 000 000 000 char buf[25] = {0x0F, 0xE0, 0x03, 0x1F, 0x58, 0xC0, 0x07, 0x16, 0xB0, 0x80, 0x05, 0x2C, 0x60, 0x01, 0x0B, 0xF8, 0xC0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00}; char buf1[25] = {0x0F, 0x60, 0x01, 0x0B, 0x58, 0xC0, 0x07, 0x66, 0x30, 0x83, 0x19, 0x7C, 0x60, 0x06, 0x1F, 0xF8, 0xC0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00}; int result[16]; parse(buf, result); parse(buf1, result); // int index = 0; // if (sd) // { // index = sd->index; //TABLEBAR_SELECT // //qDebug("Thread_Manager::doOperation, command:%d", index); // } // else // { // qDebug("sd is NULL."); // return; // } // switch (index) // { // case 0: // {} // break; // } }
#include "LogComingProc.h" #include "Logger.h" #include "HallManager.h" #include "Room.h" #include "ErrorMsg.h" #include "GameApp.h" #include "MoneyAgent.h" #include "RoundAgent.h" #include "GameCmd.h" #include "Protocol.h" #include "ProcessManager.h" #include "BaseClientHandler.h" #include "ProtocolServerId.h" #include "IProcess.h" struct Param { int uid; int tid; short source; char name[64]; char json[1024]; }; LogComingProc::LogComingProc() { this->name = "LogComingProc"; } LogComingProc::~LogComingProc() { } int LogComingProc::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket, Context* pt ) { //_NOTUSED(pt); int cmd = pPacket->GetCmdType(); short seq = pPacket->GetSeqNum(); short source = pPacket->GetSource(); int uid = pPacket->ReadInt(); string name = pPacket->ReadString(); int tid = pPacket->ReadInt(); short realTid = tid & 0x0000FFFF; int64_t m_lMoney = pPacket->ReadInt64(); short level = pPacket->ReadShort(); string json = pPacket->ReadString(); LOGGER(E_LOG_INFO) << "client params, cmd = " << TOHEX(cmd) << " seq = " << seq << " source = " << source << " uid = " << uid << " name = " << name << " tid = " << tid << " realTid = " << realTid << " m_lMoney = " << m_lMoney << " level = " << level << " json = " << json; BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (clientHandler); if(level != Configure::getInstance()->m_nLevel) { LOGGER(E_LOG_ERROR) << "Level is not match!"; return sendErrorMsg(clientHandler, cmd, uid, -3, ERRMSG(-3), seq); } MoneyAgent* connect = MoneyServer(); OutputPacket response; response.Begin(cmd, uid); response.SetSeqNum(pt->seq); response.WriteInt(uid); response.WriteShort(Configure::getInstance()->m_nServerId); response.End(); pt->seq = seq; if (source == E_MSG_SOURCE_ROBOT) goto __ROBOT_LOGIN__; if (connect->Send(&response) >= 0) { LOGGER(E_LOG_INFO) << "Transfer request to Back_MYSQLServer OK!"; struct Param* param = (struct Param *) malloc(sizeof(struct Param)); param->uid = uid; param->tid = tid; param->source = source; strncpy(param->name, name.c_str(), 63); param->name[63] = '\0'; //strncpy(param->password, password.c_str(), 31); //param->password[31] = '\0'; strncpy(param->json, json.c_str(), 1023); param->json[1023] = '\0'; pt->data = param; return 1; } else { LOGGER(E_LOG_ERROR) << "Send request to BackServer Error"; return -1; } __ROBOT_LOGIN__: Room* room = Room::getInstance(); Table *table = room->getTable(realTid); if(table == NULL) { LOGGER(E_LOG_ERROR) << "This Table is NULL"; return sendErrorMsg(clientHandler, cmd, uid, -2, ERRMSG(-2), pt->seq); } Player* player = table->isUserInTab(uid); if(player==NULL) { player = room->getAvailablePlayer(); if(player == NULL) { LOGGER(E_LOG_ERROR) << "Room is full, no seat for player"; return sendErrorMsg(clientHandler, cmd, uid, -33, ERRMSG(-33), pt->seq); } player->id = uid; player->m_lMoney = m_lMoney; player->m_nHallid = hallhandler->hallid; strncpy(player->name, name.c_str(), sizeof(player->name) - 1); player->name[sizeof(player->name) - 1] = '\0'; strcpy(player->json, json.c_str()); player->source = source; player->login(); if(table->playerComming(player) != 0) { LOGGER(E_LOG_ERROR) << "Comming into this table failed!"; return sendErrorMsg(clientHandler, cmd, uid, -32, ERRMSG(-32), pt->seq); } } player->setActiveTime(time(NULL)); for (int idx = 0; idx < GAME_PLAYER; ++idx) { Player *current = table->player_array[idx]; if (current == NULL) { continue; } IProcess::sendTabePlayersInfo(table, current, uid, seq); } return 0; } int LogComingProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { _NOTUSED(clientHandler); if(pt==NULL) { LOGGER(E_LOG_INFO) << "Context is NULL"; return -1; } if(pt->client == NULL) { LOGGER(E_LOG_INFO) << "Context client is NULL"; return -1; } BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (pt->client); struct Param* param = (struct Param*)pt->data; int uid = param->uid; int tid = param->tid; short source = param->source; short svid = tid >> 16; short realTid = tid & 0x0000FFFF; string name = string(param->name); string json = string(param->json); LOGGER(E_LOG_INFO) << "context params, uid = " << uid << " tid = " << tid << " source = " << source << " svid = " << svid << " realTid = " << realTid << " name = " << name << " json = " << json; short cmd = inputPacket->GetCmdType(); short retno = inputPacket->ReadShort(); string retmsg = inputPacket->ReadString(); uid = inputPacket->ReadInt(); int64_t money = inputPacket->ReadInt64(); int64_t safemoney = inputPacket->ReadInt64(); int roll = inputPacket->ReadInt(); int roll1 = inputPacket->ReadInt(); int coin = inputPacket->ReadInt(); int exp = inputPacket->ReadInt(); LOGGER(E_LOG_INFO) << "packet params, cmd = " << TOHEX(cmd) << " retno = " << retno << " retmsg = " << retmsg << " money = " << money << " safemoney = " << safemoney << " roll = " << roll << " roll1 = " << roll1 << " coin = " << coin << " exp = " << exp; if (retno != 0) { return sendErrorMsg(pt->client, cmd, uid, -1, retmsg.c_str(), pt->seq); } Table *table = Room::getInstance()->getTable(realTid); if(table == NULL) { LOGGER(E_LOG_ERROR) << "This Table is NULL"; return sendErrorMsg(pt->client, cmd, uid, -2, ERRMSG(-2), pt->seq); } Player* player = table->isUserInTab(uid); if(player==NULL) { player = Room::getInstance()->getAvailablePlayer(); if(player == NULL) { LOGGER(E_LOG_ERROR) << "Room is full, no seat for player"; return sendErrorMsg(pt->client, cmd, uid, -33, ERRMSG(-33), pt->seq); } player->id = uid; player->m_lMoney = money; player->m_nHallid = hallhandler->hallid; strncpy(player->name, name.c_str(), sizeof(player->name) - 1); player->name[sizeof(player->name) - 1] = '\0'; strcpy(player->json, json.c_str()); player->source = source; player->m_nRoll = roll + roll1; player->m_nExp = exp; player->login(); if(table->playerComming(player) != 0) { LOGGER(E_LOG_ERROR) << "Comming into this table failed!"; return sendErrorMsg(pt->client, cmd, uid, -32,ErrorMsg::getInstance()->getErrMsg(-32),pt->seq); } } player->setActiveTime(time(NULL)); for (int idx = 0; idx < GAME_PLAYER; ++idx) { Player *current = table->player_array[idx]; if (current == NULL) { continue; } IProcess::sendTabePlayersInfo(table, current, uid, pt->seq); } return 0; } REGISTER_PROCESS(CLIENT_MSG_LOGINCOMING, LogComingProc);
//知识点: 简单数学推导, 暴力, 枚举 /* 分析题意: - 通过 简单分析 和 观察样例 , 可以发现 : 相等的数列元素 作为 x_a,x_b,x_c,x_d 出现的次数相同 而n<=15000 , 所以 可以用桶直接 记录 每一种数 值出现的次数 输出时 直接输出 某数列元素对应数值 作为 x_a,x_b,x_c,x_d 出现的次数即可 - 对 题目给出 限制条件 进行转化: - x_a<x_b<x_c<x_d ① x_b-x_a=2(x_d-x_c) ② x_b-x_a<(x_c-x_b)/3 ③ - 设 t = x_d-x_c 将其 代入 ②中 , 则有: x_b-x_a = 2* t ④ 将 ④ 代入 ③中 , 则有: 2* t < (x_c-x_b)/3 将其 转化后: 6* t<x_c - x_b - 再设 6* t+k =x_c - x_b ⑤ 则可以得到一个数轴上的关系 - 通过观察分析 , 可以得到 各个数值的 取值范围 1<t , 且9* t<n 1<= x_a<n-9* t 9* t+1<x_d <= n - 可以发现 , 假设 已知 t 和 x_a , 则可得 x_b = x_a+2t 同时还可发现 , 对于 已知的 t 和 x_a, 所有 x >x_a+2t+6t 的位置都可以作为 合法的 x_c 已知 x_c 的位置后 可以 求得 x_d = x_c+t - 同理 , 若 t 和 x_d 已知 , 也可以 由上述过程 更新答案 - 通过上述 结论 , 发现可以通过 枚举 t,x_a和 x_d 解决问题: - 枚举 t 的值 , 1<t , 且9* t<n - 枚举x_a 的值 ,并求得 x_b 的值 1<= x_a<n-9* t - 枚举合法的 x_c ,并求得 x_d - 现在就获得了 一组 合法的 序列元素的值 - 若 x_a,x_b,x_c,x_d 的数量分别为 num[x_a],...,num[x_d] 根据乘法原理 , 将 它们组合后 产生合法序列 的数量为 num[x_a]* num[x_b]* num[x_c]* num[x_d] - 则: 对于 x_a , 其作为 A 元素出现的个数 +=num[x_b]* num[x_c]* num[x_d] 对于 x_b , 其作为 B 元素出现的个数 +=num[x_a]* num[x_c]* num[x_d] 其他同理 - 则可 使用乘法原理 , 计算 贡献 - 枚举x_d 的值,并求得 x_c 的值 9* t+1<x_d <= n - 过程同上 --- - 对上式 进行观察: 发现 x_d 递增时 , x_a 的合法范围 左边界不变 , 只有右边界 向右递增 有许多 x_a 被重复枚举 , 导致 时间复杂度 上升 对答案 有贡献的 只有 x_a的数量 * x_b的数量 所以 可以对 (x_a的数量 * x_b的数量) 取一前缀和 每次 只需要 枚举 新增的 右边界 上的 x_a的数量 * x_b的数量 用 新情况 更新前缀和 , 再用前缀和 更新 答案 - 对于 x_a: 同上 */ #include<cstdio> #include<ctype.h> const int MARX = 1e4+5e4+10; //============================================================= int n,m , x[MARX<<2],num[MARX];; int ansa[MARX],ansb[MARX],ansc[MARX],ansd[MARX]; //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } //============================================================= signed main() { n=read(),m=read(); for(int i=1; i<=m; i++) //计算数量 { x[i] = read(); num[x[i]] ++; } for(int t=1,sum=0; 9*t<n; t++,sum=0)//枚举t { for(int A = n-9*t-1; A; A--)//枚举A { int B = A+2*t , C = B+6*t+1 , D = C+t;//获得其他值 sum += num[C]*num[D]; ansa[A] += num[B]*sum;//更新答案 ansb[B] += num[A]*sum; } sum = 0; for(int D=9*t+2; D<=n; D++)//枚举D { int A = D-9*t-1 , B = A+2*t , C = D-t;//获得其他值 sum += num[A]*num[B]; ansc[C] += sum*num[D];//更新答案 ansd[D] += sum*num[C]; } } for(int i=1; i<=m; putchar('\n'),i++) printf("%d %d %d %d",ansa[x[i]],ansb[x[i]],ansc[x[i]],ansd[x[i]]); } //O(n^3) 85分 /* #include<cstdio> int n,m , x[40010]; int ansa[15010],ansb[15010],ansc[15010],ansd[15010]; int num[15010]; signed main() { scanf("%d%d",&n,&m); for(int i=1; i<=m; i++) { scanf("%d",&x[i]); num[x[i]] ++; } for(int t=1; 9*t<n; t++) { for(int A = 1; A<=n-9*t-1; A++) for(int D = A+9*t+1; D<=n; D++) { int B = A+2*t; int C = D-t; ansa[A] += num[B]*num[C]*num[D]; ansb[B] += num[A]*num[C]*num[D]; } for(int D=9*t+2; D<=n; D++) for(int A = 1; A<= D-9*t-1; A++) { int B = A+2*t; int C = D-t; ansc[C] += num[A]*num[B]*num[D]; ansd[D] += num[A]*num[B]*num[C]; } } for(int i=1; i<=m; putchar('\n'),i++) printf("%d %d %d %d",ansa[x[i]],ansb[x[i]],ansc[x[i]],ansd[x[i]]); } */ //O(n^4) 40分 /* #include<cstdio> int n,m , x[40010],ans[40010][5]; signed main() { scanf("%d%d",&n,&m); for(int i=1; i<=m; i++) scanf("%d",&x[i]); for(int a=1; a<=m; a++) //暴力枚举 for(int b=1; b<=m; b++) for(int c=1; c<=m; c++) for(int d=1; d<=m; d++) if(x[a] < x[b] && x[b] < x[c] && x[c] < x[d]) if(x[b] - x[a] == 2*x[d] - 2*x[c]) if(3*x[b] - 3*x[a] < x[c]-x[b])//暴力判断, 更新答案 ans[a][1]++, ans[b][2]++, ans[c][3]++, ans[d][4]++; for(int i=1; i<=m; putchar('\n'),i++)//输出 for(int j=1; j<=4; j++) printf("%d ",ans[i][j]); } */
#include "stdafx.h" #include <stdio.h> #include "QuoteAPI.h" QuoteAPI::QuoteAPI(void) { } QuoteAPI::~QuoteAPI(void) { } void QuoteAPI::OnFrontConnected() { if(_fnOnFrontConnected) { _fnOnFrontConnected(); } } void QuoteAPI::OnFrontDisconnected(int nReason) { if(_fnOnFrontDisconnected) { _fnOnFrontDisconnected(nReason); } } void QuoteAPI::OnHeartBeatWarning(int nTimeLapse) { if(_fnOnHeartBeatWarning) { _fnOnHeartBeatWarning(nTimeLapse); } } void QuoteAPI::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { int eId = -1; if(pRspInfo) { eId = pRspInfo->ErrorID; } if(0 == eId) { //TODO: get the tradingday } if(_fnOnRspUserLogin) { _fnOnRspUserLogin(eId); } } void QuoteAPI::OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if(_fnOnRspUserLogout) { //_fnOnRspUserLogout(nRequestID); } } void QuoteAPI::OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if(_fnOnRspError && pRspInfo) { _fnOnRspError(pRspInfo->ErrorID, pRspInfo->ErrorMsg); } } void QuoteAPI::OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if(_fnOnRspSubMarketData) { //TODO: } } void QuoteAPI::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if(_fnOnRspUnSubMarketData) { //TODO: } } void QuoteAPI::OnRspSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if(_fnOnRspSubForQuoteRsp) { } } void QuoteAPI::OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) { if(_fnOnRspUnSubForQuoteRsp) { } } void QuoteAPI::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) { if(_fnOnRtnDepthMarketData) { if(NULL == pDepthMarketData) { return; } //栈上的对象不能跨出其作用域 //MarketData *d = new MarketData(); MarketData d; memset(&d, 0, sizeof(MarketData)); strcpy_s(d.InstrumentID, sizeof(d.InstrumentID), pDepthMarketData->InstrumentID); d.LastPrice = pDepthMarketData->LastPrice; d.PreClosePrice = pDepthMarketData->PreClosePrice; d.OpenPrice = pDepthMarketData->OpenPrice; d.HighestPrice = pDepthMarketData->HighestPrice; d.LowestPrice = pDepthMarketData->LowestPrice; d.UpperLimitPrice = pDepthMarketData->UpperLimitPrice; d.LowerLimitPrice = pDepthMarketData->LowerLimitPrice; d.UpdateMillisec = pDepthMarketData->UpdateMillisec; sprintf_s(d.UpdateTime, "%s", pDepthMarketData->UpdateTime); d.AskPrice1 = pDepthMarketData->AskPrice1; d.AskVolume1 = pDepthMarketData->AskVolume1; d.AskPrice2 = pDepthMarketData->AskPrice2; d.AskVolume2 = pDepthMarketData->AskVolume2; d.AskPrice3 = pDepthMarketData->AskPrice3; d.AskVolume3 = pDepthMarketData->AskVolume3; d.AskPrice4 = pDepthMarketData->AskPrice4; d.AskVolume4 = pDepthMarketData->AskVolume4; d.AskPrice5 = pDepthMarketData->AskPrice5; d.AskVolume5 = pDepthMarketData->AskVolume5; d.BidPrice1 = pDepthMarketData->BidPrice1; d.BidVolume1 = pDepthMarketData->BidVolume1; d.BidPrice2 = pDepthMarketData->BidPrice2; d.BidVolume2 = pDepthMarketData->BidVolume2; d.BidPrice3 = pDepthMarketData->BidPrice3; d.BidVolume3 = pDepthMarketData->BidVolume3; d.BidPrice4 = pDepthMarketData->BidPrice4; d.BidVolume4 = pDepthMarketData->BidVolume4; d.BidPrice5 = pDepthMarketData->BidPrice5; d.BidVolume5 = pDepthMarketData->BidVolume5; //此处如何处理内存分配问题,在栈中传递地址??? _fnOnRtnDepthMarketData(&d); //delete d; } } void QuoteAPI::OnRtnForQuoteRsp(CThostFtdcForQuoteRspField *pForQuoteRsp) { } void QuoteAPI::RegOnFrontConnected(PFnOnFrontConnected onFrontConnected) { _fnOnFrontConnected = onFrontConnected; } void QuoteAPI::RegOnFrontDisconnected(PFnOnFrontDisconnected onFrontDisconnected) { _fnOnFrontDisconnected = onFrontDisconnected; } void QuoteAPI::RegOnHeartBeatWarning(PFnOnHeartBeatWarning onHeartBeatWarning) { _fnOnHeartBeatWarning = onHeartBeatWarning; } void QuoteAPI::RegOnRspUserLogin(PFnOnRspUserLogin onRspUserLogin) { _fnOnRspUserLogin = onRspUserLogin; } void QuoteAPI::RegOnRspUserLogout(PFnOnRspUserLogout onRspUserLogout) { _fnOnRspUserLogout = onRspUserLogout; } void QuoteAPI::RegOnRspError(PFnOnRspError onRspError) { _fnOnRspError = onRspError; } void QuoteAPI::RegOnRspSubMarketData(PFnOnRspSubMarketData onRspSubMarketData) { _fnOnRspSubMarketData = onRspSubMarketData; } void QuoteAPI::RegOnRspUnSubMarketData(PFnOnRspUnSubMarketData onRspUnSubMarketData) { _fnOnRspUnSubMarketData = onRspUnSubMarketData; } void QuoteAPI::RegOnRspSubForQuoteRsp(PFnOnRspSubForQuoteRsp onRspSubForQuoteRsp) { _fnOnRspSubForQuoteRsp = onRspSubForQuoteRsp; } void QuoteAPI::RegOnRspUnSubForQuoteRsp(PFnOnRspUnSubForQuoteRsp onRspUnSubForQuoteRsp) { _fnOnRspUnSubForQuoteRsp = onRspUnSubForQuoteRsp; } void QuoteAPI::RegOnRtnDepthMarketData(PFnOnRtnDepthMarketData onRtnDepthMarketData) { _fnOnRtnDepthMarketData = onRtnDepthMarketData; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SBCS_DECODER_H #define SBCS_DECODER_H #ifdef ENCODINGS_HAVE_TABLE_DRIVEN #include "modules/encodings/decoders/inputconverter.h" #include "modules/encodings/decoders/iso-8859-1-decoder.h" // ==== Single-byte -> UTF-16 =========================================== class SingleBytetoUTF16Converter : public ISOLatin1toUTF16Converter { public: SingleBytetoUTF16Converter(const char *tablename); SingleBytetoUTF16Converter(const char *charset, const char *tablename); virtual OP_STATUS Construct(); virtual ~SingleBytetoUTF16Converter(); virtual int Convert(const void *src, int len, void *dest, int maxlen, int *read); virtual const char *GetCharacterSet() { return m_charset; }; #ifdef ENCODINGS_HAVE_CHECK_ENDSTATE virtual BOOL IsValidEndState() { return TRUE; } #endif private: long m_table_size; ///< number of map entries const UINT16 *m_codepoints; ///< map entries for the 128 upper chars (or all 256) char m_charset[128]; ///< name of character set /* ARRAY OK 2009-03-02 johanh */ char m_tablename[128]; ///< name of charset table /* ARRAY OK 2009-03-02 johanh */ SingleBytetoUTF16Converter(const SingleBytetoUTF16Converter&); SingleBytetoUTF16Converter& operator =(const SingleBytetoUTF16Converter&); virtual void Init(const char *charset, const char *tablename); }; #endif // ENCODINGS_HAVE_TABLE_DRIVEN #endif // SBCS_DECODER_H
#pragma once #ifndef CAMERA_H #define CAMERA_H #include "math\Mat4.h" namespace NoHope { class Camera { public: Camera(); ~Camera(); /*void draw();*/ /*void update(float dt);*/ void setCameraPosition(float x,float y); Mat4 cameraViewMatrix(); Mat4 view; private: /*float x,y;*/ Camera(Camera&); }; } #endif
#include "Player.h" #include "Game.h" #include <QGraphicsItem> extern Game * game; Player::Player(QGraphicsItem *parent): QObject(), QGraphicsPixmapItem(parent) { QPixmap image(":/Images/plane.png"); setPixmap(image.scaled(QSize(70,70))); } Player::~Player() { } void Player::keyPressEvent(QKeyEvent * event){ if (event->key() == Qt::Key_Left) { if(pos().x() > 0) setPos(x() - 10, y()); qDebug() << pos().x() << pos().y(); } else if (event->key() == Qt::Key_Right) { if(pos().x() < game->windowWidth - 70) setPos(x() + 10, y()); qDebug() << pos().x() << pos().y(); } /*else if (event->key() == Qt::Key_Up) { setPos(x(), y()+10); qDebug() << pos().x() << pos().y(); } else if (event->key() == Qt::Key_Down) { setPos(x(), y() - 10); qDebug() << pos().x() << pos().y(); }*/ else if (event->key() == Qt::Key_Space) { Bullets * bullet = new Bullets(); bullet->setPos(x() + 32, y()); scene()->addItem(bullet); } } void Player::spawn() { //create an enemy Enemy * enemy = new Enemy(); scene()->addItem(enemy); }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GeneticAI.h" #include "Blueprint/UserWidget.h" #include "NeuralNetworkWidget.generated.h" class USafeZone; class UVerticalBox; class UHorizontalBox; class ANeuralNetworkManager; UCLASS() class GENETICAI_API UNeuralNetworkWidget : public UUserWidget { GENERATED_BODY() public: // Optionally override the Blueprint "Event Construct" event virtual void NativeConstruct() override; // Optionally override the tick event virtual void NativeTick(const FGeometry& MyGeometry, float InDeltaTime) override; protected: UFUNCTION(BlueprintNativeEvent, BlueprintCallable) void InitWidget(); UFUNCTION(BlueprintNativeEvent, BlueprintCallable) void UpdateSpecimen(uint8 NumberOfSpecimen); UFUNCTION(BlueprintNativeEvent, BlueprintCallable) void UpdateGeneration(uint8 NumberOfGeneration); UFUNCTION(BlueprintNativeEvent, BlueprintCallable) void UpdateFitness(float Fitness); UFUNCTION(BlueprintNativeEvent) void CreateOutputFunctions(const TArray<FName>& Names, const TArray<uint8>& Indexes); UFUNCTION(BlueprintNativeEvent) void UpdateOutputFunctions(const TArray<float>& Values); UFUNCTION(BlueprintNativeEvent) void EndRun(float TimeToNextSpecimen, float Fitness, uint8 SpecimenNumber); public: UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Manager") ANeuralNetworkManager* Manager; };
#define MAX_INT 1000000 #define MAX_N 400000 #include <stdio.h> #include<iostream> using namespace std; long long int count=0; int main(){ int quicksort(int *x,int *y,int lef, long long int righ); int mergesort(int *L,long long int n); //输入 long long int n; scanf("%d",&n); int x[MAX_N]; int y[MAX_N]; int i; for (i=0;i<n;i++){ scanf("%d %d",&(x[i]),&(y[i])); } //排序x quicksort(x,y,0,n-1); //归并排序得逆序数 mergesort(y,n-1); printf("%lld",(long long int)n*(n-1)/2-count); return 0; } //归并同时记录逆序数 int merge(int *L,int low,int m,long long int high){ int i=low; int j=m+1; int k=0; int *t=new int[high-low+1]; while(i<=m&&j<=high){ if(L[i]<=L[j]){ t[k++]=L[i]; i++; } else{ t[k++]=L[j++]; count=count+m+1-i; } } while(i<=m){ t[k++]=L[i]; i++; } while(j<=high){ t[k++]=L[j++]; } for(i=low,k=0;i<=high;i++,k++) L[i]=t[k]; delete []t; return 0; } //分开 int sort(int *L,int low,long long int high){ int mid; if(low<high){ mid=(low+high)/2; sort(L,low,mid); sort(L,mid+1,high); merge(L,low,mid,high); } return 0; } //归并排序并记录逆序数 int mergesort(int *L,long long int n){ sort(L,0,n); return 0; } //快速排序算法 int quicksort(int *x,int *y, int lef, long long int righ){ if (lef<righ){ int i=lef; int j=righ; int xx=x[lef]; int yy=y[lef]; while (i<j){ while(i<j&&x[j]>=xx){ j--; } if(i<j){ x[i] =x[j]; y[i] =y[j]; i=i+1; } while(i<j&&x[i]<xx){ i++; } if(i<j){ x[j] =x[i]; y[j] =y[i]; j=j-1; } } x[i] =xx; y[i] =yy; quicksort(x,y,lef,i - 1); quicksort(x,y,i+1,righ); } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2009 - 2011 * * WebGL GLSL compiler -- parser. * * Inspired some by es_parser. */ #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_lexer.h" #include "modules/webgl/src/wgl_parser.h" #include "modules/webgl/src/wgl_string.h" #include "modules/util/opstring.h" #define WGL_MAX_DOUBLE_LIT_LENGTH 60 #define MATCH(x) Match(x, __LINE__) #define OPTIONAL_MATCH(x) Match(x, __LINE__) #define NotMATCH(x) NotMatch(x, __LINE__) #define EXPECT_MATCH(t, l) do { if (Current() != t) { WGL_Parser::ErrorExpected(l, __LINE__); } else { Eat(FALSE); } } while(0) #define REQUIRED(v, act, err) v = act; if (!v) { WGL_Parser::Error(err, __LINE__); } static WGL_BasicType::Type ToBasicType(WGL_Token::Token t) { switch (t) { case WGL_Token::TOKEN_VOID: return WGL_BasicType::Void; case WGL_Token::TOKEN_FLOAT: return WGL_BasicType::Float; case WGL_Token::TOKEN_INT: return WGL_BasicType::Int; case WGL_Token::TOKEN_BOOL: return WGL_BasicType::Bool; default: OP_ASSERT(!"Unexpected basic type token"); return WGL_BasicType::Void; } } WGL_Expr* WGL_Parser::Expression() { WGL_Expr *e1 = AssignmentExpression(); if (!e1) return NULL; while (MATCH(WGL_Token::TOKEN_COMMA)) { WGL_Expr *e2 = AssignmentExpression(); if (!e2) Error(WGL_Error::EXPECTED_EXPR, __LINE__); else e1 = GetASTBuilder()->BuildSeqExpression(e1, e2); } return e1; } WGL_Expr* WGL_Parser::AssignmentExpression() { WGL_Expr *e1 = CondExpression(); int tok = Current(); switch (tok) { case WGL_Token::TOKEN_MOD_ASSIGN: case WGL_Token::TOKEN_LEFT_ASSIGN: case WGL_Token::TOKEN_RIGHT_ASSIGN: case WGL_Token::TOKEN_AND_ASSIGN: case WGL_Token::TOKEN_OR_ASSIGN: case WGL_Token::TOKEN_XOR_ASSIGN: Error(WGL_Error::RESERVED_OPERATOR, __LINE__); return NULL; default: break; } while (GET_TOKEN_PRECEDENCE(tok = Current()) == WGL_Expr::PrecAssign) { Eat(); /* Weird; no evidence of being supported (any longer?) in the grammar, but conformance tests use it. * Just recognise for now. */ if (token == WGL_Token::TOKEN_HIGH_PREC || token == WGL_Token::TOKEN_MED_PREC || token == WGL_Token::TOKEN_LOW_PREC) Eat(); WGL_Expr *e2 = AssignmentExpression(); if (!e2) Error(WGL_Error::EXPECTED_EXPR, __LINE__); e1 = GetASTBuilder()->BuildAssignExpression(tok == WGL_Token::TOKEN_EQUAL ? WGL_Expr::OpAssign : GET_TOKEN_OPERATOR(tok), e1, e2); } return e1; } WGL_Expr* WGL_Parser::CondExpression() { WGL_Expr *e1 = BinaryExpression(WGL_Expr::PrecCond + 1); if (!e1) return NULL; while (MATCH(WGL_Token::TOKEN_COND)) { WGL_Expr *e2; REQUIRED(e2, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_COLON, ":"); WGL_Expr *e3; REQUIRED(e3, AssignmentExpression(), WGL_Error::EXPECTED_EXPR); e1 = GetASTBuilder()->BuildCondExpression(e1, e2, e3); } return e1; } WGL_Expr* WGL_Parser::BinaryExpression(int prec) { WGL_Expr *e1 = UnaryExpression(); int tok = Current(); switch(tok) { case WGL_Token::TOKEN_MOD: case WGL_Token::TOKEN_SHIFTL: case WGL_Token::TOKEN_SHIFTR: case WGL_Token::TOKEN_BITAND: case WGL_Token::TOKEN_BITOR: case WGL_Token::TOKEN_BITXOR: Error(WGL_Error::RESERVED_OPERATOR, __LINE__); return NULL; default: break; } if (GET_TOKEN_PRECEDENCE(tok) >= WGL_Expr::PrecPrefix) return e1; for (int k1 = GET_TOKEN_PRECEDENCE(tok); k1 >= prec; k1--) while (GET_TOKEN_PRECEDENCE(tok) == k1) { Eat(); WGL_Expr *e2; REQUIRED(e2, BinaryExpression(k1+1), WGL_Error::EXPECTED_EXPR); if (!e1) Error(WGL_Error::EXPECTED_EXPR, __LINE__); e1 = GetASTBuilder()->BuildBinaryExpression(GET_TOKEN_OPERATOR(tok), e1, e2); tok = Current(); } return e1; } /* Unary prefix and postfix expressions. These operators bind tighter than any binary operator, and postfix ++ and -- binds more tightly than any prefix operator. */ WGL_Expr * WGL_Parser::UnaryExpression() { int tok = Current(); switch (tok) { case WGL_Token::TOKEN_INC: case WGL_Token::TOKEN_DEC: case WGL_Token::TOKEN_ADD: case WGL_Token::TOKEN_SUB: case WGL_Token::TOKEN_NOT: case WGL_Token::TOKEN_NEGATE: { Eat(); WGL_Expr *e1 = UnaryExpression(); if (tok == WGL_Token::TOKEN_SUB) tok = WGL_Token::TOKEN_NEGATE; return GetASTBuilder()->BuildUnaryExpression(GET_TOKEN_OPERATOR(tok), e1); } case WGL_Token::TOKEN_COMPLEMENT: Error(WGL_Error::RESERVED_OPERATOR, __LINE__); return NULL; default: return PostfixExpression(); } } WGL_Expr * WGL_Parser::PostfixExpression() { WGL_Expr *e1 = NULL; int tok = Current(); BOOL rewriteTexCoords = FALSE; switch (tok) { case WGL_Token::TOKEN_IDENTIFIER: { WGL_VarName *i = GetIdentifier(); // Since the textures are stored upside down internally we skip the tc rewrite for now. //rewriteTexCoords = rewrite_texcoords && !uni_strcmp(i->value, UNI_L("texture2D")); Eat(); if (context->IsTypeName(i)) e1 = GetASTBuilder()->BuildTypeConstructor(GetASTBuilder()->BuildTypeName(i)); else e1 = GetASTBuilder()->BuildIdentifier(i); break; } case WGL_Token::TOKEN_TYPE_NAME: { WGL_VarName *i = GetTypeName(); Eat(); e1 = GetASTBuilder()->BuildIdentifier(i); break; } case WGL_Token::TOKEN_PRIM_TYPE_NAME: { unsigned tok = GetTypeNameTag(); Eat(); WGL_Type *t = NULL; if (WGL_Context::IsVectorType(tok)) t = GetASTBuilder()->BuildVectorType(WGL_Context::ToVectorType(tok)); else if (WGL_Context::IsMatrixType(tok)) t = GetASTBuilder()->BuildMatrixType(WGL_Context::ToMatrixType(tok)); else if (WGL_Context::IsSamplerType(tok)) t = GetASTBuilder()->BuildSamplerType(WGL_Context::ToSamplerType(tok)); e1 = GetASTBuilder()->BuildTypeConstructor(t); break; } case WGL_Token::TOKEN_FLOAT: case WGL_Token::TOKEN_INT: case WGL_Token::TOKEN_BOOL: { Eat(); WGL_Type *t = GetASTBuilder()->BuildBasicType(ToBasicType(static_cast<WGL_Token::Token>(tok))); e1 = GetASTBuilder()->BuildTypeConstructor(t); break; } case WGL_Token::TOKEN_CONST_TRUE: case WGL_Token::TOKEN_CONST_FALSE: { Eat(); e1 = GetASTBuilder()->BuildBoolLit(tok == WGL_Token::TOKEN_CONST_TRUE); break; } case WGL_Token::TOKEN_CONST_FLOAT: case WGL_Token::TOKEN_CONST_INT: case WGL_Token::TOKEN_CONST_UINT: { WGL_Literal *l = GetLiteral(tok); Eat(); e1 = GetASTBuilder()->BuildLiteral(l); break; } case WGL_Token::TOKEN_LPAREN: { Eat(); REQUIRED(e1, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_RPAREN, ")"); break; } default: return NULL; } if (MATCH(WGL_Token::TOKEN_LPAREN)) { if (MATCH(WGL_Token::TOKEN_VOID)) { EXPECT_MATCH(WGL_Token::TOKEN_RPAREN, ")"); e1 = GetASTBuilder()->BuildCallExpression(e1, NULL); } else { WGL_ExprList *args = GetASTBuilder()->NewExprList(); while (TRUE) { WGL_Expr *a1 = AssignmentExpression(); if (a1) { args->Add(a1); } if (MATCH(WGL_Token::TOKEN_RPAREN)) { // If we need to rewrite the texture coordinates from gl to dx coords. if (rewriteTexCoords && args->list.Cardinal() > 1) { // Take the second argument, the texture coordinates, out of the AST. WGL_Expr *texCoord = args->list.First()->Suc(); args->list.First()->Suc()->Out(); // Apply a translation and a division to it to change it from gl to dx coordinate system. // (x, y) -> (x, 1 - y). We do it this way since we don't know the quality of the compiler // and don't want to risk having the expression evaluated twice. We cannot use a // multiplication since that will be treated as multiplying a row and a column matrix together. WGL_Expr *flippedTexCoord = ApplyBinaryOpWithLiteralVec2(0, 1, WGL_Expr::OpSub, texCoord); WGL_Expr *finalTexCoord = ApplyBinaryOpWithLiteralVec2(-1, 1, WGL_Expr::OpDiv, flippedTexCoord, false); // Put the final texture coordinates back in to the AST again. finalTexCoord->Follow(args->list.First()); } e1 = GetASTBuilder()->BuildCallExpression(e1, args); break; } if (NotMATCH(WGL_Token::TOKEN_COMMA)) { ErrorExpected(", or )", __LINE__); return NULL; } } } } while ((tok=Current()) == WGL_Token::TOKEN_LBRACKET || tok == WGL_Token::TOKEN_DOT) { if (MATCH(WGL_Token::TOKEN_LBRACKET)) { WGL_Expr *e2 = Expression(); EXPECT_MATCH(WGL_Token::TOKEN_RBRACKET, "]"); e1 = GetASTBuilder()->BuildIndexExpression(e1, e2); while (MATCH(WGL_Token::TOKEN_LBRACKET)) { WGL_Expr *e2 = Expression(); EXPECT_MATCH(WGL_Token::TOKEN_RBRACKET, "]"); e1 = GetASTBuilder()->BuildIndexExpression(e1, e2); } } if (MATCH(WGL_Token::TOKEN_DOT)) { if (NotMATCH(WGL_Token::TOKEN_IDENTIFIER)) ErrorExpected(".<identifier>", __LINE__); else { WGL_VarName *i = GetIdentifier(); e1 = GetASTBuilder()->BuildFieldSelect(e1, i); } } } if ((tok=Current()) == WGL_Token::TOKEN_INC || tok == WGL_Token::TOKEN_DEC) { Eat(); return GetASTBuilder()->BuildPostOpExpression(e1, tok == WGL_Token::TOKEN_INC ? WGL_Expr::OpPostInc : WGL_Expr::OpPostDec); } return e1; } WGL_Expr * WGL_Parser::ApplyBinaryOpWithLiteralVec2(int x, int y, WGL_Expr::Operator op, WGL_Expr *expr, BOOL expr_on_rhs) { WGL_Expr *vec2Constructor = GetASTBuilder()->BuildTypeConstructor(GetASTBuilder()->BuildVectorType(WGL_VectorType::Vec2)); WGL_ExprList *vec2ConstructorArgs = GetASTBuilder()->NewExprList(); vec2ConstructorArgs->Add(GetASTBuilder()->BuildIntLit(x)); vec2ConstructorArgs->Add(GetASTBuilder()->BuildIntLit(y)); WGL_Expr *vec2ConstructorCall = GetASTBuilder()->BuildCallExpression(vec2Constructor, vec2ConstructorArgs); if (expr_on_rhs) return GetASTBuilder()->BuildBinaryExpression(op, vec2ConstructorCall, expr); else return GetASTBuilder()->BuildBinaryExpression(op, expr, vec2ConstructorCall); } WGL_StmtList* WGL_Parser::StatementList(WGL_StmtList *ss) { while (TRUE) { WGL_Stmt *s = Statement(); if (!s) return ss; ss->Add(s); } return ss; } WGL_Stmt* WGL_Parser::SwitchStatement() { EXPECT_MATCH(WGL_Token::TOKEN_LPAREN, "("); WGL_Expr *e; REQUIRED(e, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_RPAREN, ")"); EXPECT_MATCH(WGL_Token::TOKEN_LBRACE, "{"); WGL_StmtList *ss = GetASTBuilder()->NewStmtList(); StatementList(ss); EXPECT_MATCH(WGL_Token::TOKEN_RBRACE, "}"); return GetASTBuilder()->BuildSwitchStmt(e, ss); } WGL_Stmt* WGL_Parser::WhileStatement() { WGL_Expr *e; EXPECT_MATCH(WGL_Token::TOKEN_LPAREN, "("); REQUIRED(e, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_RPAREN, ")"); EXPECT_MATCH(WGL_Token::TOKEN_LBRACE, "{"); WGL_Stmt *s = BlockStatement(); return GetASTBuilder()->BuildWhileStmt(e, s); } WGL_Stmt* WGL_Parser::ForStatement() { EXPECT_MATCH(WGL_Token::TOKEN_LPAREN, "("); WGL_Stmt *s1 = NULL; WGL_Expr *e1 = NULL; WGL_Expr *e2 = NULL; if (MATCH(WGL_Token::TOKEN_SEMI)) s1 = NULL; else REQUIRED(s1, Statement(), WGL_Error::EXPECTED_STMT); if (MATCH(WGL_Token::TOKEN_SEMI)) e1 = NULL; else REQUIRED(e1, Expression(), WGL_Error::EXPECTED_EXPR); if (MATCH(WGL_Token::TOKEN_SEMI)) e2 = Expression(); if (NotMATCH(WGL_Token::TOKEN_RPAREN)) ErrorExpected(")", __LINE__); WGL_Stmt *body = Statement(); return GetASTBuilder()->BuildForStmt(s1, e1, e2, body); } WGL_Stmt* WGL_Parser::IfStatement() { WGL_Expr *e; WGL_Stmt *s; unsigned line_no = lexer->GetLineNumber(); EXPECT_MATCH(WGL_Token::TOKEN_LPAREN, "("); REQUIRED(e, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_RPAREN, ")"); REQUIRED(s, Statement(), WGL_Error::EXPECTED_STMT); if (NotMATCH(WGL_Token::TOKEN_ELSE)) return GetASTBuilder()->BuildIfStmt(e, s, NULL, line_no); WGL_Stmt *el; REQUIRED(el, Statement(), WGL_Error::EXPECTED_STMT); return GetASTBuilder()->BuildIfStmt(e, s, el, line_no); } WGL_Stmt* WGL_Parser::Statement() { int tok = Current(); if (MATCH(WGL_Token::TOKEN_SEMI)) return GetASTBuilder()->BuildSimpleStmt(WGL_SimpleStmt::Empty); else if (MATCH(WGL_Token::TOKEN_LBRACE)) if (MATCH(WGL_Token::TOKEN_RBRACE)) return GetASTBuilder()->BuildSimpleStmt(WGL_SimpleStmt::Empty); else return BlockStatement(); else if (MATCH(WGL_Token::TOKEN_SWITCH)) return SwitchStatement(); else if (MATCH(WGL_Token::TOKEN_WHILE)) return WhileStatement(); else if (MATCH(WGL_Token::TOKEN_DO)) return DoStatement(); else if (MATCH(WGL_Token::TOKEN_FOR)) return ForStatement(); else if (MATCH(WGL_Token::TOKEN_IF)) return IfStatement(); else if (MATCH(WGL_Token::TOKEN_DEFAULT)) { EXPECT_MATCH(WGL_Token::TOKEN_COLON, ":"); return GetASTBuilder()->BuildSimpleStmt(WGL_SimpleStmt::Default); } else if (MATCH(WGL_Token::TOKEN_CASE)) { WGL_Expr *e = Expression(); if (!e) Error(WGL_Error::EXPECTED_EXPR, __LINE__); EXPECT_MATCH(WGL_Token::TOKEN_COLON, ":"); return GetASTBuilder()->BuildCaseLabel(e); } else if (MATCH(WGL_Token::TOKEN_CONTINUE) || MATCH(WGL_Token::TOKEN_BREAK) || MATCH(WGL_Token::TOKEN_DISCARD)) { EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); WGL_SimpleStmt::Type k = WGL_SimpleStmt::Continue; if (tok == WGL_Token::TOKEN_BREAK) k = WGL_SimpleStmt::Break; else if (tok == WGL_Token::TOKEN_DISCARD) k = WGL_SimpleStmt::Discard; return GetASTBuilder()->BuildSimpleStmt(k); } else if (MATCH(WGL_Token::TOKEN_RETURN)) { if (MATCH(WGL_Token::TOKEN_SEMI)) return GetASTBuilder()->BuildReturnStmt(NULL); WGL_Expr *e; REQUIRED(e, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return GetASTBuilder()->BuildReturnStmt(e); } else if (Current() == WGL_Token::TOKEN_INVARIANT) { WGL_DeclStmt *decl_stmt = static_cast<WGL_DeclStmt *>(GetASTBuilder()->BuildDeclStmt(NULL)); if (InvariantDeclaration(&decl_stmt->decls)) return decl_stmt; } else if (MATCH(WGL_Token::TOKEN_PRECISION)) { WGL_Type::Precision pq = PrecQualifier(); WGL_Type *t = TypeSpecifier(); EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return GetASTBuilder()->BuildDeclStmt(GetASTBuilder()->BuildPrecisionDecl(pq, t)); } if (WGL_Decl *d = SingleDeclaration()) { WGL_Type *type = NULL; WGL_DeclStmt *decl_stmt = static_cast<WGL_DeclStmt *>(GetASTBuilder()->BuildDeclStmt(d)); switch (d->GetType()) { case WGL_Decl::Var: type = static_cast<WGL_VarDecl *>(d)->type; break; case WGL_Decl::Array: type = static_cast<WGL_ArrayDecl *>(d)->type; break; default: return decl_stmt; } BOOL found = FALSE; while (LookingAt(WGL_Token::TOKEN_COMMA)) { Eat(); EXPECT_MATCH(WGL_Token::TOKEN_IDENTIFIER, "id"); WGL_VarName *i = GetIdentifier(); WGL_Decl *d1 = VarDeclPartial(type, i); if (!d1) break; decl_stmt->Add(d1); found = TRUE; } if (!found) EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return decl_stmt; } if (WGL_Expr *e = Expression()) { EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return GetASTBuilder()->BuildExprStmt(e); } else return NULL; } WGL_Stmt* WGL_Parser::DoStatement() { WGL_Stmt *s; WGL_Expr *e; REQUIRED(s, Statement(), WGL_Error::EXPECTED_STMT); EXPECT_MATCH(WGL_Token::TOKEN_WHILE, "while"); EXPECT_MATCH(WGL_Token::TOKEN_LPAREN, "("); REQUIRED(e, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_RPAREN, ")"); EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return GetASTBuilder()->BuildDoStmt(s,e); } WGL_Type * WGL_Parser::TypeSpecifierNoPrec() { int tok = Current(); switch (tok) { case WGL_Token::TOKEN_VOID: case WGL_Token::TOKEN_FLOAT: case WGL_Token::TOKEN_INT: case WGL_Token::TOKEN_BOOL: Eat(); return GetASTBuilder()->BuildBasicType(ToBasicType(static_cast<WGL_Token::Token>(tok))); case WGL_Token::TOKEN_PRIM_TYPE_NAME: { unsigned tok = GetTypeNameTag(); Eat(); if (WGL_Context::IsVectorType(tok)) return GetASTBuilder()->BuildVectorType(WGL_Context::ToVectorType(tok)); if (WGL_Context::IsMatrixType(tok)) return GetASTBuilder()->BuildMatrixType(WGL_Context::ToMatrixType(tok)); if (WGL_Context::IsSamplerType(tok)) return GetASTBuilder()->BuildSamplerType(WGL_Context::ToSamplerType(tok)); else Error(WGL_Error::ILLEGAL_TYPE_NAME, __LINE__); } case WGL_Token::TOKEN_TYPE_NAME: { WGL_VarName *i = GetTypeName(); Eat(); return GetASTBuilder()->BuildTypeName(i); } case WGL_Token::TOKEN_IDENTIFIER: { WGL_VarName *id = GetIdentifier(); if (context->IsTypeName(id)) { Eat(); return GetASTBuilder()->BuildTypeName(id); } else return NULL; } case WGL_Token::TOKEN_STRUCT: { Eat(); if (LookingAt(WGL_Token::TOKEN_IDENTIFIER)) { WGL_VarName *i = GetIdentifier(); Eat(); EXPECT_MATCH(WGL_Token::TOKEN_LBRACE, "{"); WGL_FieldList *s = StructDeclaration(); EXPECT_MATCH(WGL_Token::TOKEN_RBRACE, "}"); context->NewTypeName(i); return GetASTBuilder()->BuildStructType(i, s); } else if (NotMATCH(WGL_Token::TOKEN_LBRACE)) Error(WGL_Error::ILLEGAL_STRUCT, __LINE__); WGL_FieldList *s = StructDeclaration(); if (!s) Error(WGL_Error::ILLEGAL_STRUCT, __LINE__); EXPECT_MATCH(WGL_Token::TOKEN_RBRACE, "}"); return GetASTBuilder()->BuildStructType(WGL_String::Make(context, UNI_L("anon")), s); } default: return NULL; } } WGL_FieldList* WGL_Parser::StructDeclaration() { WGL_FieldList *fs = GetASTBuilder()->NewFieldList(); while (TRUE) { WGL_TypeQualifier *tq = TypeQualify(FALSE/*no invariant seen*/); WGL_Type *t = TypeSpecifier(); if (!t) break; if (tq) t->AddTypeQualifier(tq); while (TRUE) { if (LookingAt(WGL_Token::TOKEN_IDENTIFIER)) { WGL_VarName *i = GetIdentifier(); Eat(); if (MATCH(WGL_Token::TOKEN_LBRACKET)) { WGL_Expr *sz = Expression(); EXPECT_MATCH(WGL_Token::TOKEN_RBRACKET, "]"); fs->Add(context, GetASTBuilder()->BuildArrayType(t, sz), i); } else fs->Add(context, t, i); } else Error(WGL_Error::ANON_FIELD, __LINE__); if (NotMATCH(WGL_Token::TOKEN_COMMA)) break; } if (NotMATCH(WGL_Token::TOKEN_SEMI)) break; } return fs; } WGL_Type::Precision WGL_Parser::PrecQualifier() { switch (Current()) { case WGL_Token::TOKEN_HIGH_PREC: Eat(); return WGL_Type::High; case WGL_Token::TOKEN_MED_PREC: Eat(); return WGL_Type::Medium; case WGL_Token::TOKEN_LOW_PREC: Eat(); return WGL_Type::Low; default: return WGL_Type::NoPrecision; } } WGL_Type * WGL_Parser::TypeSpecifier() { WGL_Type::Precision precLevel = WGL_Type::NoPrecision; int tok = Current(); switch (tok) { case WGL_Token::TOKEN_HIGH_PREC: case WGL_Token::TOKEN_MED_PREC: case WGL_Token::TOKEN_LOW_PREC: Eat(); precLevel = TO_PRECEDENCE_LEVEL(tok); break; } WGL_Type *t = TypeSpecifierNoPrec(); if (t && precLevel > 0) return t->AddPrecision(precLevel); else return t; } WGL_Decl * WGL_Parser::InvariantDeclaration(List<WGL_Decl> *ds) { if (MATCH(WGL_Token::TOKEN_INVARIANT)) { if (Current() != WGL_Token::TOKEN_IDENTIFIER) { WGL_Type *t = FullType(TRUE); if (Current() == WGL_Token::TOKEN_IDENTIFIER) { WGL_VarName *i = GetIdentifier(); Eat(); WGL_Decl *d1 = GetASTBuilder()->BuildTypeDecl(t, i); if (!d1) return NULL; d1->Into(ds); while (MATCH(WGL_Token::TOKEN_COMMA)) { WGL_VarName *i = GetIdentifier(); Eat(); WGL_Decl *d = GetASTBuilder()->BuildTypeDecl(t, i); if (!d) return d1; d->Into(ds); if (Current() != WGL_Token::TOKEN_COMMA) break; } return d1; } } WGL_VarName *i = GetIdentifier(); Eat(); WGL_Decl *invariant_decl = GetASTBuilder()->BuildInvariantDecl(i); WGL_InvariantDecl *next_decl = static_cast<WGL_InvariantDecl *>(invariant_decl); if (!invariant_decl) return NULL; invariant_decl->Into(ds); while (MATCH(WGL_Token::TOKEN_COMMA)) { WGL_VarName *i = GetIdentifier(); Eat(); WGL_Decl *d = GetASTBuilder()->BuildInvariantDecl(i); if (!d) return invariant_decl; next_decl->next = static_cast<WGL_InvariantDecl *>(d); next_decl = next_decl->next; if (Current() != WGL_Token::TOKEN_COMMA) break; } return invariant_decl; } else return NULL; } WGL_Decl * WGL_Parser::SingleDeclaration() { WGL_Type *t = FullType(FALSE); if (!t) return NULL; if (Current() != WGL_Token::TOKEN_IDENTIFIER) return GetASTBuilder()->BuildTypeDecl(t,NULL); WGL_VarName *i = GetIdentifier(); Eat(); return VarDeclPartial(t, i); } WGL_Decl * WGL_Parser::VarDeclPartial(WGL_Type *t, WGL_VarName *i) { if (MATCH(WGL_Token::TOKEN_EQUAL)) { WGL_Expr *e = AssignmentExpression(); return GetASTBuilder()->BuildVarDecl(t,i,e); } if (NotMATCH(WGL_Token::TOKEN_LBRACKET)) return GetASTBuilder()->BuildVarDecl(t,i,NULL); WGL_Expr *c = Expression(); if (!c) Error(WGL_Error::EXPECTED_EXPR, __LINE__); EXPECT_MATCH(WGL_Token::TOKEN_RBRACKET, "]"); if (NotMATCH(WGL_Token::TOKEN_EQUAL)) return GetASTBuilder()->BuildArrayDecl(t,i,c,NULL); WGL_Expr *is = Expression(); if (!is) Error(WGL_Error::EXPECTED_EXPR, __LINE__); return GetASTBuilder()->BuildArrayDecl(t,i,c,is); } WGL_DeclList* WGL_Parser::InitDeclarators(WGL_DeclList *ds, WGL_Decl *d) { WGL_DeclList *ds_new = NULL; WGL_Type *var_decl_type = NULL; if (d && d->GetType() == WGL_Decl::Var) { WGL_VarDecl *var_decl = static_cast<WGL_VarDecl *>(d); var_decl_type = var_decl->type; d = VarDeclPartial(var_decl_type, var_decl->identifier); } if (d) ds->Add(d); else if ((d = SingleDeclaration())) ds->Add(d); if (!d) return ds_new; else ds_new = ds; while (TRUE) { if (Current() == WGL_Token::TOKEN_SEMI) return ds_new; if (NotMATCH(WGL_Token::TOKEN_COMMA)) return ds_new; if (LookingAt(WGL_Token::TOKEN_IDENTIFIER) && var_decl_type) { WGL_VarName *i = GetIdentifier(); Eat(); d = VarDeclPartial(var_decl_type, i); if (d) ds_new->Add(d); } else Error(WGL_Error::EXPECTED_ID, __LINE__); } return ds_new; } WGL_Type * WGL_Parser::FullType(BOOL seenInvariant) { WGL_TypeQualifier *tq = TypeQualify(seenInvariant); WGL_Type *t = TypeSpecifier(); if (t && tq) return t->AddTypeQualifier(tq); else return t; } /* Return a valid type qualifier, if matched. NULL otherwise (or error raised) */ WGL_TypeQualifier* WGL_Parser::TypeQualify(BOOL seenInvariant) { WGL_TypeQualifier *tq = GetASTBuilder()->NewTypeQualifier(); WGL_TypeQualifier::InvariantKind iq = WGL_TypeQualifier::Invariant; if (seenInvariant || ((iq = TypeQualifierInvariant()) != WGL_TypeQualifier::NoInvariant)) { tq = tq->AddInvariant(iq); EXPECT_MATCH(WGL_Token::TOKEN_VARYING, "varying"); return tq->AddStorage(WGL_TypeQualifier::Varying); } else { WGL_LayoutList *lq = TypeQualifierLayout(); if (lq != NULL) { tq = tq->AddLayout(lq); WGL_TypeQualifier::Storage sq = TypeStorageQualifier(); if (sq != WGL_TypeQualifier::NoStorage) return tq->AddStorage(sq); else return tq; } WGL_TypeQualifier::Storage sq = TypeStorageQualifier(); if (sq != WGL_TypeQualifier::NoStorage) return tq->AddStorage(sq); else return NULL; } } WGL_TypeQualifier::Storage WGL_Parser::TypeStorageQualifier() { int tok = Current(); switch (Current()) { case WGL_Token::TOKEN_CONST: case WGL_Token::TOKEN_ATTRIBUTE: case WGL_Token::TOKEN_VARYING: case WGL_Token::TOKEN_UNIFORM: case WGL_Token::TOKEN_IN_: case WGL_Token::TOKEN_OUT_: Eat(); return TO_STORAGE_QUALIFIER(tok); default: return WGL_TypeQualifier::NoStorage; } } /* * Returns a layout type qualifier if matched; NULL if no LAYOUT herald * seen; error if a partial parse. */ WGL_LayoutList * WGL_Parser::TypeQualifierLayout() { if (NotMATCH(WGL_Token::TOKEN_LAYOUT)) return NULL; EXPECT_MATCH(WGL_Token::TOKEN_LPAREN, "("); WGL_LayoutList *ls = GetASTBuilder()->NewLayoutList(); while (TRUE) { if (MATCH(WGL_Token::TOKEN_RPAREN)) break; else if (!LookingAt(WGL_Token::TOKEN_IDENTIFIER)) Error(WGL_Error::ILLEGAL_TYPE_LAYOUT, __LINE__); WGL_VarName *i = GetIdentifier(); Eat(); if (MATCH(WGL_Token::TOKEN_COMMA)) { ls->Add(GetASTBuilder()->BuildLayoutTypeQualifier(i,(-1))); continue; } EXPECT_MATCH(WGL_Token::TOKEN_EQUAL, "="); if (!LookingAt(WGL_Token::TOKEN_CONST_INT)) Error(WGL_Error::ILLEGAL_TYPE_LAYOUT, __LINE__); int v = GetIntLit(); Eat(); ls->Add(GetASTBuilder()->BuildLayoutTypeQualifier(i,v)); EXPECT_MATCH(WGL_Token::TOKEN_COMMA, ","); } return ls; } WGL_TypeQualifier::InvariantKind WGL_Parser::TypeQualifierInvariant() { int tok = Current(); switch (tok) { case WGL_Token::TOKEN_INVARIANT: Eat(); return TO_INVARIANT_QUALIFIER(tok); default: return WGL_TypeQualifier::NoInvariant; } } WGL_DeclList* WGL_Parser::TopDecls() { WGL_DeclList *ts = GetASTBuilder()->NewDeclList(); WGL_Decl *d; while (!LookingAt(WGL_Token::TOKEN_EOF)) { WGL_Decl *tyd = NULL; unsigned fun_start = lexer->GetLineNumber(); tyd = InvariantDeclaration(&ts->list); if (tyd) { EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); continue; } d = FunctionPrototype(tyd); if (tyd) { InitDeclarators(ts, tyd); EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); } else if (!d) { if (!(Declaration(ts))) break; OPTIONAL_MATCH(WGL_Token::TOKEN_SEMI); } else { if (MATCH(WGL_Token::TOKEN_LBRACE)) { WGL_Stmt *s = BlockStatement(); unsigned fun_end = lexer->GetLineNumber(); GetASTBuilder()->SetLineNumber(fun_start); ts->Add(GetASTBuilder()->BuildFunctionDefn(d, s)); GetASTBuilder()->SetLineNumber(fun_end); } else { OPTIONAL_MATCH(WGL_Token::TOKEN_SEMI); ts->Add(d); } } } if (!LookingAt(WGL_Token::TOKEN_EOF)) ParseError(); return ts; } WGL_Stmt * WGL_Parser::BlockStatement() { WGL_StmtList *ss = GetASTBuilder()->NewStmtList(); while (TRUE) { if (MATCH(WGL_Token::TOKEN_RBRACE)) break; WGL_Stmt *s = Statement(); if (!s) { Error(WGL_Error::EXPECTED_STMT, __LINE__); break; } else { ss->Add(s); if (Current() == WGL_Token::TOKEN_SEMI) Eat(); } } return GetASTBuilder()->BuildBlockStmt(ss); } WGL_DeclList* WGL_Parser::Declaration(WGL_DeclList *ds) { if (MATCH(WGL_Token::TOKEN_PRECISION)) { WGL_Type::Precision pq = PrecQualifier(); WGL_Type *t = TypeSpecifier(); EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return ds->Add(GetASTBuilder()->BuildPrecisionDecl(pq, t)); } WGL_Decl *tydecl = NULL; WGL_Decl *proto = FunctionPrototype(tydecl); if (proto) { EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return ds->Add(proto); } WGL_DeclList *ds_added = InitDeclarators(ds, tydecl); if (ds_added) { EXPECT_MATCH(WGL_Token::TOKEN_SEMI, ";"); return ds; } return NULL; } WGL_Decl * WGL_Parser::FunctionPrototype(WGL_Decl *&tyd) { WGL_Type *ret_ty = FullType(FALSE); if (!ret_ty) return NULL; if (LookingAt(WGL_Token::TOKEN_IDENTIFIER)) { WGL_VarName *fun = GetIdentifier(); Eat(); if (NotMATCH(WGL_Token::TOKEN_LPAREN)) { tyd = GetASTBuilder()->BuildVarDecl(ret_ty, fun, NULL); return NULL; } WGL_ParamList *ps = GetASTBuilder()->NewParamList(); if (MATCH(WGL_Token::TOKEN_VOID)) { EXPECT_MATCH(WGL_Token::TOKEN_RPAREN, ")"); return GetASTBuilder()->BuildFunctionProto(ret_ty, fun, ps); } while (TRUE) { if (MATCH(WGL_Token::TOKEN_RPAREN)) return GetASTBuilder()->BuildFunctionProto(ret_ty, fun, ps); OPTIONAL_MATCH(WGL_Token::TOKEN_CONST); int tok = Current(); WGL_Param::Direction pqual = WGL_Param::None; if (tok == WGL_Token::TOKEN_IN_ || tok == WGL_Token::TOKEN_OUT_ || tok == WGL_Token::TOKEN_INOUT) { pqual = TO_PARAM_DIRECTION(tok); Eat(); } WGL_Type *t = TypeSpecifier(); if (!t) return NULL; WGL_VarName *formal = NULL; if (LookingAt(WGL_Token::TOKEN_IDENTIFIER)) { formal = GetIdentifier(); Eat(); } if (MATCH(WGL_Token::TOKEN_COMMA)) { if (!formal) formal = context->NewUniqueVar(TRUE); ps->Add(GetASTBuilder()->BuildParam(t, pqual, formal)); } else if (MATCH(WGL_Token::TOKEN_RPAREN)) { if (!formal) formal = context->NewUniqueVar(TRUE); ps->Add(GetASTBuilder()->BuildParam(t, pqual, formal)); return GetASTBuilder()->BuildFunctionProto(ret_ty, fun, ps); } else if (formal && MATCH(WGL_Token::TOKEN_LBRACKET)) { WGL_Expr *cs; REQUIRED(cs, Expression(), WGL_Error::EXPECTED_EXPR); EXPECT_MATCH(WGL_Token::TOKEN_RBRACKET, "]"); if (MATCH(WGL_Token::TOKEN_COMMA)) ps->Add(GetASTBuilder()->BuildParam(GetASTBuilder()->BuildArrayType(t,cs), pqual, formal)); else if (MATCH(WGL_Token::TOKEN_RPAREN)) { ps->Add(GetASTBuilder()->BuildParam(GetASTBuilder()->BuildArrayType(t,cs), pqual, formal)); return GetASTBuilder()->BuildFunctionProto(ret_ty, fun, ps); } else Error(WGL_Error::EXPECTED_COMMA, __LINE__); } else Error(WGL_Error::EXPECTED_COMMA, __LINE__); } } tyd = GetASTBuilder()->BuildTypeDecl(ret_ty, NULL); return NULL; } /* static */ void WGL_Parser::MakeL(WGL_Parser *&parser, WGL_Context *context, WGL_Lexer *l, BOOL for_vertex, BOOL rewrite_tc) { context->ResetL(for_vertex); parser = OP_NEWGRO_L(WGL_Parser, (), context->Arena()); parser->rewrite_texcoords = rewrite_tc; parser->lexer = l; parser->context = context; } int WGL_Parser::Current() { if (token < 0) token = lexer->GetToken(); return token; } int WGL_Parser::Match(int l, int ll) { if (token == l) { Eat(); return 1; } return 0; } int WGL_Parser::NotMatch(int l, int ll) { if (token != l) return 1; Eat(); return 0; } int WGL_Parser::LookingAt(int l) { return (token == l); } void WGL_Parser::Eat(BOOL update_line_number) { token = lexer->GetToken(); if (update_line_number) GetASTBuilder()->SetLineNumber(lexer->GetLineNumber()); } WGL_VarName * WGL_Parser::GetIdentifier() { return lexer->lexeme.val_id; } WGL_VarName * WGL_Parser::GetTypeName() { return lexer->lexeme.val_id; } unsigned WGL_Parser::GetTypeNameTag() { return lexer->lexeme.val_ty; } WGL_Literal * WGL_Parser::GetLiteral(unsigned t) { switch (t) { case WGL_Token::TOKEN_CONST_UINT: return OP_NEWGRO_L(WGL_Literal, (lexer->lexeme.val_uint), context->Arena()); case WGL_Token::TOKEN_CONST_INT: return OP_NEWGRO_L(WGL_Literal, (lexer->lexeme.val_int), context->Arena()); case WGL_Token::TOKEN_CONST_FLOAT: { /* Passing along unreasonably long literals may cause the driver's compiler * to complain (ATI?), so just don't. The limit used is such that there'll * be no loss in precision. */ unsigned lit_length = static_cast<unsigned>(uni_strlen(lexer->numeric_buffer)); uni_char *numeric_str = NULL; if (lit_length < WGL_MAX_DOUBLE_LIT_LENGTH) { numeric_str = OP_NEWGROA_L(uni_char, lit_length + 1, context->Arena()); uni_strcpy(numeric_str, lexer->numeric_buffer); } return OP_NEWGRO_L(WGL_Literal, (lexer->lexeme.val_double, numeric_str), context->Arena()); } case WGL_Token::TOKEN_CONST_FALSE: return OP_NEWGRO_L(WGL_Literal,(FALSE), context->Arena()); case WGL_Token::TOKEN_CONST_TRUE: return OP_NEWGRO_L(WGL_Literal, (TRUE), context->Arena()); default: return OP_NEWGRO_L(WGL_Literal, (0), context->Arena()); } } int WGL_Parser::GetIntLit() { return lexer->lexeme.val_int; } void WGL_Parser::Error(WGL_Error::Type t, int l) { WGL_Error *item = OP_NEWGRO_L(WGL_Error, (context, t, context->GetSourceContext(), l), context->Arena()); context->AddError(item); #if defined(WGL_STANDALONE) && defined(_DEBUG) fprintf(stderr, "ERROR, line %d: %d\n", lexer->GetLineNumber(), t); fprintf(stderr, "[debug: from parser line %d]\n", l); fflush(stderr); #endif // WGL_STANDALONE && _DEBUG } void WGL_Parser::Error(WGL_Error::Type t, WGL_VarName *i) { WGL_Error *item = OP_NEWGRO_L(WGL_Error, (context, t, context->GetSourceContext(), lexer->GetLineNumber()), context->Arena()); item->SetMessageL(WGL_String::Storage(context, i)); context->AddError(item); } void WGL_Parser::ErrorExpected(const char *s, int l) { WGL_Error *item = OP_NEWGRO_L(WGL_Error, (context, WGL_Error::EXPECTED_INPUT, context->GetSourceContext(), lexer->GetLineNumber()), context->Arena()); item->SetMessageL(s); context->AddError(item); #if defined(WGL_STANDALONE) && defined(_DEBUG) fprintf(stderr, "ERROR expected %s, line %d\n", s, lexer->GetLineNumber()); fprintf(stderr, "[debug: from parser line %d]\n", l); fflush(stderr); #endif // WGL_STANDALONE && _DEBUG } void WGL_Parser::ParseError() { WGL_Error *item = OP_NEWGRO_L(WGL_Error, (context, WGL_Error::PARSE_ERROR, context->GetSourceContext(), lexer->GetLineNumber()), context->Arena()); uni_char buf[100]; // ARRAY OK 2010-12-07 sof lexer->GetErrorContext(buf, 100); item->SetMessageL(buf); context->AddError(item); } BOOL WGL_Parser::HaveErrors() { return (context->GetFirstError() != NULL); } #endif // CANVAS3D_SUPPORT
/* * HashTable.h * * Created on: Aug 19, 2014 * Author: deforestg */ #include <iostream> using namespace std; #ifndef HASHTABLE_H_ #define HASHTABLE_H_ #define INITIAL_SIZE 10 #define MAXIMUM_LOAD_FACTOR 0.5f template<typename Type> struct bucket { std::string key; Type value; }; template <typename Type> class HashTable { private: bucket<Type>* container; int length; unsigned int hash(const std::string& key); public: HashTable(); Type get(const std::string&); void set(const std::string& key, Type value); }; #endif /* HASHTABLE_H_ */
#ifndef HERA_COMMON_HASH_COMBINE_H #define HERA_COMMON_HASH_COMBINE_H namespace hera { template <class T> inline void hash_combine(std::size_t& seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } } #endif
#pragma once #include <UtH/UtHEngine.hpp> class Projectile : public uth::Component { public: Projectile(uth::GameObject* target, float damage, float speed); Projectile(); ~Projectile(); void Init() override; void Draw(uth::RenderTarget& target) override; void Update(float delta) override; uth::GameObject* m_TargetObj = nullptr; pmath::Vec2 m_TargetPos; float m_Damage = 1.0f; float m_Speed = 1.0f; };
// Copyright 2019 Erik Teichmann <kontakt.teichmann@gmail.com> #ifndef INCLUDE_SAM_OBSERVER_POSITION_OBSERVER_HPP_ #define INCLUDE_SAM_OBSERVER_POSITION_OBSERVER_HPP_ #include <vector> namespace sam { /*! * \brief Observer for the position and the time. * * The observer saves the position and time of the system during an integration. */ template<typename state_type> struct PositionObserver { std::vector<state_type>& position_; std::vector<double>& time_; explicit PositionObserver(std::vector<state_type>& position, std::vector<double>& time); void operator()(const state_type& x, double t) const; }; // Implementation template<typename state_type> PositionObserver<state_type>::PositionObserver( std::vector<state_type>& position, std::vector<double>& time) : position_(position), time_(time) {} template<typename state_type> void PositionObserver<state_type>::operator()(const state_type& x, double t) const { position_.push_back(x); time_.push_back(t); } } // namespace sam #endif // INCLUDE_SAM_OBSERVER_POSITION_OBSERVER_HPP_
#ifndef _TRIANGLE_H #define _TRIANGLE_H #include "sjfwd.h" #include "shape.h" #include "point.h" class triangle : public shape { public: point A; point B; point C; triangle(point a, point b, point c, bool fl = false){ this->A = a; this->B = b; this->C = c; this->fill = fl; } bool overlaps(const point) const; bool overlaps(const circle) const; bool overlaps(const rectangle) const; bool overlaps(const triangle) const; bool onscreen() const; void draw() const; void translade(double, double); }; #endif
#include "test_precomp.hpp" static const char* extraTestDataPath = #ifdef WINRT NULL; #else getenv("OPENCV_DNN_TEST_DATA_PATH"); #endif CV_TEST_MAIN("", extraTestDataPath ? (void)cvtest::addDataSearchPath(extraTestDataPath) : (void)0 ) namespace cvtest { using namespace cv; using namespace cv::dnn; }
#include <iostream> using namespace std; int main() { int v; cin >> v; cout << (v == 2 ? 2 : 1) << endl; return 0; }
// // SizeLimitedDeque.h // LostSignalTrackingNew // // Created by Andreas Müller on 26/08/2014. // // #pragma once #include <string> using namespace std; template <class T> class SizeLimitedDeque { public: // ----------------------------------------- SizeLimitedDeque() { maxSize = -1; } // ----------------------------------------- void pushFront (const T& _val) { dat.push_front( _val ); limitSizeFromBack(); } // ----------------------------------------- void pushBack (const T& _val) { dat.push_back( _val ); limitSizeFromFront(); } // ----------------------------------------- T at( int _index ) { return dat.at(_index); } // ----------------------------------------- size_t size() { return dat.size(); } // ----------------------------------------- void setMaxSize( int _size ) { maxSize = _size; } // ----------------------------------------- int getMaxSize() { return maxSize; } deque<T> dat; protected: // ----------------------------------------- void limitSizeFromBack() { if( maxSize > -1 ) { if( dat.size() > maxSize ) { while( dat.size() > maxSize ) { dat.pop_back(); } } } } // ----------------------------------------- void limitSizeFromFront() { if( maxSize > -1 ) { if( dat.size() > maxSize ) { while( dat.size() > maxSize ) { dat.pop_front(); } } } } int maxSize; };
#include <cstdlib> #include <iostream> #include <string> #include <vector> #include <sstream> // manipulate string #include <limits> // used to find min and max values of different data type int main() { // 1 - 18, 21, 50, > 65 std::string sAge = "0"; std::cout << "Enter your age: "; getline(std::cin, sAge); int nAge = std::stoi(sAge); if ((nAge >= 1) && (nAge <= 18)){ std::cout << "Important Birthday\n"; } else if ((nAge == 21) || (nAge == 50)) { std::cout << "Important Birthday\n"; } else if (nAge >= 65){ std::cout << "Important Birthday\n"; }else { std::cout << "Not Important Birthday\n"; } return 0; } /* Exercise 2 * */ // int main(){ // if age 5 "Go to Kindergarden // age 6 through 17 -> 1 through 12 // age > 17, "Go to college" // Enter age: 2 // Too young for school // Enter age: 8 // Go to grade 3 std::string sAge = "0"; std::cout << "Enter age: "; getline(std::cin, sAge); int nAge = std::stoi(sAge); if (nAge == 5){ std::cout << "Go to Kindergarden\n"; } else if((nAge >= 6) && (nAge <= 17)){ int grade = (nAge-6) + 1; std::cout << "Go to grade " << grade << "\n"; } else if (nAge > 17){ std::cout << "Go to college\n"; } else{ std::cout << "Too young for school\n"; } } /* Array 3*/ int main(){ int arrnNums[10] ={1}; int arrnNums2[] = {1,2,3}; int arrnNums3[5]={8,9}; std::cout << "1st Value: " << arrnNums3[0] << "\n"; arrnNums3[0]=7; std::cout << "1st Value: " << arrnNums3[0] << "\n"; std::cout << "Array size: " << sizeof(arrnNums3) / sizeof(*arrnNums3) << "\n"; // multi dimensional array int arrnNums4[2][2][2] = {{{1,2}, {3,4}}, {{5,6},{7,8}}}; std::cout << arrnNums4[1][1][1] <<"\n"; return 0; } /* Vector With array, once the size is set, we cannot change it. However, vector is resizable*/ int main(){ std::vector<int> vecnRandNums(2); vecnRandNums[0] = 10; vecnRandNums[1] = 10; vecnRandNums.push_back(30); std::cout << "last index :" << vecnRandNums[vecnRandNums.size() - 1] << "\n"; std::string sSentence = "This is a random string"; std::vector<std::string> vecsWords; std::stringstream ss(sSentence); std::string sIndivStr; char cSpace = ' '; while(getline(ss, sIndivStr, cSpace)){ vecsWords.push_back(sIndivStr); } for (int i=0; i<vecsWords.size(); i++){ std::cout << vecsWords[i] << "\n"; } return 0; } /* Exercise 3: Simple calculator*/ int main(){ // enter calculation (ex. 5 + 6) : 10 - 6 // 10.0 - 6.0 = 4.0 // + - * / 5 % 6 => Please enter + - / * only double num1=0; double num2=0; std::string op =" "; std::vector<std::string> vecsOperations; std::string mathOperation; std::cout << "Enter calculation (ex. 5 + 6): \n"; getline(std::cin, mathOperation); std::stringstream ss(mathOperation); std::string sIndivStr; char cSpace = ' '; while (getline(ss, sIndivStr, cSpace)){ vecsOperations.push_back(sIndivStr); } num1 = std::stod(vecsOperations[0]); num2 = std::stod(vecsOperations[2]); op = vecsOperations[1]; double result; if (op == "+") { result = num1 + num2; printf("%.1f + %.1f = %.1f", num1, num2, result); } else if(op == "-"){ result = num1 - num2; printf("%.1f - %.1f = %.1f", num1, num2, result); } else if(op == "*"){ result = num1 * num2; printf("%.1f * %.1f = %.1f", num1, num2, result); } else if(op == "/"){ result = num1 / num2; printf("%.1f / %.1f = %.1f", num1, num2, result); } else { std::cout << "Please enter + - / * only \n"; } }
#include "Viewer.h" Viewer::Viewer() { loginWidget = std::make_shared<LoginWidget>(); mainWidget = std::make_shared<MainWidget>(); connect(loginWidget.get(), SIGNAL(openMainWidget()), mainWidget.get(), SLOT(afterLogin())); } void Viewer::runApp() { auto controller = Controller::getInstance(); controller->runClient("127.0.0.1", "5555", [](int error) { std::cout << "Client error: " << error << std::endl; }); loginWidget->show(); }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define MAX 100 ll N; ll divs = 0; vector<int> v; void gen_primes() { v.push_back(2),v.push_back(3); for (int i = 4; i < 1000; ++i) { bool flag = true; for (int j = 2; j < i; ++j) { if (i % j == 0) { flag = false; break; } } if (flag) v.push_back(i); } } int main() { cin >> N; gen_primes(); vector<int> d; for (auto itr = v.begin(); itr != v.end(); itr++) { int t = *itr; int tt = 0; while (t <= N) { tt += N / t; t *= *itr; } if (tt != 0){ d.push_back(++tt); } } ll ans = 1; const long MOD = 1000000007; for (auto itr = d.begin(); itr != d.end(); ++itr) { ans *= *itr; ans %= MOD; } cout << ans << endl; }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #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; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; const int M = 1000000007; inline void add(int& x, int y) { x = (x + y) % M; } inline int mul(int x, int y) { return (LL(x) * y) % M; } int a[222], f[222][222], fact[222], C[222][222], c[222], ss[222]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); fact[0] = 1; for (int i = 1; i < 222; ++i) fact[i] = mul(fact[i - 1], i); for (int i = 0; i < 222; ++i) { C[i][0] = 1; for (int j = 1; j <= i; ++j) { C[i][j] = C[i - 1][j]; add(C[i][j], C[i - 1][j - 1]); } } int T; cin >> T; while (T--) { int n, l; cin >> n >> l; for (int i = 1; i <= n; ++i) cin >> a[i]; sort(a + 1, a + n + 1); int an = 0; for (int i = 1; i <= n; ++i) { if (an == 0 || a[i] != a[an]) { a[++an] = a[i]; c[an] = 1; } else ++c[an]; } n = an; ss[an] = 0; for (int i = n - 1; i >= 0; --i) ss[i] = ss[i + 1] + c[i + 1]; int ans = 0; memset(f, 0, sizeof(f)); a[0] = -1; f[0][0] = 1; for (int i = 0; i < l; ++i) { for (int j = 0; j < n; ++j) if (f[i][j]) { int s = 0; for (int k = j + 1; k <= n; ++k) { s += c[k]; add(f[i + 1][k], mul(f[i][j], mul(c[k], mul(C[s - 1 + ss[k]][s - 1], fact[s - 1])))); } } add(ans, f[i][n]); } add(ans, f[l][n]); cout << ans << endl; } cerr << clock() << endl; 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> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const LL mod = 1e9 + 7; int main() { int t; LL n,k; scanf("%d",&t); while (t--) { scanf("%I64d%I64d",&n,&k); LL ans = 1; if (n < (k+1)*k/2) { ans = -1; } else if (n < (k+3)*k/2) { LL inc = n - (k+1)*k/2; for (int i = k;i >= 1; i--) { if (i + inc > k) ans = (ans*(i+1))%mod; else ans = (ans*i)%mod; } } else { LL inc = n - (k+1)*k/2; LL x = inc/k,y = inc%k; for (int i = k;i >= 1; i--) { if (i + y > k) ans = (ans*(i+x+1))%mod; else ans = (ans*(i+x))%mod; } } printf("%I64d\n",ans); } return 0; }
#include<iostream> using namespace std; bool isprime(int n) { if(n<=1) return false; for(int i=2;i<n;i++) if(n%i==0) return false; return true; } bool isemirp(int n) { if(isprime(n)== false) return false; int rev=0; while(n!=0) { int lastdigit=n%10; rev= rev*10+lastdigit; n=n/10; return isprime(rev); } } int main() { int n; cout<<"Enter a number to check if a number is emirp or not"; cin>>n; if(isemirp(n)==true) cout<<"Number is emirp"; else cout<<"Number is not emirp"; }
#include <iberbar/LuaCppApis/Utility.h> #include <iberbar/LuaCppApis/Utility_Names.h> #include <iberbar/Lua/LuaError.h> #include <iberbar/Lua/LuaCppBuilder.h> #include <iberbar/Lua/LuaCppInstantiateDef.h> #include <iberbar/Utility/String.h> #include <iberbar/Utility/FileHelper.h> #include <filesystem> namespace iberbar { int LuaCFunction_ReadFileAsText( lua_State* pLuaState ); int LuaCFunction_FileSystem_IsFileExist( lua_State* pLuaState ); //int LuaCFunction_JsonDecode( lua_State* pLuaState ); int LuaCppFunction_Ref_RefCount( lua_State* pLuaState ); int LuaCppFunction_Ref___tostring( lua_State* pLuaState ); static const luaL_Reg LuaCppMethods_Ref[] = { { "RefCount", &LuaCppFunction_Ref_RefCount }, { Lua::s_ClassStandardMethod_ToString, &LuaCppFunction_Ref___tostring }, { nullptr, nullptr } }; static const Lua::UClassDefinition LuaCppDef_Ref = { LuaCppNames::s_ClassName_Ref, LuaCppNames::s_ClassName_Ref_FullName, nullptr, nullptr, nullptr, LuaCppMethods_Ref, }; } void iberbar::RegisterLuaCpp_ForUtility( lua_State* pLuaState ) { Lua::CBuilder builder( pLuaState ); builder.ResolveScope( []( Lua::CScopeBuilder* scope ) { scope->AddFunctionOne( "ReadFileAsText", &LuaCFunction_ReadFileAsText ); scope->AddClass( LuaCppDef_Ref ); scope->AddEnum( "UAlignHorizontal", []( Lua::CEnumBuilder* pEnum ) { pEnum->AddValueInt( "Left", (lua_Integer)UAlignHorizental::Left ); pEnum->AddValueInt( "Center", (lua_Integer)UAlignHorizental::Center ); pEnum->AddValueInt( "Right", (lua_Integer)UAlignHorizental::Right ); } ); scope->AddEnum( "UAlignVertical", []( Lua::CEnumBuilder* pEnum ) { pEnum->AddValueInt( "Top", (lua_Integer)UAlignVertical::Top ); pEnum->AddValueInt( "Center", (lua_Integer)UAlignVertical::Center ); pEnum->AddValueInt( "Bottom", (lua_Integer)UAlignVertical::Bottom ); } ); }, "iberbar" ); builder.ResolveScope( []( Lua::CScopeBuilder* scope ) { scope->AddFunctionOne( "IsFileExist", &LuaCFunction_FileSystem_IsFileExist ); }, "iberbar.FileSystem" ); } int iberbar::LuaCFunction_ReadFileAsText( lua_State* pLuaState ) { int t = lua_gettop( pLuaState ); if ( t != 1 ) return iberbar_LuaError_ArgumentsCountIsNotMatch( pLuaState, 1 ); const char* strFile = lua_tostring( pLuaState, 1 ); if ( StringIsNullOrEmpty( strFile ) ) { lua_pushboolean( pLuaState, false ); lua_pushstring( pLuaState, "" ); } else { CFileHelper FileHelper; bool ret = FileHelper.OpenFileA( strFile, "r" ); if ( ret == true ) { lua_pushboolean( pLuaState, ret ); lua_pushstring( pLuaState, FileHelper.ReadAsText().c_str() ); } else { lua_pushboolean( pLuaState, ret ); lua_pushstring( pLuaState, "" ); } FileHelper.CloseFile(); } return 2; } int iberbar::LuaCFunction_FileSystem_IsFileExist( lua_State* pLuaState ) { int nTop = lua_gettop( pLuaState ); iberbar_LuaCheckArguments( pLuaState, nTop, 1 ); const char* strFilePath = lua_tostring( pLuaState, 1 ); if ( StringIsNullOrEmpty( strFilePath ) ) { lua_pushboolean( pLuaState, 0 ); return 1; } std::filesystem::path fsPath = strFilePath; if ( std::filesystem::is_regular_file( fsPath ) == false ) { lua_pushboolean( pLuaState, 0 ); return 1; } lua_pushboolean( pLuaState, std::filesystem::exists( fsPath ) ? 1 : 0 ); return 1; } int iberbar::LuaCppFunction_Ref_RefCount( lua_State* pLuaState ) { int nTop = lua_gettop( pLuaState ); iberbar_LuaCheckArguments( pLuaState, nTop, 1 ); CRef* pRef = lua_tocppobject( pLuaState, 1, CRef ); if ( pRef == nullptr ) { lua_pushinteger( pLuaState, 1 ); return 1; } lua_pushinteger( pLuaState, (lua_Integer)pRef->Refcount() ); return 1; } int iberbar::LuaCppFunction_Ref___tostring( lua_State* pLuaState ) { int nTop = lua_gettop( pLuaState ); iberbar_LuaCheckArguments( pLuaState, nTop, 1 ); CRef* pRef = lua_tocppobject( pLuaState, 1, CRef ); if ( pRef == nullptr ) { lua_pushnil( pLuaState ); return 1; } lua_pushstring( pLuaState, pRef->ToString().c_str() ); //lua_pushstring( pLuaState, "" ); return 1; }
#pragma once #include "role.hpp" #include "db/message.hpp" #include "db/connector.hpp" #include "scene/log.hpp" #include "scene/common_logic.hpp" #include "scene/item_logic.hpp" #include "scene/shop.hpp" #include "scene/xinshou.hpp" #include "scene/event.hpp" #include "scene/quest.hpp" #include "scene/player/role_logic.hpp" #include "scene/relation_logic.hpp" #include "scene/activity/activity_logic.hpp" #include "scene/activity/activity_mgr.hpp" #include "scene/db_log.hpp" //#include "scene/yunying/sdk.hpp" //#include "scene/yunying/bi.hpp" #include "scene/recharge.hpp" #include "scene/mail/mail_logic.hpp" #include "scene/behavior_tree.hpp" #include "scene/condevent.hpp" #include "scene/mirror.hpp" #include "scene/chat.hpp" #include "scene/dbcache/dbcache.hpp" #include "scene/common_resource/common_resource.hpp" #include "scene/item.hpp" #include "utils/state_machine.hpp" #include "utils/server_process_mgr.hpp" #include "utils/dirty_word_filter.hpp" #include "utils/service_thread.hpp" #include "utils/json2pb.hpp" #include "utils/string_utils.hpp" #include "utils/game_def.hpp" #include "utils/instance_counter.hpp" #include "utils/assert.hpp" #include "utils/time_utils.hpp" #include "utils/random_utils.hpp" #include "utils/client_version.hpp" #include "config/utils.hpp" #include "config/player_ptts.hpp" #include "config/drop_ptts.hpp" #include "config/shop_ptts.hpp" #include "config/item_ptts.hpp" #include "config/mail_ptts.hpp" #include "config/resource_ptts.hpp" #include "config/chat_ptts.hpp" #include "config/options_ptts.hpp" #include "config/behavior_tree_ptts.hpp" #include "config/relation_ptts.hpp" #include "config/activity_ptts.hpp" #include "config/title_ptts.hpp" #include "net/stream.hpp" #include "net/server.hpp" #include "proto/cs_login.pb.h" #include "proto/cs_base.pb.h" #include "proto/cs_shop.pb.h" #include "proto/cs_chat.pb.h" #include "proto/cs_relation.pb.h" #include "proto/cs_gm.pb.h" #include "proto/cs_notice.pb.h" #include "proto/cs_mail.pb.h" #include "proto/cs_room.pb.h" #include "proto/cs_quest.pb.h" #include "proto/cs_item.pb.h" #include "proto/cs_player.pb.h" #include "proto/cs_activity.pb.h" #include "proto/cs_title.pb.h" #include "proto/cs_xinshou.pb.h" #include "proto/cs_recharge.pb.h" #include "proto/cs_yunying.pb.h" #include "proto/ss_chat.pb.h" #include "proto/ss_common_resource.pb.h" #include "proto/data_notice.pb.h" #include "proto/data_mail.pb.h" #include "proto/data_player.pb.h" #include "proto/processor.hpp" #include <string> #include <memory> #include <functional> #include <boost/any.hpp> #include <boost/core/noncopyable.hpp> using namespace std; using namespace chrono; namespace pcs = proto::cs; namespace pd = proto::data; namespace ps = proto::ss; namespace nora { namespace scene { using mirror_mgr = server_process_mgr<mirror>; using chat_mgr = server_process_mgr<chat>; using common_resource_mgr = server_process_mgr<common_resource>; template <typename T> class player : public enable_shared_from_this<player<T>>, public proto::processor<player<T>, pcs::base>, private boost::noncopyable, private instance_countee { public: player(const shared_ptr<service_thread>& st, const shared_ptr<net::server<T>>& nsv, const shared_ptr<T>& conn, const shared_ptr<db::connector>& gamedb_notice, bool mirror_role, bool online) : instance_countee(ICT_PLAYER), st_(st), nsv_(nsv), conn_(conn), gamedb_notice_(gamedb_notice), mirror_role_(mirror_role), online_(online) { if (conn_) { ip_ = conn_->remote_ip(); } } void init() { sm_ = make_shared<state_machine<player<T>>>(this->shared_from_this(), st_); sm_->start(state_init::instance()); const auto& ptt = PTTS_GET(behavior_tree_root, pc::BTRT_TICK); bt_ = make_shared<behavior_tree<player<T>>>(this, st_, ptt.node()); this->set_proto_min_frequency(milliseconds(100)); this->add_ignore_min_frequency(pcs::c2s_role_get_info_req::descriptor()); } static void static_init() { //register some handler player::register_proto_handler(pcs::c2s_login_req::descriptor(), &player::process_login_req); player::register_proto_handler(pcs::c2s_create_role_req::descriptor(), &player::process_create_role_req); player::register_proto_handler(pcs::c2s_ping_req::descriptor(), &player::process_ping_req); player::register_proto_handler(pcs::c2s_mail_fetch_req::descriptor(), &player::process_mail_fetch_req); player::register_proto_handler(pcs::c2s_mail_delete_req::descriptor(), &player::process_mail_delete_req); // ai_action //player::ai_action_handlers_[pd::PAT_ARENA_JOIN] = &player::ai_action_join_arena; // ai_condition //player::ai_condition_handlers_[pd::PCT_MANSION_CREATED] = &player::ai_condition_mansion_created; } const string& username() const { return username_; } role *get_role() { return role_.get(); } void ai_stop() { bt_->stop(); } uint64_t gid() const { if (role_) { return role_->gid(); } else { return 0; } } uint32_t level() const { ASSERT(role_); return role_->level(); } pd::gender gender() const { ASSERT(role_); return role_->gender(); } bool online() const { return online_; } const string& ip() const { return ip_; } bool mirror_role() const { return mirror_role_; } bool ai_is_active() const { return bt_->running(); } void ai_set_active(bool active) { if (bt_->running() == active) { return; } if (active) { bt_->run(); } else { bt_->stop(); } } void set_next_frequency(const system_clock::duration& du) { bt_->set_next_frequency(du); } void set_cur_root(uint32_t children_node) { const auto& ptt = PTTS_GET(behavior_tree_root, pc::BTRT_TICK); if (ptt.node() != children_node) { bt_->rebuild_root_node(ptt.node(), children_node); } } void add_async_call_count() { async_call_count_ += 1; } void dec_async_call_count() { ASSERT(async_call_count_.load() > 0); async_call_count_ -= 1; } bool has_async_call() const { return async_call_count_.load() > 0; } void async_call(const function<void()>& func) { add_async_call_count(); st_->async_call( [this, self = this->shared_from_this(), func = func] { this->dec_async_call_count(); func(); update_role_db(); }); } const shared_ptr<T>& conn() const { return conn_; } void send_to_client(pcs::base& msg, bool no_lag = false) { auto ptt = PTTS_GET_COPY(options, 1); if (ptt.scene_info().lag() > 0 && !no_lag) { ADD_TIMER( st_, ([this, self = this->shared_from_this(), msg] (auto canceled, const auto& timer) mutable { if (!canceled) { this->send_to_client_inner(msg); } }), milliseconds(ptt.scene_info().lag())); } else { async_call( [this, self = this->shared_from_this(), msg] () mutable { this->send_to_client_inner(msg); }); } } void send_to_client_inner(pcs::base& msg) { ASSERT(st_->check_in_thread()); if (!conn_) { return; } msg.set_time(system_clock::to_time_t(system_clock::now())); SPLAYER_TLOG << *this << " send " << msg.DebugString(); ASSERT(send_msg_cb_); const Reflection *reflection = msg.GetReflection(); vector<const FieldDescriptor *> fields; reflection->ListFields(msg, &fields); ASSERT(fields.size() == 2); const Descriptor *desc = fields.back()->message_type(); send_msg_cb_(desc, msg.ByteSize()); auto ss = make_shared<net::sendstream>(); msg.SerializeToOstream(ss.get()); nsv_->send(conn_, ss); } void set_mirror_role_data(uint64_t gid, const pd::role& data) { mirror_role_data_ = make_unique<pd::role>(data); mirror_role_data_->set_gid(gid); } void login(const string& username, bool check_sdk = true) { async_call( [this, self = this->shared_from_this(), username, check_sdk] { event_login event(username, check_sdk); sm_->on_event(&event); }); } void create_role(const pd::role& data) { ASSERT(st_->check_in_thread()); async_call( [this, self = this->shared_from_this(), data] { auto msg = dbcache::gen_create_role_req(username_, data); dbcache::instance().send_to_dbcached(msg); event_client_create_role event(username_); sm_->on_event(&event); }); } void quit() { async_call( [this, self = this->shared_from_this()] { event_logout event; sm_->on_event(&event); }); } bool stop_playing() { auto pl = this->shared_from_this(); if (!stop_playing_cb_(pl)) { SPLAYER_DLOG << *this << " " << *this << " reset timeout"; set_quiting_playing(); sm_->reset_timeout(1s); return false; } if (online()) { if (role_->marriage_married()) { ASSERT(marriage_notice_spouse_logout_func_); marriage_notice_spouse_logout_func_(role_->gid(), role_->marriage_spouse()); } role_->logout(); update_role_db(); stop_resource_grow_timer(); /*bi::instance().logout(username(), yci_, ip_, role_->gid(), role_->last_login_time(), pd::ce_origin(), role_->level(), role_->get_resource(pd::resource_type::EXP), role_->get_resource(pd::resource_type::DIAMOND), role_->get_resource(pd::resource_type::GOLD), role_->calc_max_zhanli(), role_->name(), pd::gender_Name(role_->gender()), role_->get_resource(pd::resource_type::VIP_EXP), role_->vip_level());*/ db_log::instance().log_logout(*role_, ip_); } return true; } void quit_timeout() { ASSERT(st_->check_in_thread()); ai_stop(); stop_resource_grow_timer(); stop_mirror_timers(); sm_->stop(); fetch_room_list_call_funcs_.clear(); fetch_room_info_call_funcs_.clear(); if (quit_cb_) { quit_cb_(this->shared_from_this()); } if (role_) { role_.reset(); } if (nsv_ && conn_) { nsv_->disconnect(conn_); conn_.reset(); } } void handle_finished_db_msg(const shared_ptr<db::message>& msg) { ASSERT(st_->check_in_thread()); event_db_rsp event(msg); sm_->on_event(&event); } void process_msg(const shared_ptr<net::recvstream>& msg) { async_call( [this, self = this->shared_from_this(), msg] { pcs::base cs_msg; if (cs_msg.ParseFromIstream(msg.get())) { SPLAYER_TLOG << *this << " recv " << cs_msg.DebugString(); this->process(this, &cs_msg); #ifndef _DEBUG if (this->check_state_playing() && !quiting_playing_) { this->sm_->reset_timeout(5min); } #endif } else { SPLAYER_DLOG << *this << " parse msg failed"; } }); } void process_msg(const pcs::base& msg) { async_call( [this, self = this->shared_from_this(), msg] { this->process(this, &msg); }); } void process_login_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_init()) { return; } const auto& req = msg->GetExtension(pcs::c2s_login_req::clr); auto result = pd::OK; if (req.client_version_size() != 3) { result = pd::CLIENT_VERSION_INVAILD; } else { auto ptt = PTTS_GET_COPY(options, 1); vector<uint32_t> minimum_version_vec; result = parse_str_version_to_vector(ptt.login_info().client_version(), minimum_version_vec); if (result == pd::OK) { vector<uint32_t> client_version_vec; for (auto small_version : req.client_version()) { client_version_vec.push_back(small_version); } if (compare_client_version(client_version_vec, minimum_version_vec) < 0) { result = pd::CLIENT_VERSION_TOO_OLD; } } } if (result != pd::OK) { pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(req.username()); rsp->set_result(result); send_to_client(rsp_msg); return; } login(req.username() + "_" + to_string(req.server_id())); ai_.robot_role_ = req.robot_role(); ai_.behavior_children_node_ = req.tree_children_node(); yci_ = req.client_info(); origin_username_ = req.username(); server_id_ = req.server_id(); } void set_username(const string& username) { username_ = username; } void process_create_role_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_client_create_role()) { return; } const auto& req = msg->GetExtension(pcs::c2s_create_role_req::ccrr); auto result = check_name(req.name(), forbid_names(), !req.robot()); if (result != pd::OK) { SPLAYER_DLOG << " invalid name " << pd::result_Name(result); return; } auto options_ptt = PTTS_GET_COPY(options, 1); auto today = refresh_day(); auto now = system_clock::to_time_t(system_clock::now()); pd::role data; pc::create_role *ptt = nullptr; if (ai_.robot_role_ && options_ptt.scene_info().allow_robot()) { ptt = req.gender() == pd::FEMALE ? &PTTS_GET(create_role, 3) : &PTTS_GET(create_role, 4); } else if (options_ptt.scene_info().testin()) { ptt = &PTTS_GET(create_role, 5); } else { ptt = req.gender() == pd::FEMALE ? &PTTS_GET(create_role, 1) : &PTTS_GET(create_role, 2); } ASSERT(ptt); data.set_gid(gid::instance().new_gid(gid_type::ROLE)); auto *role_data = data.mutable_data(); if (req.has_channel_id()) { role_data->set_channel_id(req.channel_id()); } role_data->set_name(req.name()); role_data->set_username(username_); role_data->set_gender(req.gender() == pd::FEMALE ? pd::FEMALE : pd::MALE); role_data->set_icon(0); for (auto i = 0; i < PLAYER_CUSTOM_ICON_COUNT; ++i) { role_data->add_custom_icons(""); } if (ptt->has_level()) { role_data->set_level(ptt->level()); } role_data->set_last_levelup_time(now); auto *role_other_data = data.mutable_other_data(); role_other_data->mutable_league()->set_leave_league_time(0); role_other_data->mutable_league()->set_latest_refresh_day(today); role r(data.gid(), yci_, ip_); r.username_func_ = [this] { return username(); }; for (const auto& i : ptt->resources()) { r.set_resource(i.type(), i.value()); } r.reset_resources(); const auto& resource_ptts = PTTS_GET_ALL(resource); for (const auto& i : resource_ptts) { if (i.second.grow_minutes() > 0) { r.set_resource_grow_time(i.second.type(), now); } } r.serialize_resources(data.mutable_resources()); pd::spine_item_array col; *col.mutable_items() = ptt->spine_collection(); for (auto i = 0u; i < SPINE_SELECTION_COUNT; ++i) { *spine->add_selections() = spine_check_and_fix_sel(req.spine_selection(), col); } spine->set_cur_selection(0); *spine->mutable_collection() = ptt->spine_collection(); r.parse_spine(&data.spine()); set<uint32_t> slot; vector<uint32_t> skills; for (auto i : ptt->grids()) { const auto& actor_ptt = PTTS_GET(actor, i.actor()); if (actor_ptt.type() == pd::actor::ZHU) { for(auto j : actor_ptt.skill()) { const auto& skill_ptt = PTTS_GET(skill, j); if (skill_ptt.has_slot() && slot.count(skill_ptt.slot()) <= 0) { slot.insert(skill_ptt.slot()); skills.push_back(j); } } break; } } auto *battle = data.mutable_battle(); for (auto i = 0; i < 4; ++i) { set<uint32_t> skill_slots; auto *formation = battle->add_formations(); *formation->mutable_grids()->mutable_grids() = ptt->grids(); for (auto j : skills) { const auto& skill_ptt = PTTS_GET(skill, j); if (skill_ptt.has_slot() && skill_slots.count(skill_ptt.slot()) <= 0) { skill_slots.insert(skill_ptt.slot()); formation->add_skills(j); } } } r.parse_battle(&data.battle()); for (const auto& i : ptt->huanzhuang_collection()) { r.huanzhuang_add_collection(i.part(), i.pttid()); } pd::huanzhuang_item_id_array selection; *selection.mutable_items() = ptt->huanzhuang_selection(); for (auto i = 0u; i < HUANZHUANG_SELECTION_COUNT; ++i) { r.huanzhuang_update_selection(i, selection); } r.huanzhuang_set_cur_selection(0); r.serialize_huanzhuang(data.mutable_huanzhuang()); for (auto i : ptt->items()) { r.add_item(i.pttid(), i.count(), true); } r.serialize_items(data.mutable_items()); for (const auto& i : ptt->equipments()) { for (auto j = 0; j < i.count(); ++j) { r.add_equipment(i.pttid(), i.quality(), true); } } r.serialize_equipments(data.mutable_equipments()); r.serialize_jades(data.mutable_jades()); for (auto i : ptt->titles()) { r.add_title(i); } r.serialize_titles(data.mutable_titles()); for (auto i : ptt->quests()) { r.quest_accept(i); } if (today <= server_open_day_func_() + 6) { const auto& al_ptt = PTTS_GET(activity_logic, 1); const auto& alr_ptt = PTTS_GET(activity_leiji_recharge, al_ptt.activity_start().leiji_recharge()); for (auto i : alr_ptt.quests()) { r.quest_accept(i.auto_quest()); r.quest_accept(i.event_quest()); } const auto& alc_ptt = PTTS_GET(activity_leiji_consume, al_ptt.activity_start().leiji_consume()); for (auto i : alc_ptt.quests()) { r.quest_accept(i.auto_quest()); r.quest_accept(i.event_quest()); } const auto& dyr_ptt = PTTS_GET(activity_daiyanren, 1); for (auto i : dyr_ptt.fuli_quests()) { r.quest_accept(i); } for (auto i : dyr_ptt.duihuan_quests()) { r.quest_accept(i); } } else { r.activity_daiyanren_set_finished(); } for (auto i : ptt->mansion_cook_recipes()) { r.mansion_cook_add_recipe(i); } r.serialize_mansion_data(data.mutable_mansion_data()); r.guanpin_update_battle_seed(); r.serialize_guanpin_data(data.mutable_guanpin_data()); r.serialize_records(data.mutable_records()); pd::event_res event_res; r.refresh_everyday_quests(event_res); r.accept_achievement_quest(); r.accept_ui_quest(); r.serialize_quests(data.mutable_quests()); auto m = mail_new_mail(data.gid(), CREATE_ROLE_FIRST_MAIL_PTTID, pd::dynamic_data(), pd::event_array()); r.add_mail(m); r.serialize_mails(data.mutable_mails()); create_role(data); if (!req.robot()) { ADD_TIMER( st_, ([this, self = this->shared_from_this(), data] (auto canceled, const auto& timer) { if (!canceled) { auto username = split_string(username_, '_'); ASSERT(username.size() == 2); ps::base fanli_msg; auto *fanli = fanli_msg.MutableExtension(ps::s2cr_lock_fanli_req::slfr); fanli->set_username(username[0]); common_resource_mgr::instance().random_send_msg(fanli_msg); ps::base come_back_msg; auto *come_back = come_back_msg.MutableExtension(ps::s2cr_lock_come_back_req::slcbr); come_back->set_username(username[0]); common_resource_mgr::instance().random_send_msg(come_back_msg); } }), 1s); } } void process_ping_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_playing() && !check_state_create_role() && !check_state_client_create_role()) { return; } pcs::base rsp_msg; rsp_msg.MutableExtension(pcs::s2c_ping_rsp::spr); send_to_client(rsp_msg); } //void process_challenge_adventure(const pcs::base *msg) { //} /*void process_shop_check_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_playing()) { return; } const auto& req = msg->GetExtension(pcs::c2s_shop_check_req::cscr); pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_shop_check_rsp::sscr); do { if (!PTTS_HAS(shop, req.pttid())) { rsp->set_result(pd::SHOP_NO_SUCH_SHOP); break; } auto ptt = PTTS_GET_COPY(shop, req.pttid()); rsp->set_pttid(ptt.id()); if (ptt.version() != req.version()) { rsp->set_result(pd::SHOP_NEED_UPDATE); *rsp->mutable_shop() = ptt; break; } rsp->set_result(pd::OK); } while (false); send_to_client(rsp_msg); } void process_shop_buy_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_playing()) { return; } const auto& req = msg->GetExtension(pcs::c2s_shop_buy_req::csbr); if (req.buy_goods_size() <= 0) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_shop_buy_rsp::ssbr); bool bought = false; pd::event_res event_res; bool send_bi = false; for (const auto& i : req.buy_goods()) { for (auto j = 0u; j < i.count(); ++j) { auto result = shop_check_buy(i.shop(), i.good_id(), *role_); rsp->set_result(result); if (result != pd::OK) { break; } if (j + 1 >= i.count()) { send_bi = true; } event_res = shop_buy(i.shop(), i.good_id(), *role_, &event_res, send_bi); bought = true; } if (bought) { pd::yunying_bi_info bi; auto ptt = PTTS_GET_COPY(shop, i.shop()); for (const auto& j : ptt.goods()) { if (j.id() == i.good_id()) { bi.set_is_discount(j.discount()); bi.set_is_promotion(0); bi::instance().shop_stream(username(), yci_, ip_, role_->gid(), role_->league_gid(), bi, j.type(), i.shop(), i.good_id(), event_res); } } } } if (bought) { *rsp->mutable_res() = event_res; db_log::instance().log_shop_buy(event_res, *role_); } send_to_client(rsp_msg); } void process_mys_shop_refresh_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_playing()) { return; } const auto& req = msg->GetExtension(pcs::c2s_mys_shop_refresh_req::cmsrr); pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_mys_shop_refresh_rsp::smsrr); rsp->set_pttid(req.pttid()); rsp->set_free(req.free()); pd::event_res event_res; auto result = pd::OK; if (req.free()) { result = mys_shop_free_refresh_goods(req.pttid(), &event_res, *role_); } else { result = mys_shop_refresh_goods(req.pttid(), &event_res, *role_); } rsp->set_result(result); if (result == pd::OK) { *rsp->mutable_event_res() = event_res; role_->serialize_mys_shop(req.pttid(), rsp->mutable_mys_shop()); db_log::instance().log_mys_shop_refresh(req.pttid(), event_res, rsp->mys_shop(), *role_); } send_to_client(rsp_msg); } void process_mys_shop_buy_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_playing()) { return; } const auto& req = msg->GetExtension(pcs::c2s_mys_shop_buy_req::cmsbr); pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_mys_shop_buy_rsp::smsbr); rsp->set_pttid(req.pttid()); auto result = mys_shop_check_buy(req.pttid(), req.good_id(), *role_); rsp->set_good_id(req.good_id()); rsp->set_result(result); if (result == pd::OK) { *rsp->mutable_event_res() = mys_shop_buy(req.pttid(), req.good_id(), *role_); db_log::instance().log_mys_shop_buy(req.pttid(), req.good_id(), &rsp->event_res(), *role_); } send_to_client(rsp_msg); } void mirror_broad_system_chat(uint32_t system_chat) { auto delay = rand() % 60 + 10; add_mirror_timer(delay, [this, self = this->shared_from_this(), system_chat] { pd::role_mirror_event event; event.set_gid(this->gid()); event.set_type(pd::RMET_BROADCAST); event.set_system_chat(system_chat); this->send_mirror_role_event_msg(event); }); } */ /* void process_chat_req(const pcs::base *msg) { ASSERT(st_->check_in_thread()); if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_chat_rsp::scr); rsp->set_result(pd::OK); do { if (role_->gag_until_time() >= system_clock::to_time_t(system_clock::now())) { rsp->set_result(pd::CHAT_GAG); break; } const auto& req = msg->GetExtension(pcs::c2s_chat_req::ccr); auto result = check_content(req.content(), false); if (result != pd::OK) { rsp->set_result(result); break; } bool all_space = true; for (auto i : req.content()) { if (!isspace(i)) { all_space = false; break; } } if (all_space) { rsp->set_result(pd::CHAT_CONTENT_ALL_SPACE); break; } auto content = req.content(); auto options_ptt = PTTS_GET_COPY(options, 1u); if (options_ptt.scene_info().dev_gm()) { if (try_exec_chat_gm(content)) { return; } } const auto& ptt = PTTS_GET(chat, req.type()); result = condition_check(ptt.conditions(), *role_); if (ptt.has_send_cd() && role_->get_last_chat_time(req.type()) > 0) { if (system_clock::to_time_t(system_clock::now()) <= role_->get_last_chat_time(req.type()) + ptt.send_cd()) { result = pd::CHAT_IN_CD; } } if (result == pd::OK) { role_->update_chat_data(req.type()); pd::ce_env ce; ce.set_origin(pd::CO_CHAT); *rsp->mutable_event_res() = event_process(ptt._events(), *role_, ce); } else { rsp->set_result(result); break; } content = dirty_word_filter::instance().fix(content); auto voice = req.voice(); pd::role_info ri; role_->serialize(ri.mutable_simple_info()); auto time = system_clock::to_time_t(system_clock::now()); switch (req.type()) { case pd::CT_PRIVATE: { if (!req.has_to()) { rsp->set_result(pd::CHAT_NEED_TO); break; } if (role_->relation_in_blacklist(req.to())) { rsp->set_result(pd::CHAT_TO_IN_BLACKLIST); break; } ASSERT(private_chat_func_); private_chat_func_(ri, time, req.to(), content, voice); send_chat(pd::CT_PRIVATE, ri, time, content, voice, 0, req.to()); role_->on_event(ECE_PRIVATE_CHAT, {}); break; } case pd::CT_LEAGUE: { ASSERT(league_chat_func_); league_chat_func_(ri, time, content, voice); break; } case pd::CT_WORLD: case pd::CT_WORLD_LABA: { ASSERT(world_chat_func_); world_chat_func_(req.type(), ri, time, content, voice); role_->on_event(ECE_WORLD_CHAT, {}); break; } case pd::CT_BANQUET: { if (!req.has_to()) { rsp->set_result(pd::CHAT_NEED_TO); break; } if (mansion_check_enter_banquet_time() != pd::OK) { rsp->set_result(pd::CHAT_NOT_BANQUET_TIME); break; } ASSERT(banquet_chat_func_); banquet_chat_func_(ri, time, req.to(), content, voice); break; } case pd::CT_ROOM: { if (!req.has_to()) { rsp->set_result(pd::CHAT_NEED_TO); break; } room_mgr::instance().room_chat(ri, time, req.to(), content, voice); break; } case pd::CT_CROSS_WORLD: { ps::base msg; auto *req = msg.MutableExtension(ps::sch_cross_world_chat::scwc); *req->mutable_from() = ri; req->set_time(time); req->set_from_server(options_ptt.scene_info().server_id()); req->set_content(content); *req->mutable_voice() = voice; chat_mgr::instance().broadcast_msg(msg); break; } default: break; } db_log::instance().log_chat(req.content(), rsp->event_res(), *role_); } while (false); send_to_client(rsp_msg); } */ /* void add_resource_grow_timer(pd::resource_type type) { if (!check_state_fetch_data() && !check_state_playing()) { return; } const auto& ptt = PTTS_GET(resource, type); ASSERT(ptt.grow_minutes() > 0); resource_grow_timer_[type] = ADD_TIMER( st_, ([this, self = this->shared_from_this(), type = ptt.type()] (auto canceled, const auto& timer) { auto it = resource_grow_timer_.find(type); if (it == resource_grow_timer_.end() && it->second == timer) { resource_grow_timer_.erase(type); } if (!canceled) { if (!this->check_state_fetch_data() && !this->check_state_playing()) { return; } auto now = system_clock::to_time_t(system_clock::now()); auto old_value = role_->get_resource(type); role_->grow_resource(type); this->add_resource_grow_timer(type); this->update_role_db(); auto new_value = role_->get_resource(type); if (old_value != new_value && this->check_state_playing()) { pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_update_resource::srur); notice->set_type(type); notice->set_value(new_value); notice->set_time(now); this->send_to_client(msg); } } }), system_clock::from_time_t(role_->resource_grow_time(type)) + minutes(ptt.grow_minutes())); } void stop_resource_grow_timer() { for (auto& i : resource_grow_timer_) { i.second->cancel(); i.second.reset(); } resource_grow_timer_.clear(); } void stop_mirror_timers() { for (auto i : mirror_timers_) { i->cancel(); i.reset(); } mirror_timers_.clear(); } void add_rand_quit_timer() { rand_quit_timer_ = ADD_TIMER( st_, ([this, self = this->shared_from_this()] (auto canceled, const auto& timer) { if (rand_quit_timer_ == timer) { rand_quit_timer_.reset(); } if (!canceled && this->check_state_playing()) { if (rand() % 5 == 0) { this->quit(); } else { this->add_rand_quit_timer(); } } }), 5s); } void remove_rand_quit_timer() { ASSERT(st_->check_in_thread()); if (rand_quit_timer_) { rand_quit_timer_->cancel(); rand_quit_timer_.reset(); } } */ void create_role_done(pd::result result) { async_call( [this, self = this->shared_from_this(), result] { SPLAYER_DLOG << *this << " create role done " << pd::result_Name(result); event_create_role_done event(result); sm_->on_event(&event); }); } void find_role_done(pd::result result, const pd::role& role) { async_call( [this, self = this->shared_from_this(), result, role] { SPLAYER_DLOG << *this << " find role done " << pd::result_Name(result); event_find_role_done event(result, role); sm_->on_event(&event); }); } void find_role_by_gid_done(uint64_t gid, pd::result result, const string& username, const pd::role& role) { async_call( [this, self = this->shared_from_this(), gid, result, username, role] { SPLAYER_DLOG << *this << " find role by gid done " << gid << " " << pd::result_Name(result); event_find_role_by_gid_done event(result, gid, username, role); sm_->on_event(&event); }); } void login_by_gid(uint64_t gid) { async_call( [this, self = this->shared_from_this(), gid] { SPLAYER_DLOG << *this << " login by gid " << gid; event_login_by_gid event(gid); sm_->on_event(&event); }); } void send_info_to(uint64_t to, bool simple) { async_call( [this, self = this->shared_from_this(), to, simple] { SPLAYER_DLOG << *this << " send info to " << to; ASSERT(check_state_playing()); pd::role_info data; role_->serialize_role_info_for_client(&data, simple); send_info_func_(to, data, simple); }); } void get_role_info_by_str_to(uint64_t to, const string& str, const queue<uint64_t>& gids, const pd::role_info_array& data) { async_call( [this, self = this->shared_from_this(), to, str, gids = gids, data = data] () mutable { SPLAYER_DLOG << *this << " get role info by str to " << to; ASSERT(check_state_playing()); ASSERT(gids.front() == role_->gid()); gids.pop(); role_->serialize_role_info_for_client(data.add_infos(), true); get_role_info_by_str_func_(to, str, gids, data); }); } void send_info(const pd::role_info& data, bool simple) { async_call( [this, self = this->shared_from_this(), data, simple] { SPLAYER_DLOG << *this << " send info"; if (!check_state_playing()) { return; } pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_role_get_info_rsp::srgir); rsp->set_result(pd::OK); rsp->set_gid(data.simple_info().gid()); rsp->set_simple(simple); *rsp->mutable_info() = data; send_to_client(msg); }); } void get_role_info_by_str_done(const string& str, const pd::role_info_array& data) { async_call( [this, self = this->shared_from_this(), str, data] { SPLAYER_DLOG << *this << " get role info by str done"; if (!check_state_playing()) { return; } pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_role_get_info_by_str_rsp::srgibsr); rsp->set_str(str); rsp->set_result(pd::OK); *rsp->mutable_infos() = data; send_to_client(msg); }); } friend ostream& operator<<(ostream& os, const player& pl) { ASSERT(pl.st_->check_in_thread()); auto username = pl.username().empty() ? "noname" : pl.username(); return os << username << " " << pl.gid(); } // events class event_db_rsp : public event_base { public: event_db_rsp(const shared_ptr<db::message>& db_msg) : db_msg_(db_msg) {} shared_ptr<db::message> db_msg_; friend ostream& operator<<(ostream& os, const event_db_rsp& e) { return os << "<event:db_rsp>" << *e.db_msg_; } }; class event_create_role_done : public event_base { public: event_create_role_done(pd::result result) : result_(result) {} pd::result result_; friend ostream& operator<<(ostream& os, const event_create_role_done& e) { return os << "<event:create_role_done> " << pd::result_Name(e.result_); } }; class event_check_login_done : public event_base { public: event_check_login_done(pd::result result, const string& username) : result_(result), username_(username) {} pd::result result_; const string username_; friend ostream& operator<<(ostream& os, const event_check_login_done& e) { return os << "<event:check_login_done> " << pd::result_Name(e.result_); } }; class event_find_role_done : public event_base { public: event_find_role_done(pd::result result, const pd::role& role) : result_(result), role_(role) {} pd::result result_; pd::role role_; friend ostream& operator<<(ostream& os, const event_find_role_done& e) { return os << "<event:find_role_done> " << pd::result_Name(e.result_); } }; class event_find_role_by_gid_done : public event_base { public: event_find_role_by_gid_done(pd::result result, uint64_t gid, const string& username, const pd::role& role) : result_(result), gid_(gid), username_(username), role_(role) {} pd::result result_; uint64_t gid_; string username_; pd::role role_; friend ostream& operator<<(ostream& os, const event_find_role_by_gid_done& e) { return os << "<event:find_role_by_gid_done> " << pd::result_Name(e.result_); } }; class event_net_rsp : public event_base { public: event_net_rsp(const string& rolename) : rolename_(rolename) { } const string rolename_; friend ostream& operator<<(ostream& os, const event_net_rsp& e) { return os << "<event:net_rsp><role:" << e.rolename_ << ">"; } }; class event_client_create_role : public event_base { public: event_client_create_role(const string& username) : username_(username) { } const string username_; friend ostream& operator<<(ostream& os, const event_client_create_role& e) { return os << "<event:client_create_role><role:" << e.username_ << ">"; } }; class event_fetch_data_done : public event_base { friend ostream& operator<<(ostream& os, const event_fetch_data_done& e) { return os << "<event:fetch_data_done>"; } }; class event_logout : public event_base { friend ostream& operator<<(ostream& os, const event_logout& e) { return os << "<event:logout>"; } }; class event_login : public event_base { public: event_login(const string& username, bool check_sdk) : username_(username), check_sdk_(check_sdk) { } const string username_; bool check_sdk_ = true; friend ostream& operator<<(ostream& os, const event_login& el) { return os << "<event:login>"; } }; class event_login_by_gid : public event_base { public: event_login_by_gid(uint64_t gid) : gid_(gid) { } uint64_t gid_; friend ostream& operator<<(ostream& os, const event_login_by_gid& elbg) { return os << "<event:login_by_gid " << elbg.gid_ << ">"; } }; // states class state_init : public state_base<player> { public: static state_init *instance() { static state_init inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) override { instance_counter::instance().add(ICT_INIT_PLAYER); } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) override { if (auto *e = dynamic_cast<event_login *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; auto options_ptt = PTTS_GET_COPY(options, 1); if (!options_ptt.scene_info().sdk_check_login() || !e->check_sdk_) { pl->username_ = e->username_; ASSERT(pl->login_cb_); auto result = pl->login_cb_(pl); if (result != pd::OK) { pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(pl->username_); rsp->set_result(result); pl->send_to_client(msg); return state_quit::instance(); } auto msg = dbcache::gen_find_role_req(pl->username_, 0, 0); dbcache::instance().send_to_dbcached(msg); return state_find_role::instance(); } else { sdk::instance().check_login(pl->origin_username_, [pl] (auto result, auto username) { pl->async_call( [pl, result, username] { if (!pl->check_state_check_login()) { return; } event_check_login_done event(result, username + "_" + to_string(pl->server_id_)); pl->sm_->on_event(&event); }); }); return state_check_login::instance(); } } else if (auto *e = dynamic_cast<event_login_by_gid *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; auto msg = dbcache::gen_find_role_by_gid_req(e->gid_); dbcache::instance().send_to_dbcached(msg); return state_find_role::instance(); } else if (auto *e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_quit::instance(); } return nullptr; } state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) override { SPLAYER_DLOG << *pl << " " << *this << " timeout"; return state_quit::instance(); } void on_out(const shared_ptr<player<T>>& pl) override { SPLAYER_DLOG << *pl << " " << *this << " out"; instance_counter::instance().dec(ICT_INIT_PLAYER); } system_clock::duration timeout() override { return 5s; } friend ostream& operator<<(ostream& os, const state_init& s) { return os << "<state:init>"; } }; class state_check_login : public state_base<player> { public: static state_check_login *instance() { static state_check_login inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; instance_counter::instance().add(ICT_CHECK_LOGIN_PLAYER); } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { if (auto *e = dynamic_cast<event_check_login_done *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; if (e->result_ == pd::OK) { pl->username_ = e->username_; ASSERT(pl->login_cb_); pd::result result = pl->login_cb_(pl); if (result != pd::OK) { pl->login_cb_(pl); pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(e->username_); rsp->set_result(result); pl->send_to_client(msg); return state_quit::instance(); } auto msg = dbcache::gen_find_role_req(e->username_, 0, 0); dbcache::instance().send_to_dbcached(msg); return state_find_role::instance(); } else { pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(pl->username_); rsp->set_result(e->result_); pl->send_to_client(msg); return state_quit::instance(); } } else if (auto *e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_quit::instance(); } return nullptr; } state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " timeout"; return player::state_quit::instance(); } void on_out(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " out"; instance_counter::instance().dec(ICT_CHECK_LOGIN_PLAYER); } system_clock::duration timeout() override { return 5s; } friend ostream& operator<<(ostream& os, const state_check_login& s) { return os << "<state:check_login>"; } }; class state_find_role : public state_base<player> { public: static state_find_role *instance() { static state_find_role inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; instance_counter::instance().add(ICT_FIND_ROLE_PLAYER); } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { if (auto *e = dynamic_cast<event_find_role_done *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; if (e->result_ == pd::NOT_FOUND) { pl->login_no_role(); return player::state_client_create_role::instance(); } else { ASSERT(e->result_ == pd::OK); if (!pl->init_role(e->role_)) { return player::state_quit::instance(); } else { return player::state_fetch_data::instance(); } } } else if (auto *e = dynamic_cast<event_find_role_by_gid_done *>(event)) { if (e->result_ == pd::NOT_FOUND) { return player::state_quit::instance(); } else { ASSERT(e->result_ == pd::OK); pl->username_ = e->username_; ASSERT(pl->init_role(e->role_)); return player::state_fetch_data::instance(); } } else if (auto *e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_quit::instance(); } return nullptr; } state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " timeout"; return player::state_quit::instance(); } void on_out(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " out"; instance_counter::instance().dec(ICT_FIND_ROLE_PLAYER); } system_clock::duration timeout() override { return 5s; } friend ostream& operator<<(ostream& os, const state_find_role& s) { return os << "<state:find_role>"; } }; class state_fetch_data : public state_base<player> { public: static state_fetch_data *instance() { static state_fetch_data inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; instance_counter::instance().add(ICT_FETCH_DATA_PLAYER); pl->fetch_data(); } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { if (auto *e = dynamic_cast<event_fetch_data_done *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; if (!pl->login_done()) { return player::state_quit::instance(); } return player::state_playing::instance(); } else if (auto *e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_quit::instance(); } return nullptr; } state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " timeout"; return player::state_quit::instance(); } void on_out(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " out"; instance_counter::instance().dec(ICT_FETCH_DATA_PLAYER); } system_clock::duration timeout() override { return 5s; } friend ostream& operator<<(ostream& os, const state_fetch_data& s) { return os << "<state:fetch_data>"; } }; class state_client_create_role : public state_base<player> { public: static state_client_create_role *instance() { static state_client_create_role inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; instance_counter::instance().add(ICT_CLIENT_CREATE_ROLE_PLAYER); } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { if (auto e = dynamic_cast<event_client_create_role *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_create_role::instance(); } else if (auto e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_quit::instance(); } return nullptr; } state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " timeout"; return player::state_quit::instance(); } void on_out(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " out"; instance_counter::instance().dec(ICT_CLIENT_CREATE_ROLE_PLAYER); } system_clock::duration timeout() override { return 1h; } friend ostream& operator<<(ostream& os, const state_client_create_role& s) { return os << "<state::client_create_role>"; } }; class state_create_role : public state_base<player> { public: static state_create_role *instance() { static state_create_role inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; instance_counter::instance().add(ICT_CREATE_ROLE_PLAYER); } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { if (auto e = dynamic_cast<event_create_role_done *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; ASSERT(e->result_ != pd::OK); pcs::base msg; auto rsp = msg.MutableExtension(pcs::s2c_create_role_rsp::scrr); rsp->set_result(e->result_); pl->send_to_client(msg); return player::state_client_create_role::instance(); } else if (auto *e = dynamic_cast<event_find_role_done *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; if (e->result_ != pd::OK) { return nullptr; } pl->init_role(e->role_); db_log::instance().log_login(*pl->role_, pl->ip_); pl->role_->on_event(ECE_ZHANLI_CHANGE, {}); db_log::instance().log_create_role(e->role_, *pl->role_); auto opt_ptt = PTTS_GET_COPY(options, 1); if (!pl->mirror_role()) { /*bi::instance().create_role(pl->username(), pl->yci_, pl->ip_, pl->role_->gid(), pl->role_->name());*/ const auto& mails = pl->role_->mails(); ASSERT(mails.size() == 1); db_log::instance().log_send_mail(pl->role_->gid(), mails.begin()->first, opt_ptt.scene_info().server_id(), mails.begin()->second); } else { auto m = mail_new_mail(pl->role_->gid(), CREATE_ROLE_FIRST_MAIL_PTTID, pd::dynamic_data(), pd::event_array()); db_log::instance().log_send_mail(pl->role_->gid(), m.gid(), opt_ptt.scene_info().server_id(), m); } return player::state_fetch_data::instance(); } else if (auto e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_quit::instance(); } return nullptr; } state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " timeout"; return player::state_quit::instance(); } void on_out(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " out"; instance_counter::instance().dec(ICT_CREATE_ROLE_PLAYER); } system_clock::duration timeout() override { return 5s; } friend ostream& operator<<(ostream& os, const state_create_role& s) { return os << "<state:db_create_role>"; } }; class state_playing : public state_base<player> { public: static state_playing *instance() { static state_playing inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; instance_counter::instance().add(ICT_PLAYING_PLAYER); pl->start_playing_cb_(pl); auto ptt = PTTS_GET_COPY(options, 1); if (ptt.scene_info().weak_connection()) { pl->add_rand_quit_timer(); } } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { if (auto e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; if (!pl->stop_playing()) { return nullptr; } return player::state_quit::instance(); } else if (auto e = dynamic_cast<event_db_rsp *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; if (e->db_msg_->procedure() == "add_notice") { const auto& params = e->db_msg_->params(); auto notice_gid = boost::any_cast<uint64_t>(params[0]); auto role_gid = boost::any_cast<uint64_t>(params[1]); ASSERT(pl->add_notice_cb_); pl->add_notice_cb_(notice_gid, role_gid); } else if (e->db_msg_->procedure() == "find_notice" || e->db_msg_->procedure() == "get_notice") { if (!e->db_msg_->results().empty()) { auto now = duration_cast<hours>(system_clock::now().time_since_epoch()); pcs::base msg; auto *ssn = msg.MutableExtension(pcs::s2c_sync_notices::ssn); auto& results = e->db_msg_->results(); for (const auto& i : results) { auto gid = boost::any_cast<uint64_t>(i[0]); auto str = boost::any_cast<string>(i[2]); pd::notice notice; notice.ParseFromString(str); // todo number limit if (now - hours(notice.time()) > 28 * 24h) { pl->notice_delete(gid); } else { auto *cs_notice = ssn->add_notices(); cs_notice->set_gid(gid); cs_notice->set_already_read(boost::any_cast<uint32_t>(i[1]) != 0); *cs_notice->mutable_data() = notice; } } if (ssn->notices_size() > 0) { pl->send_to_client(msg); } } SPLAYER_DLOG << *this << " find notice done"; } else if (e->db_msg_->procedure() == "notice_set_already_read") { const auto& params = e->db_msg_->params(); auto gid = boost::any_cast<uint64_t>(params[0]); pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_notice_set_already_read_rsp::snsarr); rsp->set_gid(gid); pl->send_to_client(msg); } } return nullptr; } void on_out(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " out"; instance_counter::instance().dec(ICT_PLAYING_PLAYER); auto ptt = PTTS_GET_COPY(options, 1); if (ptt.scene_info().weak_connection()) { pl->remove_rand_quit_timer(); } } #ifndef _DEBUG system_clock::duration timeout() override { return 5min; } #endif state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " timeout"; if (!pl->stop_playing()) { return nullptr; } return player::state_quit::instance(); } friend ostream& operator<<(ostream& os, const state_playing& s) { return os << "<state:playing>"; } }; class state_quit : public state_base<player> { public: static state_quit *instance() { static state_quit inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; instance_counter::instance().add(ICT_QUIT_PLAYER); } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { if (auto *e = dynamic_cast<event_logout *>(event)) { SPLAYER_DLOG << *pl << " " << *this << " on " << *e; return player::state_quit_done::instance(); } return nullptr; } void on_out(const shared_ptr<player<T>>& pl) { pl->quit_timeout(); instance_counter::instance().dec(ICT_QUIT_PLAYER); } system_clock::duration timeout() override { return 100ms; } state_base<player> *on_timeout(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " timeout"; return player::state_quit_done::instance(); } friend ostream& operator<<(ostream& os, const player::state_quit& s) { return os << "<state:quit>"; } }; class state_quit_done : public state_base<player> { public: static state_quit_done *instance() { static state_quit_done inst; return &inst; } void on_in(const shared_ptr<player<T>>& pl) { SPLAYER_DLOG << *pl << " " << *this << " in"; } state_base<player> *on_event(const shared_ptr<player<T>>& pl, event_base *event) { return nullptr; } void on_out(const shared_ptr<player<T>>& pl) { ASSERT(false); } friend ostream& operator<<(ostream& os, const player::state_quit_done& s) { return os << "<state:quit_done>"; } }; #define NOTICE_COMMON(type, rolegid, self) auto db_msg = make_shared<db::message>("add_notice", \ db::message::req_type::rt_insert, \ [self] (const shared_ptr<db::message>& db_msg) { \ self->handle_finished_db_msg(db_msg); \ }); \ auto gid = gid::instance().new_gid(gid_type::NOTICE); \ db_msg->push_param(gid); \ db_msg->push_param(rolegid); \ db_msg->push_param(0); \ pd::notice notice; \ notice.set_type(type); \ notice.set_gid(gid); \ notice.set_time(system_clock::to_time_t(system_clock::now())); void notice_offline_private_chat(uint64_t from_gid, uint32_t time, const string& content, const pd::voice& voice) { async_call( [this, self = this->shared_from_this(), from_gid, time, content, voice] { ASSERT(role_); if (!role_->relation_in_blacklist(from_gid)) { SPLAYER_DLOG << *this << " notice offline private chat " << role_->gid(); NOTICE_COMMON(pd::notice::OFFLINE_PRIVATE_CHAT, role_->gid(), self); auto *opc = notice.mutable_offline_private_chat(); opc->set_from(from_gid); opc->set_time(time); opc->set_content(content); *opc->mutable_voice() = voice; string str; notice.SerializeToString(&str); db_msg->push_param(str); gamedb_notice_->push_message(db_msg, st_); SPLAYER_DLOG << *this << " add notice: " << db_msg; } }); } void relation_notice_removed_by_friend(uint64_t to_gid) { async_call( [this, self = this->shared_from_this(), to_gid] { SPLAYER_DLOG << *self << " notice " << to_gid << " removed by friend"; NOTICE_COMMON(pd::notice::REMOVED_BY_FRIEND, to_gid, self); auto *rbf = notice.mutable_removed_by_friend(); rbf->set_from(role_->gid()); string str; notice.SerializeToString(&str); db_msg->push_param(str); self->gamedb_notice_->push_message(db_msg, self->st_); SPLAYER_DLOG << *self << " add notice: " << db_msg; }); } void send_gift_offline_add_notice(uint64_t from, uint32_t gift, uint32_t count) { auto self = this->shared_from_this(); NOTICE_COMMON(pd::notice::OFFLINE_SEND_GIFT, role_->gid(), self); auto *osg = notice.mutable_offline_send_gift(); osg->set_from(from); osg->set_gift(gift); osg->set_count(count); string str; notice.SerializeToString(&str); db_msg->push_param(str); self->gamedb_notice_->push_message(db_msg, self->st_); SPLAYER_DLOG << *self << " add notice: " << db_msg; } void offline_system_chat_add_notice(uint64_t spouse, uint32_t system_chat, const pd::dynamic_data& dd) { auto self = this->shared_from_this(); NOTICE_COMMON(pd::notice::OFFLINE_SYSTEM_CHAT, role_->gid(), self); auto *osc = notice.mutable_offline_system_chat(); osc->set_from(spouse); osc->set_system_chat(system_chat); *osc->mutable_data() = dd; string str; notice.SerializeToString(&str); db_msg->push_param(str); self->gamedb_notice_->push_message(db_msg, self->st_); SPLAYER_DLOG << *self << " system chat add notice: " << db_msg; } void comment_by_other(uint64_t from, uint64_t reply_to, const string& content) { async_call( [this, self = this->shared_from_this(), from, reply_to, content] { SPLAYER_DLOG << *this << " comment by " << from; ASSERT(check_state_playing()); uint64_t gid; auto result = role_comment_by_other(from, reply_to, content, *role_, gid); ASSERT(comment_done_cb_); if (result == pd::OK) { const auto& comment = role_->get_comment(gid); if (from != role_->gid()) { pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_comment_by_other::srcbo); notice->set_role(from); *notice->mutable_comment() = comment; send_to_client(msg); } comment_done_cb_(from, result, role_->gid(), comment); } else { comment_done_cb_(from, result, role_->gid(), pd::comment()); } }); } void comment_done(pd::result result, uint64_t to, const pd::comment& comment) { async_call( [this, self = this->shared_from_this(), result, to, comment] { ASSERT(check_state_playing()); SPLAYER_DLOG << *this << " comment done " << pd::result_Name(result); pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_role_comment_rsp::srcr); rsp->set_role(to); rsp->set_result(result); if (result == pd::OK) { *rsp->mutable_comment() = comment; } send_to_client(msg); }); } void other_fetch_comments(uint64_t role) { async_call( [this, self = this->shared_from_this(), role] { SPLAYER_DLOG << *this << " fetch comments by " << role; ASSERT(check_state_playing()); pd::comment_array comments; role_->serialize_comments(&comments); comments.clear_gid_seed(); ASSERT(fetch_comments_done_cb_); fetch_comments_done_cb_(role, role_->gid(), comments); }); } void fetch_comments_done(uint64_t role, const pd::comment_array& comments) { async_call( [this, self = this->shared_from_this(), role, comments] { SPLAYER_DLOG << *this << " fetch comments done " << role; if (!check_state_playing()) { return; } pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_fetch_comments_rsp::srfcr); notice->set_role(role); notice->set_result(pd::OK); *notice->mutable_comments() = comments; send_to_client(msg); }); } void delete_comment(uint64_t role, uint64_t gid) { async_call( [this, self = this->shared_from_this(), role, gid] { SPLAYER_DLOG << *this << " delete comment by " << role; ASSERT(check_state_playing()); auto result = pd::OK; do { if (!role_->has_comment(gid)) { result = pd::ROLE_COMMENT_NO_SUCH_COMMENT; break; } const auto& comment = role_->get_comment(gid); if (role != role_->gid() && comment.role() != role) { result = pd::ROLE_COMMENT_NEITHER_OWNER_NOR_WRITER; break; } role_->delete_comment(gid); if (role != role_->gid()) { pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_other_deleted_comment::srodc); notice->set_role(role); notice->set_gid(gid); send_to_client(msg); } } while (false); ASSERT(delete_comment_done_cb_); delete_comment_done_cb_(role, result, role_->gid(), gid); }); } void delete_comment_done(pd::result result, uint64_t role, uint64_t gid) { async_call( [this, self = this->shared_from_this(), result, role, gid] { pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_role_delete_comment_rsp::srdcr); rsp->set_role(role); rsp->set_gid(gid); rsp->set_result(result); send_to_client(rsp_msg); }); } void upvote_by_other(uint64_t upvoter) { async_call( [this, self = this->shared_from_this(), upvoter] { SPLAYER_DLOG << *this << " upvote by " << upvoter; ASSERT(check_state_playing()); uint32_t present = 0; auto result = role_check_upvote_by_other(upvoter, *role_); if (result == pd::OK) { pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_upvoted_by_other::srubo); notice->set_role(upvoter); *notice->mutable_event_res() = role_upvote_by_other(upvoter, *role_, present); send_to_client(msg); } uint32_t present_count = 0; if (role_->has_present()) { present_count = role_->present_count(role_->get_present()); } ASSERT(upvote_done_cb_); upvote_done_cb_(upvoter, result, role_->gid(), present, present_count); }); } void upvote_done(pd::result result, uint64_t upvotee, uint32_t present, uint32_t present_count) { async_call( [this, self = this->shared_from_this(), result, upvotee, present, present_count] { SPLAYER_DLOG << *this << " upvote done " << pd::result_Name(result); if (present > 0) { ASSERT(check_state_playing()); } else { if (!check_state_playing()) { return; } } pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_role_upvote_rsp::srur); rsp->set_result(result); rsp->set_role(upvotee); rsp->set_present_count(present_count); if (result == pd::OK && present > 0) { const auto& ptt = PTTS_GET(role_present, present); auto events = drop_process(PTTS_GET(drop, ptt.drop())); pd::ce_env ce; ce.set_origin(pd::CO_ROLE_UPVOTE_GET_PRESENT); *rsp->mutable_event_res() = event_process(events, *role_, ce); db_log::instance().log_upvote(upvotee, present_count, rsp->event_res(), *role_); } send_to_client(msg); auto *can = bt_->cur_action_node(); if (can) { const auto& ptt = PTTS_GET(behavior_tree, can->pttid()); if (ptt.has_player_action() && ptt.player_action().type() == pd::PAT_ROLE_UPVOTE) { can->mutable_cache()->set_status(result == pd::OK ? pd::OK : pd::FAILED); } } }); } void gongdou_by_other(uint64_t role, const pd::gongdou_data& data, const pd::event_res& event_res, uint64_t call_helper, int desc_idx) { async_call( [this, self = this->shared_from_this(), role, data, event_res, call_helper, desc_idx] { SPLAYER_DLOG << *this << " gongdou by other " << role << " " << pd::gongdou_type_Name(data.type()); ASSERT(check_state_playing()); auto result = gongdou_target_check(data, *role_); if (result != pd::OK) { ASSERT(gongdou_done_cb_); gongdou_done_cb_(role, role_->gid(), data.type(), result, pd::gongdou_effect(), event_res, call_helper, role_->league_gid()); return; } if (data.type() == pd::GT_SLANDER) { pd::gongdou_base_data base_data; base_data.set_from(role); base_data.set_target(role_->gid()); base_data.set_type(data.type()); base_data.set_time(system_clock::to_time_t(system_clock::now())); base_data.set_slander_idx(desc_idx); gongdou_slander_vote_start_func_(base_data); gongdou_done_cb_(role, role_->gid(), data.type(), pd::CONTINUE, pd::gongdou_effect(), event_res, call_helper, role_->league_gid()); return; } const auto& ptt = PTTS_GET(gongdou, data.type()); auto last_minutes = ptt.last_minutes(); if (role_->gongdou_has_effect(pd::GT_PRISON)) { if (ptt.effect_type() == pd::GET_HARMFUL) { last_minutes *= 2; } } auto record = role_->gongdou_add_effect(role, data.type(), last_minutes * 60); role_->change_gongdou_by_other_times(data.type(), 1); pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_gongdou_by_other::sgbo); *notice->mutable_effect() = role_->gongdou_effect(data.type()); *notice->mutable_record() = record; *notice->mutable_event_res() = gongdou_effect_event_process(data, *role_, event_res); if (ptt.has_gongdou_by_other_mail()) { pd::dynamic_data mdd; mdd.add_name(gid2rolename_func_(role)); send_mail(ptt.gongdou_by_other_mail(), mdd, pd::event_array()); } if (ptt.has_system_chat()) { pd::dynamic_data dd; dd.add_name(gid2rolename_func_(role_->gid())); dd.add_name(gid2rolename_func_(data.other())); ASSERT(send_system_chat_func_); send_system_chat_func_(ptt.system_chat(), dd); } send_to_client(msg); ASSERT(gongdou_done_cb_); gongdou_done_cb_(role, role_->gid(), data.type(), pd::OK, role_->gongdou_effect(data.type()), event_res, call_helper, role_->league_gid()); }); } void gongdou_slander_vote_done(uint64_t from, uint64_t target, pd::gongdou_type type, pd::result result) { async_call( [this, self = this->shared_from_this(), from, target, type, result] { if (!check_state_playing()) { return; } pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_gongdou_vote_rsp::sgvr); notice->set_result(result); notice->set_type(type); notice->set_from(from); notice->set_target(target); send_to_client(msg); }); } void gongdou_slander_stat_finish_done(const pd::gongdou_base_data& base_data, pd::result result) { async_call( [this, self = this->shared_from_this(), base_data, result] { SPLAYER_DLOG << *this << " gongdou slander vote finish done " << pd::result_Name(result); ASSERT(check_state_playing()); if (result == pd::OK) { const auto& ptt = PTTS_GET(gongdou, base_data.type()); auto last_minutes = ptt.last_minutes(); if (role_->gongdou_has_effect(pd::GT_PRISON)) { if (ptt.effect_type() == pd::GET_HARMFUL) { last_minutes *= 2; } } auto record = role_->gongdou_add_effect(base_data.from(), base_data.type(), last_minutes * 60, base_data.slander_idx()); role_->change_gongdou_by_other_times(base_data.type(), 1); pd::gongdou_data data; data.set_type(base_data.type()); data.set_other(base_data.from()); data.set_slander_idx(base_data.slander_idx()); pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_gongdou_by_other::sgbo); *notice->mutable_effect() = role_->gongdou_effect(base_data.type()); *notice->mutable_record() = record; *notice->mutable_event_res() = gongdou_effect_event_process(data, *role_, pd::event_res()); send_to_client(msg); if (ptt.has_gongdou_by_other_mail()) { pd::dynamic_data mdd; mdd.add_name(gid2rolename_func_(base_data.from())); send_mail(ptt.gongdou_by_other_mail(), mdd, pd::event_array()); } ASSERT(base_data.slander_idx() < ptt.slander_size()); pd::dynamic_data dd; dd.add_name(gid2rolename_func_(base_data.target())); dd.add_title(ptt.slander(base_data.slander_idx()).title()); ASSERT(send_system_chat_func_); send_system_chat_func_(ptt.slander(base_data.slander_idx()).system_chat(), dd); } else { role_->gongdou_slander_fail(base_data.from(), base_data.target(), result, false); } }); } void gongdou_slander_finish_itself_effect_done(const pd::gongdou_base_data& base_data, pd::result result, bool has_debuff) { async_call( [this, self = this->shared_from_this(), base_data, result, has_debuff] { SPLAYER_DLOG << *this << " gongdou slander itself effect, has_debuff = " << has_debuff; ASSERT(check_state_playing()); auto record = role_->gongdou_slander_fail(base_data.from(), base_data.target(), result, has_debuff); if (has_debuff) { const auto& ptt = PTTS_GET(gongdou, pd::GT_SLANDER); pd::ce_env ce; ce.set_origin(pd::CO_GONGDOU_BY_OTHER); pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_gongdou_by_other::sgbo); *notice->mutable_effect() = role_->gongdou_effect(base_data.type()); *notice->mutable_record() = record; *notice->mutable_event_res() = event_process(ptt.slander_fail_events().events(), *role_, ce); send_to_client(msg); pd::dynamic_data dd; dd.add_name(gid2rolename_func_(base_data.from())); dd.add_name(gid2rolename_func_(base_data.target())); ASSERT(send_system_chat_func_); send_system_chat_func_(ptt.slander_fail_events().system_chat(), dd); } }); } void gongdou_done(uint64_t role, pd::gongdou_type type, pd::result result, const pd::gongdou_effect& effect, const pd::event_res& event_res, uint64_t call_helper, uint64_t to_league = 0) { async_call( [this, self = this->shared_from_this(), role, type, result, effect, event_res, call_helper, to_league] { SPLAYER_DLOG << *this << " gongdou done " << pd::result_Name(result); if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_gongdou_rsp::sgr); rsp->set_type(type); rsp->set_target(role); rsp->set_result(result); const auto& ptt = PTTS_GET(gongdou, type); if (result == pd::OK) { *rsp->mutable_effect() = effect; *rsp->mutable_event_res() = event_res; role_->change_gongdou_times(type, role); role_->on_event(ECE_ROLE_GONGDOU, { to_league, role_->league_gid(), ptt.effect_type() }); db_log::instance().log_gongdou(type, role_->gid(), result, role, event_res, *role_); if (call_helper != 0) { league_gongdou_helped_by_other_func_(role_->gid(), type, role, call_helper); } } else if (result == pd::GONGDOU_NOT_HITTED || result == pd::CONTINUE) { *rsp->mutable_event_res() = event_res; role_->change_gongdou_times(type, role); role_->on_event(ECE_ROLE_GONGDOU, { to_league, role_->league_gid(),ptt.effect_type() }); db_log::instance().log_gongdou(type, role_->gid(), result, role, event_res, *role_); } else { event_revert(event_res, *role_, pd::CO_GONGDOU_REVERT); } send_to_client(rsp_msg); if (result == pd::OK) { role_->try_levelup(); } auto *can = bt_->cur_action_node(); if (can) { const auto& ptt = PTTS_GET(behavior_tree, can->pttid()); if (ptt.has_player_action() && ptt.player_action().type() == pd::PAT_GONGDOU) { can->mutable_cache()->set_status(result == pd::OK ? pd::OK : pd::FAILED); } } }); } void gongdou_add_spouse_record(uint64_t role, pd::gongdou_type type, const pd::gongdou_record& record) { async_call( [this, self = this->shared_from_this(), role, type, record] { SPLAYER_DLOG << *this << " gongdou add spouse record " << role; ASSERT(check_state_playing()); if (!role_->marriage_married() || role_->marriage_spouse() != role) { return; } role_->gongdou_add_spouse_record(type, record); }); } void marriage_update_spouse_vip_exp(uint64_t role, uint64_t vip_exp) { async_call( [this, self = this->shared_from_this(), role, vip_exp] { SPLAYER_DLOG << *this << " marriage update spouse vip exp " << role; ASSERT(check_state_playing()); if (!role_->marriage_married() || role_->marriage_spouse() != role) { return; } role_->marriage_set_spouse_vip_exp(vip_exp); }); } void marriage_refresh_questions(uint64_t spouse) { async_call( [this, self = this->shared_from_this(), spouse] { SPLAYER_DLOG << *this << " marriage refresh questions " << spouse; ASSERT(check_state_playing()); if (!role_->marriage_married() || role_->marriage_spouse() != spouse) { return; } role_->marriage_refresh_questions(true); }); } void marriage_spouse_sync_questions(uint64_t spouse, const vector<pd::marriage_question>& questions) { async_call( [this, self = this->shared_from_this(), spouse, questions] { SPLAYER_DLOG << *this << " marriage spouse sync questions " << spouse; if (!role_->marriage_married() || role_->marriage_spouse() != spouse) { return; } role_->marriage_spouse_sync_questions(questions); }); } void get_ranking_list_done(uint32_t self_rank, const vector<pd::rank_entity>& entities, uint32_t count, pd::rank_type type) { async_call( [this, self = this->shared_from_this(), self_rank, entities, count, type] { SPLAYER_DLOG << *this << " get ranking list done"; if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_ranking_list_rsp::srlr); rsp->set_self_rank(self_rank); auto need_count = count < 50 ? count : 50; auto index = entities.size() < need_count ? entities.size() : need_count; for (uint i = 0; i < index; i++) { *rsp->add_entities() = entities[i]; } rsp->set_type(type); send_to_client(rsp_msg); }); } void get_ranking_self_rank_done(const pcs::ranking_self_ranks& ranks) { async_call( [this, self = this->shared_from_this(), ranks] { SPLAYER_DLOG << *this << " get ranking self rank done"; if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_ranking_get_self_rank_rsp::srgsrr); *rsp->mutable_ranks() = ranks; send_to_client(rsp_msg); }); } void rank_give_role_a_like_done(pd::result result, uint64_t gid, pd::rank_type type, int like_count, const pd::event_res& event_res) { async_call( [this, self = this->shared_from_this(), result, gid, type, like_count, event_res] { SPLAYER_DLOG << *this << " rank give role a like done"; if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_rank_give_role_a_like_rsp::srgralr); rsp->set_result(result); rsp->set_role(gid); rsp->set_type(type); if (result == pd::OK) { role_->on_event(ECE_GIVE_ROLE_A_LIKE, {}); rsp->set_like_count(like_count); *rsp->mutable_event_res() = event_res; } else { role_->rank_like_delete_role(gid, type); event_revert(event_res, *role_, pd::CO_RANK_GIVE_A_LIKE_FILED); } send_to_client(rsp_msg); }); } void replay_battle_conflict_record_done(pd::result result, uint64_t gid, const pd::conflict_battle_record& record) { async_call( [this, self = this->shared_from_this(), result, gid, record] { if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_replay_battle_conflict_record_rsp::srbcrr); if (result == pd::OK) { auto b = make_unique<battle>(); auto result = b->init(record.pttid(), record.team_a(), record.team_b(), record.context()); if (result == pd::CONTINUE) { if (record.battle_info().skip_battle()) { result = b->process_role_inputs(record.role(), record.battle_info().inputs(), true); } else{ result = b->process_role_inputs(record.role(), record.battle_info().inputs(), false); } b->check_battle_info(record.battle_info(), result); } *rsp->mutable_record() = record; } rsp->set_result(result); rsp->set_gid(gid); send_to_client(rsp_msg); }); } void guanpin_promote_done(pd::result result, int gpin, const pd::battle_damage_info& damage_info, const pd::event_res& event_res, int idx) { async_call( [this, self = this->shared_from_this(), result, gpin, damage_info, event_res, idx] { SPLAYER_DLOG << *this << " guanpin promote done " << pd::result_Name(result); ASSERT(check_state_playing()); if (result != pd::OK && result != pd::BATTLE_LOST) { event_revert(event_res, *role_, pd::CO_GUANPIN_PROMOTE_REVERT); } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_guanpin_promote_rsp::sgpr); rsp->set_gpin(gpin); rsp->set_result(result); rsp->set_battle_seed(role_->guanpin_battle_seed()); pd::event_res events = event_res; if (result == pd::OK) { if (role_->guanpin_gpin() != gpin && role_->guanpin_idx() != idx) { const auto& ptt = PTTS_GET(guanpin, gpin); pd::ce_env ce; ce.set_origin(pd::CO_GUANPIN_PROMOTE); *rsp->mutable_renzhi_event_res() = event_process(ptt.renzhi_events(), *role_, ce); } role_->guanpin_set(gpin, idx); rsp->set_cur_gpin(gpin); rsp->set_cur_idx(idx); *rsp->mutable_damage_info() = damage_info; *rsp->mutable_event_res() = event_res; db_log::instance().log_guanpin_promote(gpin, idx, rsp->event_res(), *role_); } send_to_client(rsp_msg); if (!mirror_role()) { pd::role_mirror_event event; event.set_gid(gid()); event.set_challenge_gpin(gpin); event.set_type(pd::RMET_GUANPIN_PROMOTE); send_mirror_role_event_msg(event); if (result == pd::OK) { //bi::instance().guanpin_promote(username(), yci_, ip_, role_->gid(), role_->league_gid(), role_->level(), event_res, pd::CO_GUANPIN_PROMOTE); } } auto *can = bt_->cur_action_node(); if (can) { const auto& ptt = PTTS_GET(behavior_tree, can->pttid()); if (ptt.has_player_action() && ptt.player_action().type() == pd::PAT_GUANPIN_PROMOTE) { can->mutable_cache()->set_status(pd::OK); } } }); } void guanpin_fetch_data_done(int gpin, int idx) { async_call( [this, self = this->shared_from_this(), gpin, idx] { SPLAYER_DLOG << *this << " guanpin fetch data done " << gpin << " " << idx; if (check_state_playing()) { role_->guanpin_set(gpin, idx); pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_guanpin_fetch_data_rsp::sgfdr); notice->set_gpin(gpin); notice->set_idx(idx); send_to_client(msg); } else if (check_state_fetch_data()) { role_->guanpin_set(gpin, idx); fetch_one_data_done(); } }); } void guanpin_get_guans_done(pd::result result, uint32_t gpin, uint32_t page, uint32_t page_size, const list<pd::guan>& guans, uint32_t gpin_guan_count) { async_call( [this, self = this->shared_from_this(), result, gpin, page, page_size, guans, gpin_guan_count] { SPLAYER_DLOG << *this << " guanpin get guan done " << pd::result_Name(result) << " " << gpin << " " << page; if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_guanpin_get_guans_rsp::sgggr); rsp->set_gpin(gpin); rsp->set_page(page); if (page_size != rsp->page_size()) { rsp->set_page_size(page_size); } rsp->set_gpin_guan_count(gpin_guan_count); rsp->set_result(result); if (result == pd::OK) { for (const auto& i : guans) { *rsp->mutable_guans()->add_guans() = i; } } send_to_client(rsp_msg); }); } void guanpin_collect_fenglu_done(pd::result result, const pd::event_array& events, uint32_t fenglu_factor) { async_call( [this, self = this->shared_from_this(), result, events, fenglu_factor] { SPLAYER_DLOG << *this << " guanpin collect fenglu done " << pd::result_Name(result); if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_guanpin_collect_fenglu_rsp::sgcfr); rsp->set_result(result); if (result == pd::OK) { pd::ce_env ce; ce.set_origin(pd::CO_GUANPIN_FENGLU); ce.set_add_percent(fenglu_factor); *rsp->mutable_event_res() = event_process(events, *role_, ce); role_->on_event(ECE_GUANPIN_COLLECT_FENGLU, {}); role_->guanpin_set_collect_fenglu_day(); db_log::instance().log_guanpin_collect_fenglu(role_->guanpin_gpin(), role_->guanpin_idx(), rsp->event_res(), *role_); } send_to_client(rsp_msg); }); } void guanpin_challenge_done(pd::result result, int target_gpin, int target_idx, uint64_t target, uint32_t battle_seed, const pd::battle_team& target_team, const pd::battle_team& self_team, const pd::battle_damage_info& damage_info, int gpin, int idx, const pd::event_res& event_res) { async_call( [this, self = this->shared_from_this(), result, target_gpin, target_idx, target, battle_seed, target_team, self_team, damage_info, gpin, idx, event_res = event_res] () mutable { ASSERT(check_state_playing()); SPLAYER_DLOG << *this << " guanpin challenge done " << pd::result_Name(result); if (result != pd::OK && result != pd::BATTLE_LOST) { event_revert(event_res, *role_, pd::CO_GUANPIN_CHALLENGE_REVERT); } else if (result == pd::OK){ role_->guanpin_set(gpin, idx); } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_guanpin_challenge_rsp::sgcr); rsp->set_target_gpin(target_gpin); rsp->set_target_idx(target_idx); rsp->set_target(target); rsp->set_result(result); rsp->set_gpin(gpin); rsp->set_idx(idx); rsp->set_battle_seed(battle_seed); *rsp->mutable_target_team() = target_team; *rsp->mutable_damage_info() = damage_info; *rsp->mutable_self_team() = self_team; pd::ce_env ce; ce.set_origin(pd::CO_GUANPIN_CHALLENGE); const auto& ptt = PTTS_GET(guanpin, role_->guanpin_gpin()); if (result == pd::OK) { *rsp->mutable_event_res() = event_process(ptt.challenge().win_events(), *role_, ce, &event_res); } else { *rsp->mutable_event_res() = event_process(ptt.challenge().lose_events(), *role_, ce, &event_res); } db_log::instance().log_guanpin_challenge(target_gpin, target_idx, rsp->event_res(), *role_); role_->on_event(ECE_GUANPIN_CHALLENGE, {}); send_to_client(rsp_msg); auto *can = bt_->cur_action_node(); if (can) { const auto& ptt = PTTS_GET(behavior_tree, can->pttid()); if (ptt.has_player_action() && ptt.player_action().type() == pd::PAT_GUANPIN_CHAOTANG_CHANLLENGE) { can->mutable_cache()->set_status(pd::OK); } } }); } void guanpin_challenged_by_other(pd::result result, int gpin, int idx, const pd::guanpin_challenge_record& challenge_record, uint64_t from) { async_call( [this, self = this->shared_from_this(), result, gpin, idx, challenge_record, from] { SPLAYER_DLOG << *this << " guanpin challenged by other " << pd::result_Name(result); if (!check_state_playing()) { return; } pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_guanpin_challenged_by_other::sgcbo); if (role_->guanpin_gpin() != gpin) { role_->guanpin_changed_record(from, pd::RT_GUANPIN_CHANGED_DEMOTE, role_->guanpin_gpin(), gpin); } role_->guanpin_set(gpin, idx); notice->set_gpin(gpin); notice->set_idx(idx); *notice->mutable_challenge_record() = challenge_record; send_to_client(msg); }); } void guanpin_dianshi_baoming_done(pd::result result, int gpin, const pd::event_res& event_res) { async_call( [this, self = this->shared_from_this(), result, gpin, event_res] { SPLAYER_DLOG << *this << " guanpin dianshi baoming done " << pd::result_Name(result); if (!check_state_playing()) { return; } if (result != pd::OK) { event_revert(event_res, *role_, pd::CO_GUANPIN_DIANSHI_BAOMING_REVERT); } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_guanpin_dianshi_baoming_rsp::sgdbr); rsp->set_gpin(gpin); rsp->set_result(result); if (result == pd::OK) { *rsp->mutable_event_res() = event_res; db_log::instance().log_guanpin_baoming(gpin, rsp->event_res(), *role_); } send_to_client(rsp_msg); auto *can = bt_->cur_action_node(); if (can) { const auto& ptt = PTTS_GET(behavior_tree, can->pttid()); if (ptt.has_player_action() && ptt.player_action().type() == pd::PAT_GUANPIN_DIANSHI_BAOMING) { can->mutable_cache()->set_status(result == pd::OK ? pd::OK : pd::FAILED); } } if (!mirror_role()) { pd::role_mirror_event event; event.set_gid(gid()); event.set_challenge_gpin(gpin); event.set_type(pd::RMET_GUANPIN_DIANSHI_BAOMING); send_mirror_role_event_msg(event); } }); } void guanpin_dianshi_demote(int gpin, int idx) { async_call( [this, self = this->shared_from_this(), gpin, idx] { SPLAYER_DLOG << *this << " guanpin dianshi demote " << gpin << " " << idx; ASSERT(check_state_playing()); pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_guanpin_dianshi_demote::sgdd); if (role_->guanpin_gpin() != gpin && role_->guanpin_idx() != idx) { const auto& ptt = PTTS_GET(guanpin, gpin); pd::ce_env ce; ce.set_origin(pd::CO_GUANPIN_DEMOTE); *notice->mutable_event_res() = event_process(ptt.renzhi_events(), *role_, ce); role_->guanpin_changed_record(role_->gid(), pd::RT_GUANPIN_CHANGED_DEMOTE, role_->guanpin_gpin(), gpin); } role_->guanpin_set(gpin, idx); notice->set_gpin(gpin); notice->set_idx(idx); db_log::instance().log_guanpin_dianshi_demote(gpin, idx, *role_); send_to_client(msg); }); } void guanpin_dianshi_promote(int gpin, int idx) { async_call( [this, self = this->shared_from_this(), gpin, idx] { SPLAYER_DLOG << *this << " guanpin dianshi promote " << gpin << " " << idx; ASSERT(check_state_playing()); pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_guanpin_dianshi_promote::sgdp); if (role_->guanpin_gpin() != gpin && role_->guanpin_idx() != idx) { const auto& ptt = PTTS_GET(guanpin, gpin); pd::ce_env ce; ce.set_origin(pd::CO_GUANPIN_PROMOTE); *notice->mutable_event_res() = event_process(ptt.renzhi_events(), *role_, ce); role_->guanpin_changed_record(role_->gid(), pd::RT_GUANPIN_CHANGED_PROMOTE, role_->guanpin_gpin(), gpin); } role_->guanpin_set(gpin, idx); notice->set_gpin(gpin); notice->set_idx(idx); send_to_client(msg); }); } void guanpin_gongdou_promote(int gpin, int idx, pd::result result, const pd::gongdou_data& gongdou_data, const pd::event_res& event_res) { async_call( [this, self = this->shared_from_this(), gpin, idx, result, gongdou_data, event_res] { SPLAYER_DLOG << *this << " guanpin gongdou promote " << gpin << " " << idx; ASSERT(check_state_playing()); if (result != pd::OK) { if (role_->gid() == gongdou_data.other()) { event_revert(event_res, *role_, pd::CO_GONGDOU_REVERT); } else { role_->change_gongdou_by_other_times(gongdou_data.type(), -1); } } pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_guanpin_gongdou_promote::sggp); if (result == pd::OK) { if (role_->guanpin_gpin() != gpin && role_->guanpin_idx() != idx) { const auto& ptt = PTTS_GET(guanpin, gpin); pd::ce_env ce; ce.set_origin(pd::CO_GUANPIN_PROMOTE); *notice->mutable_event_res() = event_process(ptt.renzhi_events(), *role_, ce); } role_->guanpin_set(gpin, idx); notice->set_gpin(gpin); notice->set_idx(idx); send_to_client(msg); } }); } void guanpin_dianshi_info_done(pd::result result, int gpin, const pd::guanpin_dianshi_gpin& data) { async_call( [this, self = this->shared_from_this(), result, gpin, data] { SPLAYER_DLOG << *this << " guanpin info done " << pd::result_Name(result); if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_guanpin_dianshi_info_rsp::sgdir); rsp->set_result(result); rsp->set_gpin(gpin); if (result == pd::OK) { *rsp->mutable_data() = data; } send_to_client(rsp_msg); }); } void guanpin_dianshi_replay_done(pd::result result, int gpin, int record_idx, const pd::guanpin_dianshi_record& data) { async_call( [this, self = this->shared_from_this(), result, gpin, record_idx, data] { SPLAYER_DLOG << *this << " guanpin dianshi replay done " << pd::result_Name(result); if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_guanpin_dianshi_replay_rsp::sgdrr); rsp->set_result(result); rsp->set_gpin(gpin); rsp->set_record_idx(record_idx); if (result == pd::OK) { *rsp->mutable_record() = data; } send_to_client(rsp_msg); }); } void guanpin_fetch_baoming_info_done(const pd::guanpin_baoming_infos& baomings) { async_call( [this, self = this->shared_from_this(), baomings] { SPLAYER_DLOG << *this << " guanpin fetch baoming info done"; if (!check_state_playing()) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_fetch_gpin_baoming_info_rsp::sfgbir); *rsp->mutable_baomings() = baomings; send_to_client(rsp_msg); }); } void guanpin_set_gpin_done(pd::result result, int gpin, int idx) { async_call( [this, self = this->shared_from_this(), result, gpin, idx] { SPLAYER_DLOG << *this << " guanpin set gpin done " << gpin << " " << idx; if (!check_state_playing()) { return; } if (result != pd::OK) { return; } role_->guanpin_set(gpin, idx); pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_guanpin_set_gpin::sgsg); notice->set_gpin(gpin); notice->set_idx(idx); send_to_client(msg); }); } void marriage_spouse_login(uint64_t spouse) { async_call( [this, self = this->shared_from_this(), spouse] { SPLAYER_DLOG << *this << " marriage spouse login " << spouse; ASSERT(check_state_playing()); if (!role_->marriage_married() || role_->marriage_spouse() != spouse) { return; } role_->marriage_spouse_login(); pcs::base msg; msg.MutableExtension(pcs::s2c_marriage_spouse_login::smsl); send_to_client(msg); }); } void marriage_spouse_logout(uint64_t spouse) { async_call( [this, self = this->shared_from_this(), spouse] { SPLAYER_DLOG << *this << " marriage spouse logout " << spouse; ASSERT(check_state_playing()); if (!role_->marriage_married() || role_->marriage_spouse() != spouse) { return; } role_->marriage_spouse_logout(); pcs::base msg; msg.MutableExtension(pcs::s2c_marriage_spouse_logout::smsl); send_to_client(msg); }); } void marriage_fetch_data_done(bool star_wishing, bool pking, uint32_t qiu_qian_actor, uint32_t pregnent_time) { async_call( [this, self = this->shared_from_this(), star_wishing, pking, qiu_qian_actor, pregnent_time] { SPLAYER_DLOG << *this << " marriage fetch data done " << star_wishing << " " << pking << " " << qiu_qian_actor << " " << pregnent_time; if (!check_state_fetch_data()) { return; } role_->marriage_set_star_wishing(star_wishing); role_->marriage_set_pking(pking); role_->marriage_set_qiu_qian_actor(qiu_qian_actor); role_->marriage_set_pregnent_time(pregnent_time); this->fetch_one_data_done(); }); } void marriage_start_star_wish_done(pd::result result, const string& declaration, const pd::voice& voice, const pd::event_res& event_res, uint32_t time) { async_call( [this, self = this->shared_from_this(), result, declaration, voice, event_res, time] { SPLAYER_DLOG << *this << " marriage start star wish done " << pd::result_Name(result); if (!check_state_playing()) { return; } if (result != pd::OK) { event_revert(event_res, *role_, pd::CO_MARRIAGE_START_STAR_WISH_REVERT); if (result != pd::MARRIAGE_ALREADY_START_STAR_WISH) { role_->marriage_set_star_wishing(false); } } else { auto ptt = PTTS_GET(marriage_logic, 1); pd::dynamic_data dd; dd.add_name(gid2rolename_func_(role_->gid())); ASSERT(send_system_chat_func_); send_system_chat_func_(ptt.star_wish_start_system_chat(), dd); } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_marriage_start_star_wish_rsp::smsswr); rsp->set_result(result); rsp->set_declaration(declaration); *rsp->mutable_voice() = voice; rsp->set_time(time); *rsp->mutable_event_res() = event_res; send_to_client(rsp_msg); db_log::instance().log_marriage_start_star_wish(declaration, event_res, *role_); auto *can = bt_->cur_action_node(); if (can) { const auto& ptt = PTTS_GET(behavior_tree, can->pttid()); if (ptt.has_player_action() && ptt.player_action().type() == pd::PAT_MARRIAGE_START_STAR_WISH) { can->mutable_cache()->set_status(result); ai_.marriage_.star_wish_start_time_ = time; } } }); } void marriage_star_wish_list_done(pd::result result, const pd::marriage_star_wish_array& data) { async_call( [this, self = this->shared_from_this(), result, data] { SPLAYER_DLOG << *this << " marriage star wish list done " << pd::result_Name(result); if (!check_state_playing()) { return; } for (const auto& i : fetch_marriage_star_wish_list_call_funcs_) { i(result, data); } fetch_marriage_star_wish_list_call_funcs_.clear(); }); } void marriage_star_wish_send_gift_done(pd::result result, uint64_t target, uint32_t gift, uint32_t count, const pd::event_res& event_res, int star_wish, bool suiting) { async_call( [this, self = this->shared_from_this(), result, target, count, gift, event_res, star_wish, suiting] { SPLAYER_DLOG << *this << " marriage star wish send gift done " << pd::result_Name(result); if (!check_state_playing()) { return; } if (result != pd::OK) { event_revert(event_res, *role_, pd::CO_MARRIAGE_STAR_WISH_SEND_GIFT_REVERT); if (!suiting) { role_->marriage_set_star_wishing(false); } } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_marriage_star_wish_send_gift_rsp::smswsgr); rsp->set_role(target); rsp->set_gift(gift); rsp->set_count(count); rsp->set_result(result); if (result == pd::OK) { *rsp->mutable_event_res() = event_res; rsp->set_star_wish(star_wish); db_log::instance().log_marriage_star_wish_send_gift(event_res, *role_); } send_to_client(rsp_msg); auto *can = bt_->cur_action_node(); if (can) { const auto& ptt = PTTS_GET(behavior_tree, can->pttid()); if (ptt.has_player_action() && ptt.player_action().type() == pd::PAT_MARRIAGE_STAR_WISH_SEND_GIFT) { can->mutable_cache()->set_status(result == pd::OK ? pd::OK : pd::FAILED); if (ai_.marriage_.star_wish_target_ == 0) { ai_.marriage_.star_wish_target_ = target; } } } }); } void marriage_star_wish_receive_gift(uint64_t from, uint32_t gift, uint32_t count, int star_wish) { async_call( [this, self = this->shared_from_this(), from, gift, count, star_wish] { SPLAYER_DLOG << *this << " marriage star wish receive gift"; if (!check_state_playing()) { return; } pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_marriage_star_wish_receive_gift::smswrg); notice->set_role(from); notice->set_gift(gift); notice->set_count(count); notice->set_star_wish(star_wish); send_to_client(msg); }); } /*void role_mirror_event_mansion_leave_banquet() { async_call( [this, self = this->shared_from_this()] { ASSERT(check_state_playing()); ASSERT(mansion_leave_banquet_func_); mansion_leave_banquet_func_(role_->gid()); }); }*/ /* pd::result ai_action_activity_qiandao(pd::behavior_tree_node& node) { auto cur_month = refresh_month(); auto cur_mday = refresh_mday(); auto result = activity_check_qiandao(cur_month, cur_mday, *role_); if (result != pd::OK) { return pd::FAILED; } pd::ce_env ce; ce.set_origin(pd::CO_ACTIVITY_QIANDAO_REWARD); const auto& qiandao_ptt = PTTS_GET(activity_qiandao, cur_month); ASSERT(qiandao_ptt.rewards_size() > cur_mday - 1); ASSERT(condevent_check(qiandao_ptt.rewards(cur_mday - 1).qiandao_events(), *role_, ce) == pd::OK); condevent_process(qiandao_ptt.rewards(cur_mday - 1).qiandao_events(), *role_, ce); role_->activity_add_qiandao(cur_month, cur_mday); return pd::OK; } pd::result ai_action_activity_recharge(pd::behavior_tree_node& node) { const auto& ptts = PTTS_GET_ALL(recharge); auto iter = ptts.begin(); advance(iter, rand() % ptts.size()); auto recharge_pttid = iter->second.id(); const auto& ptt = PTTS_GET(recharge, recharge_pttid); auto result = activity_check_recharge(recharge_pttid, *role_); if (result != pd::OK) { return pd::FAILED; } auto order = role_->add_recharge_order(recharge_pttid); activity_recharge(recharge_pttid, *role_); auto opt_ptt = PTTS_GET_COPY(options, 1); yunying_recharge(0, 0, order, "", "RMB", ptt.price(), system_clock::to_time_t(system_clock::now()), "", true); return pd::OK; } pd::result ai_acition_activity_yueka_reward(pd::behavior_tree_node& node) { set<uint32_t> yueka_set; for (const auto& i : PTTS_GET_ALL(recharge)) { if (i.second.has_days()) { yueka_set.insert(i.second.id()); } } if (yueka_set.empty()) { return pd::FAILED; } auto iter = yueka_set.begin(); advance(iter, rand() % yueka_set.size()); auto result = check_recharge_day(*iter, *role_); if (result != pd::OK) { return pd::FAILED; } const auto& ptt = PTTS_GET(recharge, *iter); role_->recharge_update_last_process_day(*iter, refresh_day()); pd::ce_env ce; ce.set_origin(pd::CO_GET_RECHARGE); event_process(ptt.day_events(), *role_, ce); return pd::OK; } pd::result ai_action_adventure_challenge_new(pd::behavior_tree_node& node) { auto passed_adventures = role_->adventure_passed_adventures(); set<uint64_t> adventures; auto result = pd::OK; const auto& ptts = PTTS_GET_ALL(adventure); for (const auto& i : ptts) { if (passed_adventures.count(i.first) > 0) { continue; } result = adventure_check_challenge(i.second, *role_); if (result == pd::OK) { adventures.insert(i.first); } } if (adventures.empty()) { return pd::FAILED; } auto iter = adventures.begin(); advance(iter, rand() % adventures.size()); pd::pttid_array plots; const auto& selections = get_plot_selection_array(*iter, plots); if (selections.selections_size() > 1) { for (auto i : selections.selections()) { pd::plot_selection_array psa; if (selections.has_plot()) { psa.set_plot(selections.plot()); } psa.add_selections(i); result = challenge_adventure(*iter, psa, plots, pd::battle_info(), pd::huanzhuang_item_id_array()); if (result != pd::OK) { return pd::FAILED; } } } else { result = challenge_adventure(*iter, selections, plots, pd::battle_info(), pd::huanzhuang_item_id_array()); } return result == pd::OK ? pd::OK : pd::FAILED; } */ void clear_timeout() { async_call( [this, self = this->shared_from_this()] { if (this->check_state_playing() && !quiting_playing_) { SPLAYER_DLOG << *this << " clear timeout"; this->sm_->reset_timeout(5min); } }); } const shared_ptr<service_thread>& get_st() const { return st_; } function<void(const Descriptor *, size_t)> send_msg_cb_; function<pd::result(const shared_ptr<player<T>>&)> login_cb_; function<bool(const shared_ptr<player<T>>&)> start_fetch_data_cb_; function<bool(const shared_ptr<player<T>>&, const string&, const string&)> login_done_cb_; function<void(const shared_ptr<player<T>>&)> quit_cb_; function<void(const shared_ptr<player<T>>&)> start_playing_cb_; function<bool(const shared_ptr<player<T>>&)> stop_playing_cb_; function<uint64_t(const string&)> rolename2gid_func_; function<string(uint64_t)> gid2rolename_func_; function<string(uint32_t)> random_role_name_func_; function<uint32_t()> server_open_day_func_; function<void(bool)> activity_add_fund_func_; private: bool check_state_playing() const { return sm_->get_state() == state_playing::instance(); } void set_quiting_playing() { ai_stop(); stop_resource_grow_timer(); quiting_playing_ = true; } bool check_state_fetch_data() const { return sm_->get_state() == state_fetch_data::instance(); } bool check_state_init() const { return sm_->get_state() == state_init::instance(); } bool check_state_check_login() const { return sm_->get_state() == state_check_login::instance(); } bool check_state_client_create_role() const { return sm_->get_state() == state_client_create_role::instance(); } bool check_state_create_role() const { return sm_->get_state() == state_create_role::instance(); } bool check_state_find_role() const { return sm_->get_state() == state_find_role::instance(); } vector<string> translate_data(const vector<boost::any>& data) { vector<string> str_data; for (auto& i : data) { try { str_data.push_back(boost::any_cast<string>(i)); } catch (const boost::bad_any_cast& e) { auto value = boost::any_cast<uint64_t>(i); str_data.push_back(to_string(value)); } } return str_data; } bool init_role(const pd::role& data) { role_ = make_shared<role>(st_, yci_, ip_); role_->parse_from(data); role_->gid2rolename_func_ = [this, self = this->shared_from_this()] (auto gid) { ASSERT(gid2rolename_func_); return gid2rolename_func_(gid); }; role_->server_open_day_func_ = [this, self = this->shared_from_this()] () { ASSERT(server_open_day_func_); return server_open_day_func_(); }; role_->username_func_ = [this] { return username(); }; role_->actor_info_update_cb_ = [this, self = this->shared_from_this()] (auto role, const auto& actor) { ASSERT(actor_info_update_cb_); actor_info_update_cb_(role, actor); }; role_->friend_intimacy_changed_cb_ = [this, self = this->shared_from_this()] (auto role, auto other, auto value) { ASSERT(change_friend_intimacy_func_); change_friend_intimacy_func_(other, role, value); }; role_->quest_update_func_ = [this, self = this->shared_from_this()] (auto role, const auto& quest) { // role login before sending login rsp if (!this->check_state_playing()) { return; } pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_quest_update_notice::squn); *notice->mutable_quest() = quest; this->send_to_client(msg); }; role_->forever_quest_update_func_ = [this, self = this->shared_from_this()] (auto role, const auto& quest, const auto& event_res) { // role login before sending login rsp if (!this->check_state_playing()) { return; } pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_quest_update_notice::squn); *notice->mutable_quest() = quest; *notice->mutable_event_res() = event_res; this->send_to_client(msg); }; role_->quest_auto_commit_func_ = [this, self = this->shared_from_this()] (auto role, auto quest_pttid) { auto result = quest_check_commit(quest_pttid, *self->role_); if (result != pd::OK) { return; } this->async_call( [this, self, quest_pttid, role] { SPLAYER_DLOG << "auto commit quset " << quest_pttid; if (!this->check_state_playing()) { return; } if (!role_->quest_has_accepted(quest_pttid)) { return; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_quest_commit_rsp::sqcr); rsp->set_pttid(quest_pttid); rsp->set_result(pd::OK); const auto& ptt = PTTS_GET(quest, quest_pttid); if (ptt.has__league_quest()) { auto lea = role_->get_quest_cur_pass_league_events(quest_pttid); league_quest_finish_notice_func_(role, quest_pttid, lea); role_->on_event(ECE_LEAGUE_QUEST_FINISH_TIMES, {}); } auto event_res = quest_commit(quest_pttid, *role_); *rsp->mutable_event_res() = event_res; db_log::instance().log_quest_commit(quest_pttid, event_res, *role_); this->send_to_client(rsp_msg); }); }; role_->levelup_cb_ = [this, self = this->shared_from_this()] (auto role, auto old_level, auto cur_level, const auto& event_res, auto has_mansion) { if (this->check_state_playing()) { pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_levelup_event_notice::srlen); *notice->mutable_event_res() = event_res; this->send_to_client(msg); } ASSERT(levelup_cb_); levelup_cb_(role, old_level, cur_level, has_mansion); for (auto i = old_level + 1; i <= cur_level; ++i) { const auto& levelup_ptt = PTTS_GET(role_levelup, i); if (levelup_ptt.has_mail()) { this->send_mail(levelup_ptt.mail(), pd::dynamic_data(), pd::event_array()); } } this->update_level_rank(); }; role_->update_db_func_ = [this, self = this->shared_from_this()] () { update_role_db(); }; role_->on_new_day_cb_ = [this, self = this->shared_from_this()] (const auto& event_res, const auto& battles) { pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_on_new_day::srond); *notice->mutable_event_res() = event_res; for(const auto& i : battles) { auto *bt = notice->add_battles(); bt->set_pttid(i.first); bt->set_battle_pttid(i.second); } this->send_to_client(msg); }; role_->arena_update_role_func_ = [this, self = this->shared_from_this()] (auto role, const auto& team) { ASSERT(arena_update_role_func_); arena_update_role_func_(role, team); }; role_->gongdou_sync_record_to_spouse_func_ = [this, self = this->shared_from_this()] (auto spouse, auto role, auto type, const auto& record) { ASSERT(gongdou_sync_record_to_spouse_func_); gongdou_sync_record_to_spouse_func_(spouse, role, type, record); }; role_->vip_exp_sync_to_spouse_func_ = [this, self = this->shared_from_this()] (auto spouse, auto role, auto vip_exp) { ASSERT(vip_exp_sync_to_spouse_func_); vip_exp_sync_to_spouse_func_(spouse, role, vip_exp); }; role_->gongdou_promote_guanpin_func_ = [this, self = this->shared_from_this()] (auto role, auto gpin, auto gongdou_data, const auto& event_res) { ASSERT(gongdou_promote_guanpin_func_); gongdou_promote_guanpin_func_(role, gpin, gongdou_data, event_res); }; role_->marriage_spouse_refresh_questions_func_ = [this, self = this->shared_from_this()] (auto role, auto spouse) { ASSERT(marriage_spouse_refresh_questions_func_); marriage_spouse_refresh_questions_func_(role, spouse); }; role_->marriage_sync_questions_func_ = [this, self = this->shared_from_this()] (const auto& questions) { pcs::base msg; auto *sync = msg.MutableExtension(pcs::s2c_marriage_update_questions::smuq); for (const auto& i : questions) { *sync->add_questions() = i; } this->send_to_client(msg); }; role_->marriage_sync_questions_to_spouse_func_ = [this, self = this->shared_from_this()] (auto role, auto spouse, const auto& questions) { ASSERT(marriage_sync_questions_to_spouse_func_); marriage_sync_questions_to_spouse_func_(role, spouse, questions); }; role_->mansion_add_hall_quest_func_ = [this, self = this->shared_from_this()] (auto role, const auto& quest, auto need_notice) { ASSERT(mansion_add_hall_quest_func_); mansion_add_hall_quest_func_(role, quest, need_notice); }; role_->gongdou_effect_changed_notice_ = [this, self = this->shared_from_this()] (auto role, const auto& extra_battle_data) { ASSERT(gongdou_effect_changed_notice_); gongdou_effect_changed_notice_(role, extra_battle_data); }; role_->guanpin_update_role_func_ = [this, self = this->shared_from_this()] (auto role, const auto& data) { ASSERT(guanpin_update_role_func_); guanpin_update_role_func_(role, data); }; role_->guanpin_changed_cb_ = [this, self = this->shared_from_this()] (auto role, auto old_gpin, auto new_gpin) { ASSERT(guanpin_changed_cb_); guanpin_changed_cb_(role, old_gpin, new_gpin); }; role_->role_add_new_record_notice_ = [this, self = this->shared_from_this()] (auto role, auto type, auto sub_type, const auto& record) { pcs::base msg; auto *notice = msg.MutableExtension(pcs::s2c_role_new_record_notice::srnrn); notice->set_type(type); notice->set_sub_type(sub_type); *notice->mutable_record() = record; this->send_to_client(msg); }; role_->broadcast_system_chat_func_ = [this, self = this->shared_from_this()] (auto role, auto pttid) { pd::dynamic_data dd; dd.add_name(gid2rolename_func_(role)); ASSERT(send_system_chat_func_); send_system_chat_func_(pttid, dd); this->mirror_broad_system_chat(pttid); }; role_->league_update_role_func_ = [this, self = this->shared_from_this()] (auto role, auto battle_team) { ASSERT(league_update_role_func_); league_update_role_func_(role, battle_team); }; role_->child_sync_actor_stars_func_ = [this, self = this->shared_from_this()] (auto role, const auto& data) { child_mgr::instance().sync_actor_stars(role, data); }; role_->send_mail_func_ = [this, self = this->shared_from_this()] (auto mail, const auto& events) { this->send_mail(mail, pd::dynamic_data(), events); }; role_->register_event(ECE_CHANGE_RESOURCE, [this, self = this->shared_from_this()] (const auto& args) { ASSERT(args.size() == 2); auto type = boost::any_cast<pd::resource_type>(args[0]); if (type == pd::resource_type::EXP) { this->update_level_rank(); } else if (type == pd::resource_type::GIVE_GIFT) { this->update_give_gift_rank(); } else if (type == pd::resource_type::RECEIVE_GIFT) { this->update_receive_gift_rank(); } else if (type == pd::resource_type::TEA_PARTY_FAVOR) { this->update_tea_party_favor(); } }); role_->register_event(ECE_ZHANLI_CHANGE, [this, self = this->shared_from_this()] (const auto& args) { this->update_zhanli_rank(); }); role_->register_event(ECE_MANSION_UPDATE_FANCY, [this, self = this->shared_from_this()] (const auto& args) { if (this->check_update_ranking_permit(pd::RT_MANSION_FANCY) == pd::OK) { ASSERT(update_mansion_fancy_rank_func_); update_mansion_fancy_rank_func_(role_->gid(), boost::any_cast<uint32_t>(args[0])); } }); role_->register_event(ECE_TOWER_NEW_HIGHEST_LEVEL, [this, self = this->shared_from_this()] (const auto& args) { if (this->check_update_ranking_permit(pd::RT_TOWER) == pd::OK) { ASSERT(update_tower_rank_func_); update_tower_rank_func_(role_->gid(), boost::any_cast<uint32_t>(args[0])); } }); role_->register_event(ECE_CHAOTANG_RANK_CHANGE, [this, self = this->shared_from_this()] (const auto& args) { if (this->check_update_ranking_permit(pd::RT_CHAOTANG) == pd::OK) { ASSERT(update_chaotang_rank_func_); update_chaotang_rank_func_(role_->gid(), boost::any_cast<int>(args[0]), boost::any_cast<int>(args[1])); } }); role_->register_event(ECE_RELATION_FRIEND_INTIMACY, [this, self = this->shared_from_this()] (const auto& args) { if (this->check_update_ranking_permit(pd::RT_MARRIAGE_DEVOTION) == pd::OK) { if (role_->marriage_married() && role_->marriage_proposer()) { ASSERT(update_marriage_devotion_rank_func_); update_marriage_devotion_rank_func_(role_->gid(), role_->marriage_spouse(), boost::any_cast<int>(args[0])); } } }); role_->register_event(ECE_MARRIAGE_PROPOSE, [this, self = this->shared_from_this()] (const auto& args) { this->update_marriage_devotion_rank(); }); if (online()) { if (role_->ban_until_time() >= system_clock::to_time_t(system_clock::now())) { pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(username_); rsp->set_result(pd::ROLE_IS_BANNED); send_to_client(msg); return false; } } if (mirror_role()) { role_->set_mirror_role(); SPLAYER_DLOG << *this << " update mirror role " << mirror_role_data_->gid(); ASSERT(mirror_role_data_); role_->mirror_update(*mirror_role_data_); } return true; } void fetch_data() { if (online()) { ASSERT(start_fetch_data_cb_); if (!start_fetch_data_cb_(this->shared_from_this())) { pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(username_); rsp->set_result(pd::AGAIN); send_to_client(msg, true); quit(); return; } fetching_data_count_ += 1; fetch_league_data_call_func( [this, self = this->shared_from_this()] (auto result, const auto& data) { SPLAYER_DLOG << *this << " got league data"; if (result == pd::OK) { login_league_data_ = make_unique<pd::league>(); *login_league_data_ = data.league_data(); role_->set_league_info(data.league_data()); for (auto i : data.bonus_cities()) { role_->add_bonus_city(i); } if (data.has_member_position()) { role_->set_league_member_position(data.member_position()); } auto president_gid = league_president_gid(data.league_data()); if (role_->get_league_member_position() == pd::LMP_PRESIDENT && president_gid != role_->gid()) { role_->set_league_member_position(pd::LMP_MEMBER); } if (this->mirror_role()) { if (president_gid == role_->gid()) { this->mirror_role_league_transfer_president(); } } } else { role_->clear_league_info(); } this->fetch_one_data_done(); }); fetching_data_count_ += 1; ASSERT(fetch_fief_data_func_); fetch_fief_data_func_(role_->gid(), role_->ip()); fetching_data_count_ += 1; ASSERT(fetch_mansion_data_func_); fetch_mansion_data_func_(role_->gid(), role_->level()); fetching_data_count_ += 1; ASSERT(fetch_marriage_data_func_); fetch_marriage_data_func_(role_->gid(), role_->marriage_married() ? role_->marriage_spouse() : 0); fetching_data_count_ += 1; ASSERT(fetch_arena_rank_func_); fetch_arena_rank_func_(role_->gid()); fetching_data_count_ += 1; huanzhuang_pvp::instance().fetch_data(role_->gid(), role_->gender()); fetching_data_count_ += 1; ASSERT(guanpin_fetch_data_func_); guanpin_fetch_data_func_(role_->gid()); fetching_data_count_ += 1; child_mgr::instance().fetch_children(role_->gid()); fetching_data_count_ += 1; activity_mgr::instance().fetch_data(role_->gid()); } else { this->async_call( [this, self = this->shared_from_this()] { event_fetch_data_done event; sm_->on_event(&event); }); } } bool login_done() { ASSERT(st_->check_in_thread()); ASSERT(login_done_cb_); if (!login_done_cb_(this->shared_from_this(), role_->name(), username())) { pcs::base msg; auto *rsp = msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(username_); rsp->set_result(pd::AGAIN); send_to_client(msg, true); return false; } if (online()) { role_->login(); role_->try_levelup(); const auto& ptts = PTTS_GET_ALL(resource); for (const auto& i : ptts) { if (i.second.grow_minutes() > 0) { role_->grow_resource(i.second.type()); add_resource_grow_timer(i.second.type()); } } if (!mirror_role()) { /*bi::instance().login(username(), yci_, ip_, role_->gid(), role_->league_gid(), role_->name(), role_->level(), role_->calc_max_zhanli(), role_->get_resource(pd::resource_type::EXP), role_->get_resource(pd::resource_type::DIAMOND), role_->get_resource(pd::resource_type::GOLD), pd::gender_Name(role_->gender()), role_->get_resource(pd::resource_type::VIP_EXP), role_->vip_level());*/ db_log::instance().log_login(*role_, ip_); pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_result(pd::OK); rsp->set_username(username_); role_->serialize_for_client(rsp->mutable_role()); auto emperor_effect = gongdou_emperor_favour_effect_func_(); if (system_clock::to_time_t(system_clock::now()) <= emperor_effect.start_time() + emperor_effect.last_time()) { *rsp->mutable_role()->mutable_gongdou()->add_effects() = emperor_effect; } rsp->set_seconds_west(clock::instance().seconds_west()); rsp->set_server_open_day(server_open_day_func_()); for(const auto& i : get_images_announcements_func_()) { *rsp->add_images_announcements() = i.first; } if (login_league_data_) { *rsp->mutable_league() = *login_league_data_; login_league_data_.reset(); } if (login_mansion_data_) { *rsp->mutable_mansion() = *login_mansion_data_; login_mansion_data_.reset(); } if (login_fief_data_) { *rsp->mutable_fief() = *login_fief_data_; login_fief_data_.reset(); } if (login_arena_champion_) { *rsp->mutable_arena_champion() = *login_arena_champion_; login_arena_champion_.reset(); } if (login_huanzhuang_pvp_) { *rsp->mutable_huanzhuang_pvp() = *login_huanzhuang_pvp_; login_huanzhuang_pvp_.reset(); } if (login_children_) { *rsp->mutable_children() = *login_children_; login_children_.reset(); } if (login_activity_mgr_) { *rsp->mutable_activity_mgr() = *login_activity_mgr_; login_activity_mgr_.reset(); } auto options_ptt = PTTS_GET_COPY(options, 1); if (options_ptt.scene_info().testin()) { rsp->set_testin(true); } rsp->set_skip_xinshou(options_ptt.scene_info().skip_xinshou()); send_to_client(rsp_msg); auto db_msg = make_shared<db::message>("find_notice", db::message::req_type::rt_select, [this, self = this->shared_from_this()] (const auto& msg) { this->handle_finished_db_msg(msg); }); db_msg->push_param(role_->gid()); gamedb_notice_->push_message(db_msg, st_); SPLAYER_DLOG << *this << " find notice"; recharge_day_bufa(); update_all_ranking(); behavior_tree_start(); activity_daiyanren_check_finish(); activity_seven_days_check_finish(); pd::role_mirror_event event; serialize_mirror_data(rsp_msg, &event); send_mirror_role_event_msg(event); if (role_->marriage_married()) { ASSERT(marriage_notice_spouse_login_func_); marriage_notice_spouse_login_func_(role_->gid(), role_->marriage_spouse()); } } else { update_all_ranking(); if (!mirror_role_data_->other_data().league().has_league_gid()) { role_mirror_event_try_join_league(); } mirror_role_data_.reset(); } update_role_db(); } return true; } void serialize_mirror_data(const pcs::base& msg, pd::role_mirror_event *mirror_event) { mirror_event->set_type(pd::RMET_LOGIN); mirror_event->set_gid(gid()); role_->serialize(mirror_event->mutable_role()); const auto& rsp = msg.GetExtension(pcs::s2c_login_rsp::slr); if (rsp.has_mansion()) { *mirror_event->mutable_mansion() = rsp.mansion(); } if (rsp.has_fief()) { *mirror_event->mutable_fief_data() = rsp.fief(); } } bool can_send_mirror_role_event_msg() { const auto& ptt = PTTS_GET(role_logic, 1); auto result = condition_check(ptt.mirror_unlock_conditions(), *role_); if (result == pd::OK) { return true; } else { return false; } } void send_mirror_role_event_msg(const pd::role_mirror_event& event) { if (!role_) { return; } ASSERT(st_->check_in_thread()); if (!can_send_mirror_role_event_msg()) { return; } switch (event.type()) { case pd::RMET_LOGIN: mirrored_ = true; break; default: break; } if (!mirrored_) { return; } ps::base msg; auto *notice = msg.MutableExtension(ps::sm_role_event::sre); *notice->mutable_event() = event; if (!event.has_gid()) { notice->mutable_event()->set_gid(gid()); } mirror_mgr::instance().random_send_msg(msg); } void fetch_one_data_done() { fetching_data_count_ -= 1; if (fetching_data_count_ <= 0) { SPLAYER_DLOG << *this << " fetch data done"; event_fetch_data_done event; sm_->on_event(&event); } } void fetch_league_data_call_func(const function<void(pd::result, const pd::league_for_role&)>& func) { if (fetch_league_data_call_funcs_.empty()) { fetch_league_data_call_funcs_.push_back(func); fetch_league_data_func_(role_->gid()); } else { fetch_league_data_call_funcs_.push_back(func); } } void fetch_league_list_call_func(const function<void(const list<pair<uint64_t, string>>&, const list<pair<uint64_t, string>>&)>& func) { ASSERT(get_league_list_func_); if (fetch_league_list_call_funcs_.empty()) { fetch_league_list_call_funcs_.push_back(func); get_league_list_func_(role_->gid()); } else { fetch_league_list_call_funcs_.push_back(func); } } void fetch_mansion_banquet_list_call_func(const function<void(const pd::mansion_banquets&)>& func) { if (fetch_mansion_banquet_list_call_funcs_.empty()) { const auto& friends = role_->relation_friends(); set<uint64_t> friends_set; for (const auto& i : friends) { friends_set.insert(i.first); } fetch_mansion_banquet_list_call_funcs_.push_back(func); mansion_fetch_banquet_list_func_(role_->gid(), friends_set); } else { fetch_mansion_banquet_list_call_funcs_.push_back(func); } } void fetch_room_list_call_func(const function<void(pd::result, pd::room_type, const pd::room_array&)>& func, pd::room_type room_type) { if (fetch_room_list_call_funcs_.empty()) { fetch_league_data_call_func( [this, func, room_type] (auto result, const auto& data) { set<uint64_t> friends_and_league; if (result == pd::OK) { friends_and_league = league_members(data.league_data()); } const auto& friends = role_->relation_friends(); for (auto i : friends) { friends_and_league.insert(i.first); } fetch_room_list_call_funcs_.push_back(func); room_mgr::instance().list_room(role_->gid(), room_type, friends_and_league); }); } else { fetch_room_list_call_funcs_.push_back(func); } } void fetch_room_info_call_func(const function<void(uint64_t, pd::result, const pd::room&)>& func, uint64_t room_keeper) { if (fetch_room_info_call_funcs_.empty()) { fetch_room_info_call_funcs_.push_back(func); room_mgr::instance().get_room_info_by_role(role_->gid(), room_keeper); } else { fetch_room_info_call_funcs_.push_back(func); } } void fetch_marriage_star_wish_list_call_func(const function<void(pd::result, const pd::marriage_star_wish_array&)>& func) { if (fetch_marriage_star_wish_list_call_funcs_.empty()) { fetch_marriage_star_wish_list_call_funcs_.push_back(func); ASSERT(marriage_star_wish_list_func_); marriage_star_wish_list_func_(role_->gid()); } else { fetch_marriage_star_wish_list_call_funcs_.push_back(func); } } void fetch_marriage_pk_list_call_func(const function<void(pd::result, const pd::marriage_pk_array&)>& func) { if (fetch_marriage_pk_list_call_funcs_.empty()) { fetch_marriage_pk_list_call_funcs_.push_back(func); ASSERT(marriage_pk_list_func_); marriage_pk_list_func_(role_->gid()); } else { fetch_marriage_pk_list_call_funcs_.push_back(func); } } void mirror_role_fief_action_list_call_func(uint64_t to_fief, const function<void()>& func) { if (mirror_role_ai_.fief_.entered_fief_ == to_fief) { func(); } else if (mirror_role_fief_action_list_call_funcs_[to_fief].empty()) { mirror_role_ai_.fief_.action_count_ += 1; mirror_role_fief_action_list_call_funcs_[to_fief].push_back(func); ASSERT(enter_fief_func_); enter_fief_func_(role_->gid(), to_fief); } else { mirror_role_ai_.fief_.action_count_ += 1; mirror_role_fief_action_list_call_funcs_[to_fief].push_back(func); } } void mirror_role_mansion_action_list_call_func(uint64_t to_mansion, pd::mansion_building_type building_type, const function<void()>& func) { if (mirror_role_ai_.mansion_.entered_mansion_ == to_mansion) { func(); } else if (mirror_role_mansion_action_list_call_funcs_[to_mansion].empty()) { mirror_role_ai_.mansion_.gid2action_count_[to_mansion] += 1; mirror_role_mansion_action_list_call_funcs_[to_mansion].push_back(func); ASSERT(enter_mansion_func_); auto is_friend = role_->gid() == to_mansion || role_->relation_has_friend(to_mansion); enter_mansion_func_(role_->gid(), to_mansion, building_type, is_friend, mansion_random_plot(to_mansion, building_type, *role_)); } else { mirror_role_ai_.mansion_.gid2action_count_[to_mansion] += 1; mirror_role_mansion_action_list_call_funcs_[to_mansion].push_back(func); } } void login_no_role() { if (!mirror_role()) { pcs::base msg; auto rsp = msg.MutableExtension(pcs::s2c_login_rsp::slr); rsp->set_username(username_); rsp->set_result(pd::NOT_FOUND); send_to_client(msg); } else { ASSERT(mirror_role_data_); SPLAYER_DLOG << *this << " create mirror role " << mirror_role_data_->gid(); ASSERT(random_role_name_func_); mirror_role_data_->mutable_data()->set_name(random_role_name_func_(MIRROR_NAME_POOL_START)); create_role(*mirror_role_data_); } } void update_role_db() { pd::role data; if (role_ && role_->serialize_changed_data(&data)) { role_->reset_data_changed(); auto msg = dbcache::gen_update_role_req(data); dbcache::instance().send_to_dbcached(msg); } } void notice_set_already_read(uint64_t gid) { auto msg = make_shared<db::message>("notice_set_already_read", db::message::req_type::rt_update, [this, self = this->shared_from_this()] (const auto& msg) { this->handle_finished_db_msg(msg); }); msg->push_param(gid); msg->push_param(role_->gid()); msg->push_param(1); gamedb_notice_->push_message(msg, st_); } void notice_delete(uint64_t gid) { auto msg = make_shared<db::message>("delete_notice", db::message::req_type::rt_delete); msg->push_param(gid); msg->push_param(role_->gid()); gamedb_notice_->push_message(msg); } void add_mirror_timer(uint32_t delay, const function<void()>& cb) { ASSERT(st_->check_in_thread()); if (!check_state_playing()) { return; } auto timer = ADD_TIMER(st_, ([this, self = this->shared_from_this(), cb] (auto canceled, const auto& timer) { if (!canceled) { mirror_timers_.erase(timer); cb(); } }), seconds(delay)); mirror_timers_.emplace(timer); } bool try_exec_chat_gm(string& content) { if (content.find("\\gm ") == 0 && content.size() > 4) { content = content.substr(4); auto tokens = split_string(content); if (!tokens.empty()) { SPLAYER_DLOG << *this << " chat gm:"; for (const auto& i : tokens) { SPLAYER_DLOG << i; } static map<string, string> fief_event_type { { "FET_ADD_RESOURCE", "ADD_RESOURCE" }, { "FET_DEC_RESOURCE", "DEC_RESOURCE" }, { "FET_INCIDENT_EXTRA_WEIGHT", "INCIDENT_EXTRA_WEIGHT" }, }; pd::event::event_type type; pd::league_event_type league_type; pd::fief_event::fief_event_type fief_type; if (pd::event::event_type_Parse(tokens[0], &type)) { exec_chat_gm_events(tokens); } else if (pd::league_event_type_Parse(tokens[0], &league_type)) { exec_chat_gm_league_events(tokens); } else if (fief_event_type.count(tokens[0]) > 0) { tokens[0] = fief_event_type.at(tokens[0]); if (pd::fief_event::fief_event_type_Parse(tokens[0], &fief_type)) { exec_chat_gm_fief_events(tokens); } } else { exec_chat_gm_commands(tokens); } } return true; } return false; } void exec_chat_gm_league_events(const vector<string>& tokens) { pd::league_event_type type; pd::league_event_type_Parse(tokens[0], &type); pd::league_event_array lea; auto *e = lea.add_events(); e->set_type(type); for (auto i = 1ul; i < tokens.size(); ++i) { e->add_arg(tokens[i]); } if (config::check_league_events(lea)) { league_gm_process_event_func_(role_->gid(), lea); } } void exec_chat_gm_fief_events(const vector<string>& tokens) { pd::fief_event::fief_event_type type; pd::fief_event::fief_event_type_Parse(tokens[0], &type); pd::fief_event_array fea; auto *e = fea.add_events(); e->set_type(type); for (auto i = 1ul; i < tokens.size(); ++i) { e->add_arg(tokens[i]); } if (config::check_fief_events(fea)) { fief_gm_process_event_func_(role_->gid(), fea); } } void exec_chat_gm_events(const vector<string>& tokens) { pd::event::event_type type; pd::event::event_type_Parse(tokens[0], &type); pd::event_array ea; auto *e = ea.add_events(); e->set_type(type); for (auto i = 1ul; i < tokens.size(); ++i) { e->add_arg(tokens[i]); } if (config::check_events(ea) && config::verify_events(ea)) { pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_gm_exec_event_rsp::sgeer); pd::ce_env ce; ce.set_origin(pd::CO_CHAT_GM); auto event_res = event_process(ea, *role_, ce); *rsp->mutable_res_array()->add_event_reses() = event_res; send_to_client(rsp_msg); db_log::instance().log_exec_gm(ea, rsp->res_array(), *role_, 0); role_->try_levelup(); } } void exec_chat_gm_commands(const vector<string>& tokens) { auto result = pd::OK; if (tokens[0] == "ADD_MIN") { if (tokens.size() == 2) { auto min = stoi(tokens[1]); if (min <= 0 || !add_min(min)) { result = pd::INTERNAL_ERROR; } } } else if (tokens[0] == "ADD_HOUR") { if (tokens.size() == 2) { auto hour = stoi(tokens[1]); if (hour <= 0 || !add_hour(hour)) { result = pd::INTERNAL_ERROR; } } } else if (tokens[0] == "SEND_MAIL") { if (tokens.size() == 2) { send_mail(stoul(tokens[1]), pd::dynamic_data(), pd::event_array()); } } else if (tokens[0] == "AI") { if (tokens.size() == 2) { auto token = stoi(tokens[1]); if (token == 0) { ai_set_active(false); } else if (token == 1) { ai_set_active(true); } } } else if (tokens[0] == "PASS_XINSHOU_GROUP") { if (tokens.size() == 2) { auto group_pttid = stoul(tokens[1]); if (PTTS_HAS(xinshou_group, group_pttid)) { const auto& ptts = PTTS_GET_ALL(xinshou_group); for (const auto& i : ptts) { if (i.first <= group_pttid) { role_->xinshou_add_passed_group(i.first); } } } } } else if (tokens[0] == "EXEC_GM") { if (tokens.size() == 2) { ASSERT(PTTS_HAS(gm_data, stoul(tokens[1]))); pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_gm_exec_event_rsp::sgeer); pd::ce_env ce; ce.set_origin(pd::CO_CHAT_GM); const auto& ptt = PTTS_GET(gm_data, stoul(tokens[1])); for (const auto& i : ptt.events().events()) { pd::event_array ea; *ea.add_events() = i; auto event_res = event_process(ea, *role_, ce); *rsp->mutable_res_array()->add_event_reses() = event_res; } send_to_client(rsp_msg); db_log::instance().log_exec_gm(pd::event_array(), rsp->res_array(), *role_, ptt.id()); } } else if (tokens[0] == "EXEC_GM_SEQ") { if (tokens.size() == 2) { ASSERT(PTTS_HAS(gm_sequence, stoul(tokens[1]))); pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_gm_exec_event_rsp::sgeer); pd::ce_env ce; ce.set_origin(pd::CO_CHAT_GM); const auto& ptt = PTTS_GET(gm_sequence, stoul(tokens[1])); for (auto i : ptt.sequences()) { const auto& gm_ptt = PTTS_GET(gm_data, i); for (const auto& i : gm_ptt.events().events()) { pd::event_array ea; *ea.add_events() = i; auto event_res = event_process(ea, *role_, ce); *rsp->mutable_res_array()->add_event_reses() = event_res; } } send_to_client(rsp_msg); db_log::instance().log_exec_gm(pd::event_array(), rsp->res_array(), *role_, ptt.id()); } } else if (tokens[0] == "ADD_FIEF_INCIDENT") { if (tokens.size() == 1) { fief_add_incident_func_(role_->gid(), 0u); } else if (tokens.size() == 2) { ASSERT(PTTS_HAS(fief_incident, stoul(tokens[1]))); fief_add_incident_func_(role_->gid(), stoul(tokens[1])); } } else if (tokens[0] == "SET_GPIN") { if (tokens.size() == 2) { auto battle_team = role_->battle_team(pd::BOT_GUANPIN, true); guanpin_set_gpin_func_(role_->gid(), battle_team, stoi(tokens[1])); } } else if (tokens[0] == "SET_QUEST") { if (tokens.size() == 3) { ASSERT(PTTS_HAS(quest, stoul(tokens[1]))); ASSERT(stoul(tokens[2]) > 0u); role_->exec_chat_gm_pass_quest(stoul(tokens[1]), stoul(tokens[2])); } } else if (tokens[0] == "ADD_MANSION_HALL_QUEST") { if (tokens.size() == 2) { ASSERT(PTTS_HAS(mansion_hall_quest, stoul(tokens[1]))); role_->mansion_add_hall_quest(stoul(tokens[1])); } } else if (tokens[0] == "ADD_RANDOM_SEED") { if (tokens.size() >= 2) { for (size_t i = 1; i < tokens.size(); ++i) { random_seeds::instance().push(stoul(tokens[i])); } } } else if (tokens[0] == "CLEAR_RANDOM_SEED") { if (tokens.size() == 1) { random_seeds::instance().clear(); } } else if (tokens[0] == "SET_TOWER_HIGHEST_LEVEL") { if (tokens.size() == 2) { auto level = stoul(tokens[1]); role_->tower_set_highest_level(level); role_->on_event(ECE_TOWER_NEW_HIGHEST_LEVEL, { level }); } } else if (tokens[0] == "SET_TOWER_CUR_LEVEL") { if (tokens.size() == 2) { auto level = stoul(tokens[1]); role_->tower_set_cur_level(level); if (role_->tower_highest_level() < level) { role_->tower_set_highest_level(level); role_->on_event(ECE_TOWER_NEW_HIGHEST_LEVEL, { level }); } } } else if (tokens[0] == "RESET_FEIGE") { role_->reset_feige(); } else if (tokens[0] == "RECHARGE") { ASSERT(tokens.size() == 2); auto pttid = stoul(tokens[1]); auto order = role_->add_recharge_order(pttid); const auto& ptt = PTTS_GET(recharge, pttid); yunying_recharge(0, 0, order, "", "RMB", ptt.price(), system_clock::to_time_t(system_clock::now()), "", true); } else if (tokens[0] == "REBATE") { ASSERT(tokens.size() >= 2); map<uint32_t, uint32_t> recharge2count; for (auto i = 1u; i < tokens.size(); ++i) { const auto& token = split_string(tokens[i], ','); ASSERT(token.size() == 2); if (recharge2count.count(stoul(token[0]) > 0)) { recharge2count[stoul(token[0])] += stoul(token[1]); } else { recharge2count[stoul(token[0])] = stoul(token[1]); } } pd::event_array events; for (const auto& i : recharge2count) { event_merge(events, rebate_events(i.first, i.second)); } send_mail(2000, pd::dynamic_data(), events); } else if (tokens[0] == "ACTIVITY_PRIZE_WHEEL_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_prize_wheel(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_DISCOUNT_GOODS_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_discount_goods(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_CONTINUE_RECHARGE_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_continue_recharge(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_LIMIT_PLAY_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_limit_play(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_LEIJI_RECHARGE_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_leiji_recharge(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_LEIJI_CONSUME_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_leiji_consume(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_FESTIVAL_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_festival(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_PRIZE_WHEEL_STOP") { ASSERT(tokens.size() == 1); activity_mgr::instance().stop_prize_wheel(0, 0); } else if (tokens[0] == "ACTIVITY_DISCOUNT_GOODS_STOP") { ASSERT(tokens.size() == 1); activity_mgr::instance().stop_discount_goods(0, 0); } else if (tokens[0] == "ACTIVITY_CONTINUE_RECHARGE_STOP") { ASSERT(tokens.size() == 2); auto pttid = stoul(tokens[1]); activity_mgr::instance().stop_continue_recharge(0, 0, pttid); } else if (tokens[0] == "ACTIVITY_LIMIT_PLAY_STOP") { ASSERT(tokens.size() == 2); auto pttid = stoul(tokens[1]); activity_mgr::instance().stop_limit_play(0, 0, pttid); } else if (tokens[0] == "ACTIVITY_LEIJI_RECHARGE_STOP") { ASSERT(tokens.size() == 2); auto pttid = stoul(tokens[1]); activity_mgr::instance().stop_leiji_recharge(0, 0, pttid); } else if (tokens[0] == "ACTIVITY_LEIJI_CONSUME_STOP") { ASSERT(tokens.size() == 2); auto pttid = stoul(tokens[1]); activity_mgr::instance().stop_leiji_consume(0, 0, pttid); } else if (tokens[0] == "ACTIVITY_TEA_PARTY_START") { ASSERT(tokens.size() == 3); auto pttid = stoul(tokens[1]); auto duration = stoul(tokens[2]); activity_mgr::instance().start_tea_party(0, 0, refresh_day(), duration, pttid); } else if (tokens[0] == "ACTIVITY_TEA_PARTY_STOP") { ASSERT(tokens.size() == 1); activity_mgr::instance().stop_tea_party(0, 0); } else if (tokens[0] == "ACTIVITY_FESTIVAL_STOP") { ASSERT(tokens.size() == 2); auto pttid = stoul(tokens[1]); activity_mgr::instance().stop_festival(0, 0, pttid); } else if (tokens[0] == "ACTIVITY_RECHARGE_RANK_START") { ASSERT(tokens.size() == 2); auto duration = stoul(tokens[1]); activity_mgr::instance().start_recharge_rank(0, 0, refresh_day(), duration); } else if (tokens[0] == "ACTIVITY_RECHARGE_RANK_STOP") { ASSERT(tokens.size() == 1); activity_mgr::instance().stop_recharge_rank(0, 0); } else { result = pd::NOT_FOUND; } pcs::base rsp_msg; auto *rsp = rsp_msg.MutableExtension(pcs::s2c_gm_exec_command_rsp::sgecr); rsp->set_result(result); send_to_client(rsp_msg); } void update_all_ranking() { update_level_rank(); update_give_gift_rank(); update_receive_gift_rank(); update_zhanli_rank(); update_chaotang_rank(); update_marriage_devotion_rank(); update_tea_party_favor(); update_tower_rank(); } void update_level_rank() { if (check_update_ranking_permit(pd::RT_LEVEL) == pd::OK) { update_level_rank_func_(role_->gid(), role_->level(), role_->get_resource(pd::resource_type::EXP)); } } void update_give_gift_rank() { if (check_update_ranking_permit(pd::RT_GIVE_GIFT) == pd::OK) { update_give_gift_rank_func_(role_->gid(), role_->get_resource(pd::resource_type::GIVE_GIFT)); } } void update_receive_gift_rank() { if (check_update_ranking_permit(pd::RT_RECEIVE_GIFT) == pd::OK) { update_receive_gift_rank_func_(role_->gid(), role_->get_resource(pd::resource_type::RECEIVE_GIFT)); } } void update_zhanli_rank() { if (check_update_ranking_permit(pd::RT_ZHANLI) == pd::OK) { update_zhanli_rank_func_(role_->gid(), role_->calc_max_zhanli()); } } void update_tower_rank() { if (check_update_ranking_permit(pd::RT_TOWER) == pd::OK) { update_tower_rank_func_(role_->gid(), role_->tower_highest_level()); } } void update_chaotang_rank() { if (check_update_ranking_permit(pd::RT_CHAOTANG) == pd::OK) { if (role_->guanpin_gpin() != 0){ update_chaotang_rank_func_(role_->gid(), role_->guanpin_gpin(), numeric_limits<int>::max() - role_->guanpin_idx()); } } } void update_marriage_devotion_rank() { if (check_update_ranking_permit(pd::RT_MARRIAGE_DEVOTION) == pd::OK) { if (role_->marriage_married() && role_->marriage_proposer()) { update_marriage_devotion_rank_func_(role_->gid(), role_->marriage_spouse(), role_->relation_friend_intimacy(role_->marriage_spouse())); } } } void update_tea_party_favor() { if (check_update_ranking_permit(pd::RT_TEA_PARTY_FAVOR) == pd::OK) { update_tea_party_favor_func_(role_->gid(), role_->get_resource(pd::resource_type::TEA_PARTY_FAVOR)); } } void set_player_in_multiplayer_game(bool state) { multiplayer_game_ = state; } bool check_player_in_multiplayer_game() { if (multiplayer_game_) { return true; } return false; } void behavior_tree_start() { if (ai_.robot_role_) { SPLAYER_TLOG << "set behavior_tree_root: " << ai_.behavior_children_node_; if (PTTS_HAS(behavior_tree, ai_.behavior_children_node_)) { set_cur_root(ai_.behavior_children_node_); } ai_set_active(true); } } void reset_cur_mansion_game() { cur_mansion_game_.type_ = pd::MGT_NONE; cur_mansion_game_.free_extra_fishing_ = false; } string username_; string origin_username_; uint32_t server_id_ = 0; shared_ptr<role> role_; shared_ptr<service_thread> st_; shared_ptr<net::server<T>> nsv_; shared_ptr<T> conn_; shared_ptr<db::connector> gamedb_notice_; shared_ptr<state_machine<player<T>>> sm_; shared_ptr<behavior_tree<player<T>>> bt_; string ip_; pd::yunying_client_info yci_; int fetching_data_count_ = 0; atomic<int> async_call_count_{0}; map<pd::resource_type, shared_ptr<timer_type>> resource_grow_timer_; set<shared_ptr<timer_type>> mirror_timers_; shared_ptr<timer_type> rand_quit_timer_; struct { struct { queue<uint64_t> game_invitations_; pd::mansion_game_type game_ = pd::MGT_NONE; struct { uint32_t play_times_ = 0; bool took_bait_ = false; } fishing_; struct { struct { uint32_t pttid_ = 0; pd::pttid_array celebrities_; pd::time_point open_time_; bool allow_stranger_ = false; } host_info_; list<pd::mansion_banquet> hosted_; map<uint64_t, pd::mansion_banquet> reserved_; uint64_t mansion_ = 0; uint32_t pttid_ = 0; uint64_t spouse_ = 0; pd::mansion_building_type building_; bool dish_ = false; uint32_t riddle_ = 0; pd::mansion_building_type riddle_building_ = pd::MBT_NONE; map<pd::mansion_building_type, pd::mansion_banquet_riddle_box> riddle_boxes_; uint32_t question_ = 0; uint32_t thief_ = 0; pd::mansion_building_type thief_building_ = pd::MBT_NONE; map<uint32_t, pcs::mansion_banquet_celebrity> celebrities_; set<uint32_t> celebrities_challenged_; bool coins_ = false; uint32 coin_stage_level_ = 0; bool vote_bedroom_tool_ = false; } banquet_; } mansion_; struct { pd::fief_area_incident area_incident_; uint64_t enter_fief_role_ = 0; } fief_incident_; struct { pd::league_for_role data_; uint32_t refresh_time_ = 0; } league_cache_; struct { uint32_t update_day_ = 0; } huanzhuang_pvp_; system_clock::time_point last_chat_time_; struct { map<uint32_t, set<uint32_t>> unlock_options_; } plot_; struct { bool started_qiu_qian_ = false; bool qiu_qian_started_by_spouse_ = false; bool qiu_qianing_ = false; uint32_t star_wish_start_time_ = 0; uint64_t star_wish_target_ = 0; uint32_t pk_start_time_ = 0; uint64_t pk_target_ = 0; } marriage_; bool robot_role_ = false; uint32_t behavior_children_node_; } ai_; unique_ptr<pd::league> login_league_data_; unique_ptr<pd::mansion> login_mansion_data_; unique_ptr<pd::fief> login_fief_data_; unique_ptr<pcs::gladiator> login_arena_champion_; unique_ptr<pd::huanzhuang_pvp_data> login_huanzhuang_pvp_; unique_ptr<pd::child_array> login_children_; unique_ptr<pd::activity_mgr> login_activity_mgr_; bool multiplayer_game_ = false; bool mirrored_ = false; bool quiting_playing_ = false; bool mirror_role_ = false; bool online_ = false; struct { pd::mansion_game_type type_ = pd::MGT_NONE; bool free_extra_fishing_ = false; } cur_mansion_game_; unique_ptr<pd::role> mirror_role_data_; struct { struct { pd::role_mirror_event_type action_type_; uint64_t entered_mansion_ = 0; map<uint64_t, int> gid2action_count_; struct { map<uint64_t, pd::mansion_banquet> gid2banquets_; struct { uint64_t mansion_gid_ = 0; pd::mansion_banquet_stage current_stage_ = pd::MBS_NONE; uint32_t question_ = 0; map<pd::mansion_building_type, pd::mansion_banquet_riddle_box> riddle_boxes_; int challenged_thief_idxs_ = 0; pd::mansion_banquet_thieves thieves_; map<uint32_t, pcs::mansion_banquet_celebrity> celebrities_; pd::mansion_banquet_pintu_game pintu_games_; vector<pd::mansion_banquet_weilie_game> weilie_game_; } live_; } banquet_; struct { int fetching_farm_count_ = 0; map<uint64_t, pd::mansion_farm> gid2farms_; } farm_; } mansion_; struct { uint64_t entered_fief_ = 0; int action_count_ = 0; } fief_; } mirror_role_ai_; static map<pd::player_action_type, function<pd::result(player<T> *, pd::behavior_tree_node&)>> ai_action_handlers_; static map<pd::player_condition_type, function<pd::result(player<T> *, pd::behavior_tree_node&)>> ai_condition_handlers_; vector<function<void(pd::result, const pd::league_for_role&)>> fetch_league_data_call_funcs_; vector<function<void(const list<pair<uint64_t, string>>&, const list<pair<uint64_t, string>>&)>> fetch_league_list_call_funcs_; vector<function<void(const pd::mansion_banquets&)>> fetch_mansion_banquet_list_call_funcs_; vector<function<void(pd::result, pd::room_type, const pd::room_array&)> > fetch_room_list_call_funcs_; vector<function<void(uint64_t, pd::result, const pd::room&)>> fetch_room_info_call_funcs_; vector<function<void(pd::result, const pd::marriage_star_wish_array&)>> fetch_marriage_star_wish_list_call_funcs_; vector<function<void(pd::result, const pd::marriage_pk_array&)>> fetch_marriage_pk_list_call_funcs_; map<uint64_t, vector<function<void()>>> mirror_role_fief_action_list_call_funcs_; map<uint64_t, vector<function<void()>>> mirror_role_mansion_action_list_call_funcs_; }; template <typename T> map<pd::player_action_type, function<pd::result(player<T> *, pd::behavior_tree_node&)>> player<T>::ai_action_handlers_; template <typename T> map<pd::player_condition_type, function<pd::result(player<T> *, pd::behavior_tree_node&)>> player<T>::ai_condition_handlers_; } }
#pragma once #include <iberbar/Utility/Ref.h> #include <iberbar/Utility/Rect.h> #include <iberbar/Utility/Clonable.h> #include <vector> namespace iberbar { class CTransform2D; IBERBAR_UNKNOWN_PTR_DECLARE( CTransform2D ); class __iberbarUtilityApi__ CTransform2D : public CRef, public IClonable { protected: typedef std::vector< PTR_CTransform2D > Array_Transfrom2D; public: CTransform2D(); virtual ~CTransform2D() override; virtual CTransform2D* Clone() const override; protected: CTransform2D( const CTransform2D& trans ); public: void SetPosition( const CPoint2i& pt ) { m_Position = pt; UpdateTransform(); } void SetSize( const CSize2i& size ) { m_Size = size; UpdateTransform(); } void SetPaddings( const CRect2i& Paddings ) { m_Paddings = Paddings; UpdateTransform(); } void SetAlignHorizental( UAlignHorizental nAlign ) { m_alignHorizental = nAlign; UpdateTransform(); } void SetAlignVertical( UAlignVertical nAlign ) { m_alignVertical = nAlign; UpdateTransform(); } void SetPercentX( bool bValue ) { m_bPercentX = bValue; UpdateTransform(); } void SetPercentY( bool bValue ) { m_bPercentY = bValue; UpdateTransform(); } void SetPercentW( bool bValue ) { m_bPercentW = bValue; UpdateTransform(); } void SetPercentH( bool bValue ) { m_bPercentH = bValue; UpdateTransform(); } void SetParentTransform( CTransform2D* parent ); void UpdateTransform(); void LockChildTransforms() { m_bLockChildTransforms = true; } void UnlockChildTransforms() { m_bLockChildTransforms = false; } public: const CPoint2i& GetPosition() const { return m_Position; } int GetPositionX() const { return m_Position.x; } int GetPositionY() const { return m_Position.y; } const CSize2i& GetSize() const { return m_Size; } const CRect2i& GetPaddings() const { return m_Paddings; } CTransform2D* GetParentTransform() const { return m_ParentTransform; } UAlignHorizental GetAlignHorizental() const { return m_alignHorizental; } UAlignVertical GetAlignVertical() const { return m_alignVertical; } const CRect2i& GetBounding() const { return m_rcBounding; } bool HitTest( const CPoint2i& point ) const { return RectPointHitTest( &GetBounding(), &point ); } private: bool m_bPercentX : 1; bool m_bPercentY : 1; bool m_bPercentW : 1; bool m_bPercentH : 1; bool m_bLockChildTransforms; UAlignStyle m_alignStyle; UAlignHorizental m_alignHorizental; UAlignVertical m_alignVertical; CPoint2i m_Position; CSize2i m_Size; CRect2i m_Paddings; CTransform2D* m_ParentTransform; // do not add reference CRect2i m_rcBounding; Array_Transfrom2D m_ChildTransformArray; // add reference +1 }; __iberbarExportTemplateRef( __iberbarUtilityApi__, CTransform2D ); //template class __iberbarUtilityApi__ std::allocator<PTR_CTransform2D>; //template class __iberbarUtilityApi__ std::vector<PTR_CTransform2D, std::allocator<PTR_CTransform2D>>; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef QUICK_BINDER_SELECTABLE_H #define QUICK_BINDER_SELECTABLE_H #include "adjunct/quick_toolkit/bindings/QuickBinder.h" #include "modules/widgets/OpWidget.h" class QuickSelectable; /** * A base class of (potentially) bidirectional bindings for the state of * a QuickSelectable. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class QuickBinder::QuickSelectableBinding : public QuickBinder::Binding , public OpWidgetListener { public: // Binding virtual const QuickWidget* GetBoundWidget() const; // OpWidgetListener virtual void OnChange(OpWidget* widget, BOOL by_mouse = FALSE); protected: QuickSelectableBinding(); virtual ~QuickSelectableBinding(); OP_STATUS Init(QuickSelectable& selectable); OP_STATUS ToWidget(bool new_value); virtual OP_STATUS FromWidget(bool new_value) = 0; private: QuickSelectable* m_selectable; }; /** * A bidirectional binding for the state of a QuickSelectable. * * The "selected" state of a QuickSelectable is bound to a boolean OpProperty. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class QuickBinder::QuickSelectablePropertyBinding : public QuickSelectableBinding { public: QuickSelectablePropertyBinding(); virtual ~QuickSelectablePropertyBinding(); OP_STATUS Init(QuickSelectable& selectable, OpProperty<bool>& property); void OnPropertyChanged(bool new_value); protected: // QuickSelectableBinding virtual OP_STATUS FromWidget(bool new_value); private: OpProperty<bool>* m_property; }; /** * A unidirectional preference binding for the state of a QuickSelectable. * * The "selected" state of a QuickSelectable is automatically written to an * integer preference. * * @author Wojciech Dzierzanowski (wdzierzanowski) */ class QuickBinder::QuickSelectablePreferenceBinding : public QuickSelectableBinding { public: QuickSelectablePreferenceBinding(); virtual ~QuickSelectablePreferenceBinding(); OP_STATUS Init(QuickSelectable& selectable, PrefUtils::IntegerAccessor* accessor, int selected, int deselected); protected: // QuickSelectableBinding virtual OP_STATUS FromWidget(bool new_value); private: PrefUtils::IntegerAccessor* m_accessor; int m_selected; int m_deselected; }; #endif // QUICK_BINDER_SELECTABLE_H
#include "magic_wand_model_data.h" // We need to keep the data array aligned on some architectures. #ifdef __has_attribute #define HAVE_ATTRIBUTE(x) __has_attribute(x) #else #define HAVE_ATTRIBUTE(x) 0 #endif #if HAVE_ATTRIBUTE(aligned) || (defined(__GNUC__) && !defined(__clang__)) #define DATA_ALIGN_ATTRIBUTE __attribute__((aligned(4))) #else #define DATA_ALIGN_ATTRIBUTE #endif const unsigned char g_magic_wand_model_data[] DATA_ALIGN_ATTRIBUTE = { // Paste the data of the char array in `src/model.cc` here 0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c, 0x33, 0x00, 0x00, 0x12, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x18, 0x00, 0x12, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x24, 0x30, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x54, 0x4f, 0x43, 0x4f, 0x20, 0x43, 0x6f, 0x6e, 0x76, 0x65, 0x72, 0x74, 0x65, 0x64, 0x2e, 0x00, 0x12, 0x00, 0x00, 0x00, 0xb0, 0x00, 0x00, 0x00, 0xa4, 0x00, 0x00, 0x00, 0x98, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x74, 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6e, 0xd2, 0xff, 0xff, 0x68, 0x00, 0x00, 0x00, 0x30, 0xd2, 0xff, 0xff, 0x34, 0xd2, 0xff, 0xff, 0x7e, 0xd2, 0xff, 0xff, 0xf0, 0x01, 0x00, 0x00, 0x86, 0xd2, 0xff, 0xff, 0xc8, 0x03, 0x00, 0x00, 0x48, 0xd2, 0xff, 0xff, 0x4c, 0xd2, 0xff, 0xff, 0x50, 0xd2, 0xff, 0xff, 0x54, 0xd2, 0xff, 0xff, 0x58, 0xd2, 0xff, 0xff, 0x5c, 0xd2, 0xff, 0xff, 0xa6, 0xd2, 0xff, 0xff, 0xc0, 0x0d, 0x00, 0x00, 0xae, 0xd2, 0xff, 0xff, 0x00, 0x2a, 0x00, 0x00, 0xb6, 0xd2, 0xff, 0xff, 0x60, 0x2a, 0x00, 0x00, 0xbe, 0xd2, 0xff, 0xff, 0xe0, 0x2a, 0x00, 0x00, 0xc6, 0xd2, 0xff, 0xff, 0x48, 0x2b, 0x00, 0x00, 0xce, 0xd2, 0xff, 0xff, 0x98, 0x2c, 0x00, 0x00, 0x90, 0xd2, 0xff, 0xff, 0x05, 0x00, 0x00, 0x00, 0x31, 0x2e, 0x35, 0x2e, 0x30, 0x00, 0x00, 0x00, 0x54, 0xf4, 0xff, 0xff, 0x08, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x6d, 0x69, 0x6e, 0x5f, 0x72, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x00, 0x0c, 0x00, 0x14, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x88, 0x2c, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x9c, 0x0c, 0x00, 0x00, 0x14, 0x0b, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, 0x24, 0x29, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0xa4, 0x02, 0x00, 0x00, 0x80, 0x29, 0x00, 0x00, 0x5c, 0x0b, 0x00, 0x00, 0xb0, 0x0c, 0x00, 0x00, 0xc4, 0x2b, 0x00, 0x00, 0xf0, 0x0b, 0x00, 0x00, 0x2c, 0x0c, 0x00, 0x00, 0x48, 0x2a, 0x00, 0x00, 0xec, 0x29, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x88, 0x0b, 0x00, 0x00, 0x66, 0xd4, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x6f, 0x6f, 0x6c, 0x69, 0x6e, 0x67, 0x32, 0x64, 0x2f, 0x4d, 0x61, 0x78, 0x50, 0x6f, 0x6f, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x88, 0xd3, 0xff, 0xff, 0xba, 0xd4, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x2f, 0x52, 0x65, 0x6c, 0x75, 0x00, 0x00, 0xd0, 0xd3, 0xff, 0xff, 0x02, 0xd5, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x2f, 0x43, 0x6f, 0x6e, 0x76, 0x32, 0x44, 0x2f, 0x52, 0x65, 0x61, 0x64, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x4f, 0x70, 0x00, 0x28, 0xd4, 0xff, 0xff, 0x80, 0x01, 0x00, 0x00, 0x49, 0x02, 0xc2, 0x3d, 0x09, 0x12, 0xc8, 0xbd, 0x35, 0x79, 0x0a, 0x3d, 0x34, 0x34, 0xb0, 0x3c, 0x2b, 0xb3, 0xe3, 0x3d, 0x15, 0x71, 0xc0, 0x3c, 0x33, 0x03, 0x98, 0x3e, 0xcc, 0x89, 0x92, 0xbc, 0xe7, 0x77, 0x46, 0xbb, 0x20, 0xdb, 0x54, 0xbe, 0x95, 0x06, 0xc2, 0xbd, 0xb8, 0x79, 0x06, 0x3e, 0xee, 0xe7, 0x9d, 0x3d, 0x15, 0x63, 0x04, 0x3e, 0x9c, 0x69, 0xa6, 0x3e, 0x53, 0xde, 0x21, 0xbe, 0x97, 0x9f, 0xd2, 0xbd, 0xf2, 0x99, 0x53, 0xbe, 0xf2, 0x1f, 0x07, 0xbc, 0xd8, 0x4f, 0x75, 0xbe, 0x19, 0x64, 0x0d, 0xbd, 0x8d, 0x96, 0xf3, 0xbe, 0xe6, 0x88, 0x1a, 0x3e, 0x6d, 0x2c, 0x0d, 0x3e, 0x4e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 0x3c, 0x98, 0x1b, 0xea, 0xbd, 0x63, 0x56, 0xab, 0xbd, 0x8e, 0x37, 0x52, 0x3e, 0xcd, 0xb5, 0x8f, 0x3c, 0xf9, 0xb9, 0x17, 0x3f, 0x0a, 0xfe, 0x29, 0x3e, 0x04, 0xc5, 0xb4, 0xbe, 0x6b, 0xf1, 0x1b, 0xbd, 0xc1, 0xb2, 0x45, 0xbe, 0x79, 0xf0, 0x86, 0x3c, 0x25, 0x35, 0x22, 0x3e, 0x47, 0x58, 0x41, 0x3e, 0x75, 0xf2, 0x43, 0x3e, 0x35, 0x30, 0x07, 0xbe, 0x13, 0x56, 0x8d, 0xbe, 0xc9, 0x09, 0xe8, 0xbd, 0xfc, 0xe4, 0xf4, 0xbd, 0xdc, 0x60, 0x06, 0xbc, 0xad, 0x77, 0x3d, 0xbe, 0xf0, 0x20, 0x02, 0x3e, 0xe1, 0x12, 0x85, 0x3e, 0xec, 0xc6, 0x28, 0x3b, 0x57, 0xd3, 0x91, 0xbd, 0x5b, 0x36, 0x48, 0x3e, 0xbf, 0xb8, 0xc1, 0xbd, 0x77, 0x21, 0xaa, 0x3d, 0xde, 0xd6, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x31, 0x2f, 0x43, 0x6f, 0x6e, 0x76, 0x32, 0x44, 0x2f, 0x52, 0x65, 0x61, 0x64, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x4f, 0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0xc3, 0x9e, 0xbe, 0x68, 0xfb, 0xcf, 0xbd, 0x0c, 0x6d, 0xc7, 0xbd, 0x40, 0x3d, 0x80, 0x3e, 0xbe, 0x85, 0xc5, 0xbd, 0xf4, 0x9d, 0x84, 0xbe, 0x3b, 0xad, 0x06, 0x3e, 0x3a, 0x2a, 0x59, 0xbe, 0xe9, 0x1c, 0x3c, 0xbe, 0xe5, 0xf9, 0xc1, 0xbd, 0x33, 0xf9, 0x32, 0x3e, 0x1c, 0xb6, 0x5a, 0x3d, 0xa5, 0x14, 0x1e, 0x3e, 0xbb, 0x97, 0x56, 0xbd, 0xae, 0x05, 0x3b, 0x3d, 0xc6, 0x44, 0x58, 0xbe, 0xbd, 0x7c, 0x4d, 0xbe, 0xf6, 0x3e, 0x64, 0xbe, 0x3e, 0xdf, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x08, 0x00, 0x08, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0x43, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9e, 0xdf, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x31, 0x2f, 0x52, 0x65, 0x6c, 0x75, 0x00, 0x00, 0x00, 0x00, 0xb8, 0xde, 0xff, 0xff, 0xea, 0xdf, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x6d, 0x61, 0x78, 0x5f, 0x70, 0x6f, 0x6f, 0x6c, 0x69, 0x6e, 0x67, 0x32, 0x64, 0x5f, 0x31, 0x2f, 0x4d, 0x61, 0x78, 0x50, 0x6f, 0x6f, 0x6c, 0x00, 0x00, 0x0c, 0xdf, 0xff, 0xff, 0x3e, 0xe0, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x2f, 0x52, 0x65, 0x6c, 0x75, 0x00, 0x00, 0x00, 0x4c, 0xdf, 0xff, 0xff, 0x7e, 0xe0, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x31, 0x2f, 0x42, 0x69, 0x61, 0x73, 0x41, 0x64, 0x64, 0x00, 0x00, 0x90, 0xdf, 0xff, 0xff, 0xc2, 0xe0, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x00, 0x00, 0x00, 0x00, 0xc4, 0xdf, 0xff, 0xff, 0xf6, 0xe0, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x2f, 0x4d, 0x61, 0x74, 0x4d, 0x75, 0x6c, 0x2f, 0x52, 0x65, 0x61, 0x64, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x4f, 0x70, 0x2f, 0x74, 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 0x3e, 0xd2, 0x37, 0xa5, 0xbd, 0x77, 0xfd, 0x51, 0xbc, 0x48, 0x6a, 0x87, 0x3c, 0x46, 0xc0, 0x23, 0x3e, 0x9a, 0x54, 0x86, 0x3d, 0xee, 0x74, 0x4d, 0x3d, 0x30, 0xa0, 0xc8, 0x3d, 0x3b, 0xd3, 0x67, 0xbe, 0xeb, 0x91, 0x11, 0xbe, 0x2d, 0x25, 0xe5, 0x3c, 0x1c, 0x00, 0x7d, 0xbe, 0x45, 0x4a, 0x0a, 0x3a, 0x8d, 0x5d, 0x80, 0x3d, 0x94, 0xa3, 0x67, 0x3d, 0x85, 0x39, 0x0c, 0xbe, 0x52, 0xb0, 0x12, 0xbe, 0xda, 0xbf, 0xa5, 0xbd, 0x2f, 0x5a, 0x91, 0xbd, 0x55, 0x3f, 0x50, 0xbd, 0x42, 0xec, 0x4c, 0xbd, 0xb5, 0x1b, 0xb3, 0xbd, 0x7d, 0x54, 0xaa, 0xbe, 0x11, 0x23, 0x5f, 0xbd, 0xe8, 0xfb, 0x88, 0xbe, 0x82, 0x98, 0x04, 0xbe, 0x9e, 0x65, 0x53, 0xbe, 0x94, 0xd0, 0x59, 0xbe, 0x00, 0xe2, 0x92, 0xbc, 0xf8, 0xb5, 0x0f, 0x3d, 0x56, 0xfd, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x2f, 0x43, 0x6f, 0x6e, 0x76, 0x32, 0x44, 0x5f, 0x62, 0x69, 0x61, 0x73, 0x00, 0x00, 0x00, 0x68, 0xfc, 0xff, 0xff, 0x20, 0x00, 0x00, 0x00, 0xe1, 0x27, 0x95, 0xbf, 0x8d, 0x4b, 0x05, 0xc0, 0x28, 0x8a, 0x85, 0xbf, 0xa4, 0x8b, 0x9f, 0xbf, 0x82, 0x51, 0x26, 0xc0, 0xf4, 0xee, 0xeb, 0xbf, 0xe8, 0x01, 0x81, 0xbf, 0xc8, 0x57, 0xfc, 0xbf, 0xbe, 0xfd, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x63, 0x6f, 0x6e, 0x76, 0x32, 0x64, 0x5f, 0x31, 0x2f, 0x43, 0x6f, 0x6e, 0x76, 0x32, 0x44, 0x5f, 0x62, 0x69, 0x61, 0x73, 0x00, 0xd0, 0xfc, 0xff, 0xff, 0x40, 0x00, 0x00, 0x00, 0xbc, 0x7b, 0xec, 0xbf, 0x5d, 0xd1, 0xaf, 0xbc, 0xed, 0xee, 0x50, 0x3b, 0x0e, 0x64, 0x6d, 0xbe, 0x86, 0x6b, 0x9b, 0xbf, 0x58, 0x9c, 0x83, 0xbf, 0x32, 0xde, 0x29, 0x3f, 0xf3, 0xb7, 0xe6, 0x3f, 0xdc, 0x67, 0x9b, 0xbf, 0xf3, 0x85, 0xef, 0xbf, 0x01, 0xed, 0x05, 0xbf, 0x57, 0xde, 0x95, 0xbc, 0x22, 0x49, 0xce, 0xbf, 0xf8, 0xed, 0x08, 0x3b, 0x9f, 0xb3, 0xb7, 0xbc, 0x9e, 0xf1, 0x6b, 0x40, 0x46, 0xfe, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x31, 0x2f, 0x4d, 0x61, 0x74, 0x4d, 0x75, 0x6c, 0x5f, 0x62, 0x69, 0x61, 0x73, 0x00, 0x00, 0x58, 0xfd, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0xee, 0x38, 0x7c, 0xc0, 0x97, 0x60, 0x9c, 0xc0, 0xc1, 0x5f, 0x03, 0x40, 0x11, 0xbd, 0x70, 0x3f, 0x9e, 0xfe, 0xff, 0xff, 0x10, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x5f, 0x31, 0x2f, 0x4d, 0x61, 0x74, 0x4d, 0x75, 0x6c, 0x2f, 0x52, 0x65, 0x61, 0x64, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x4f, 0x70, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x73, 0x65, 0x00, 0x00, 0xc8, 0xfd, 0xff, 0xff, 0x00, 0x01, 0x00, 0x00, 0x63, 0x77, 0xde, 0xbe, 0x3d, 0x7e, 0xcf, 0x3d, 0x06, 0x1e, 0x47, 0x3e, 0x28, 0xf6, 0xca, 0xbd, 0xc0, 0x2e, 0x93, 0x3e, 0xaf, 0xe9, 0xbb, 0xbd, 0xee, 0x49, 0x42, 0x3e, 0xb8, 0x63, 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, 0x71, 0xbe, 0x62, 0x15, 0xea, 0x38, 0x73, 0x32, 0x34, 0x3e, 0xcd, 0xb4, 0x18, 0x3d, 0x0c, 0x68, 0xab, 0x3e, 0xc9, 0x37, 0x1b, 0xbe, 0x71, 0x71, 0xb0, 0x3d, 0x04, 0xff, 0x57, 0xbe, 0x3a, 0xe4, 0x8c, 0x3e, 0xaf, 0x39, 0xaa, 0x3e, 0x01, 0xc2, 0x3b, 0x3e, 0xc6, 0x91, 0x22, 0xbe, 0x00, 0x00, 0x0e, 0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x74, 0x69, 0x61, 0x6c, 0x2f, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x2f, 0x4d, 0x61, 0x74, 0x4d, 0x75, 0x6c, 0x5f, 0x62, 0x69, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x20, 0xff, 0xff, 0xff, 0x40, 0x00, 0x00, 0x00, 0xc6, 0x20, 0x81, 0xbe, 0x15, 0xa7, 0x3c, 0xbf, 0x04, 0x9d, 0x94, 0x3e, 0x0a, 0xda, 0x3a, 0xba, 0x73, 0x99, 0xe2, 0x3e, 0x3f, 0xcc, 0x3d, 0x3e, 0x84, 0xf9, 0x19, 0x40, 0x4b, 0x7c, 0x1a, 0xbf, 0xe3, 0xbd, 0x0e, 0x40, 0x4e, 0x26, 0x85, 0xbf, 0x3a, 0x64, 0x66, 0xbf, 0x9b, 0x4a, 0x28, 0x3f, 0xa9, 0x8c, 0xad, 0x3f, 0x15, 0xd2, 0x6f, 0xbf, 0x73, 0xa4, 0x08, 0x40, 0x21, 0x5c, 0xcf, 0xbe, 0x07, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x90, 0x01, 0x00, 0x00, 0x3c, 0x01, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x30, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x09, 0x04, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x08, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x70, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x08, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0xb0, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x08, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0xf0, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x05, 0x03, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x14, 0x00, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x14, 0x00, 0x18, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xa8, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x05, 0x03, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x18, 0x00, 0x07, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x14, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x14, 0x00, 0x1c, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x07, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0c, 0x00, 0x10, 0x00, 0x07, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xce, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x19, 0xd6, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x09, 0xde, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x09, 0xe6, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x11, 0xfa, 0xff, 0xff, 0xff, 0x00, 0x03, 0x06, 0x00, 0x06, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x11, 0x06, 0x00, 0x08, 0x00, 0x07, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 }; unsigned int model_tflite_len = 12448;// Fill the int in `src/model.cc` here
#include "GLSL.h" GLSL::GLSL() : _numAttributes(0), _programId(0), _vertexShaderId(0), _fragmentShaderId(0) { } GLSL::~GLSL() { } void GLSL::compileShaders(const std::string& vertexShaderFilePath, const std::string& fragmentShaderFilePath){ _programId = glCreateProgram(); _vertexShaderId = glCreateShader(GL_VERTEX_SHADER); //Create Shader-Vertex (Assigns an ID) if (_vertexShaderId == 0) { FatalError("Vertex shader failed to be created!"); } _fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER); //Create Shader-Fragment (Assigns an ID) if (_fragmentShaderId == 0) { FatalError("Vertex shader failed to be created!"); } compileShader(vertexShaderFilePath, _vertexShaderId); compileShader(fragmentShaderFilePath, _fragmentShaderId); }void GLSL::compileShader(const std::string& filePath, GLuint Id) { //Compile Shaders helper function, to open and compile each shader std::string fileContents = ""; std::string line; //Opens the Shader file to read and write to fileContents as one string (to then compile) std::fstream shaderFile(filePath); //Opens Shader file to read from... if (shaderFile.fail()) { perror(filePath.c_str()); FatalError("Failed to open " + filePath); } while(std::getline(shaderFile, line)) { fileContents += line + "\n"; } shaderFile.close(); const char* contentsPointer = fileContents.c_str(); glShaderSource(Id, 1, &contentsPointer, nullptr); glCompileShader(Id); //Here is where we just compiled the Shader GLint success = 0; glGetShaderiv(Id, GL_COMPILE_STATUS, &success); if (success == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(Id, GL_INFO_LOG_LENGTH, &maxLength); std::vector<char> errorLog(maxLength); glGetShaderInfoLog(Id, maxLength, &maxLength, &errorLog[0]); glDeleteShader(Id); std:printf("%s\n", &(errorLog[0])); FatalError("Shader (" + filePath + ") failed to compile"); } } void GLSL::linkShaders(){ //Links the compiled shaders into 1 program. glAttachShader(_programId, _vertexShaderId); glAttachShader(_programId, _fragmentShaderId); glLinkProgram(_programId); GLint isLinked = 0; glGetProgramiv(_programId, GL_LINK_STATUS, (int *)&isLinked); if (isLinked == GL_FALSE) { //Something went wrong with the shader program... What gives?!?!?! GLint maxLength = 0; glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &maxLength); std::vector<char> errorLog(maxLength); glGetProgramInfoLog(_programId, maxLength, &maxLength, &errorLog[0]); glDeleteProgram(_programId); glDeleteShader(_vertexShaderId); glDeleteShader(_fragmentShaderId); std:printf("%s\n", &(errorLog[0])); FatalError("Shaders failed to link!"); } //Detach and delete the 2 shaders glDetachShader(_programId, _vertexShaderId); glDetachShader(_programId, _fragmentShaderId); glDeleteShader(_vertexShaderId); glDeleteShader(_fragmentShaderId); } void GLSL::addAttribute(const std::string& attributeName) { glBindAttribLocation(_programId, _numAttributes++, attributeName.c_str()); } GLuint GLSL::getUniformLocation(const std::string& uniformName) { GLuint local = glGetUniformLocation(_programId, uniformName.c_str()); if (local == GL_INVALID_INDEX) { FatalError("Uniform " + uniformName + " not found in shader!"); } return local; }void GLSL::loadUniformLocations() { //uni_time = getUniformLocation("time"); //uni_isTexture = getUniformLocation("isTexture"); //uni_curTexture = getUniformLocation("curTexture"); } void GLSL::use() { glUseProgram(_programId); for (int i = 0; i < _numAttributes; i++) { glEnableVertexAttribArray(i); } } void GLSL::unuse(){ glUseProgram(0); for (int i = 0; i < _numAttributes; i++) { glDisableVertexAttribArray(i); } }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef TEST_VIEW_POLY_H_ #define TEST_VIEW_POLY_H_ #include <view/Primitive.h> #include "view/openGl/OpenGl.h" #include <geometry/LineString.h> /** * */ class TestView : public View::Primitive { public: C__ (void) b_ ("Primitive") TestView (); virtual ~TestView (); virtual void update (Model::IModel *model, Event::UpdateEvent *e, View::GLContext *ctx); Geometry::LineString *voronoi; Geometry::LineString *delaunay; Geometry::LineString *delaunay2; Geometry::LineString *crossing; private: GLuint buffer; E_ (TestView) }; # endif /* CIRCLE_H_ */
#ifndef SESSION_H #define SESSION_H #include <QList> #include "SessionManager.h" #include "NetManager.h" #include "HostID.h" #include "Packet.h" class NetManager; class Session { friend class SessionManager; private: unsigned int m_sessionKey; NetManager * m_cnet; QList<HostID> m_hosts; Session(unsigned int sessionKey, NetManager * cnet); Session(const Session & rhs); Session & operator=(const Session & rhs); void AddHost(const HostID & hid); public: ~Session(); void SendToAll(const Packet * pkt); }; #endif
/****************************************************************************** * * * Copyright 2018 Jan Henrik Weinstock * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * ******************************************************************************/ #ifndef VCML_PROPERTY_H #define VCML_PROPERTY_H #include "vcml/common/types.h" #include "vcml/common/strings.h" #include "vcml/common/report.h" #include "vcml/properties/property_base.h" #include "vcml/properties/property_provider.h" namespace vcml { template <typename T, const unsigned int N = 1> class property: public property_base { private: T m_value[N]; T m_defval; bool m_inited; mutable string m_str; public: property(const char* nm, const T& def = T(), sc_module* mod = nullptr); virtual ~property(); VCML_KIND(property); property() = delete; property(const property<T,N>&) = delete; virtual const char* str() const override; virtual void str(const string& s) override; virtual size_t size() const override; virtual size_t count() const override; virtual const char* type() const override; const T& get() const; T& get(); const T& get(unsigned int idx) const; T& get(unsigned int idx); void set(const T& val); void set(const T val[N]); void set(const T& val, unsigned int idx); const T& get_default() const; void set_default(const T& defval); operator T() const; T operator ~ () const; const T& operator [] (unsigned int idx) const; T& operator [] (unsigned int idx); property<T, N>& operator = (const property<T, N>& other); template <typename T2> property<T, N>& operator = (const T2& other); template <typename T2> property<T, N>& operator += (const T2& other); template <typename T2> property<T, N>& operator -= (const T2& other); template <typename T2> property<T, N>& operator *= (const T2& other); template <typename T2> property<T, N>& operator /= (const T2& other); template <typename T2> property<T, N>& operator %= (const T2& other); template <typename T2> property<T, N>& operator &= (const T2& other); template <typename T2> property<T, N>& operator |= (const T2& other); template <typename T2> property<T, N>& operator ^= (const T2& other); template <typename T2> property<T, N>& operator <<= (const T2& other); template <typename T2> property<T, N>& operator >>= (const T2& other); template <typename T2> bool operator == (const T2& other); template <typename T2> bool operator != (const T2& other); template <typename T2> bool operator <= (const T2& other); template <typename T2> bool operator >= (const T2& other); template <typename T2> bool operator < (const T2& other); template <typename T2> bool operator > (const T2& other); }; template <typename T, const unsigned int N> property<T, N>::property(const char* nm, const T& def, sc_module* m): property_base(nm, m), m_value(), m_defval(def), m_inited(false), m_str("") { for (unsigned int i = 0; i < N; i++) m_value[i] = m_defval; string init; if (property_provider::init(name(), init)) str(init); } template <typename T, const unsigned int N> property<T, N>::~property() { // nothing to do } template <typename T, const unsigned int N> inline const char* property<T, N>::str() const { const string delim = to_string(ARRAY_DELIMITER); m_str = ""; // coverity[unsigned_compare] for (unsigned int i = 0; i < (N - 1); i++) m_str += escape(to_string<T>(m_value[i]), delim) + delim; m_str += escape(to_string<T>(m_value[N - 1]), delim); return m_str.c_str(); } template <typename T, const unsigned int N> inline void property<T, N>::str(const string& s) { m_inited = true; vector<string> args = split(s, ARRAY_DELIMITER); unsigned int size = args.size(); if (size < N) { log_warn("property %s has not enough initializers", name().c_str()); } else if (size > N) { log_warn("property %s has too many initializers", name().c_str()); } for (unsigned int i = 0; i < min(N, size); i++) m_value[i] = from_string<T>(trim(args[i])); } template <typename T, const unsigned int N> inline size_t property<T, N>::size() const { return sizeof(T); } template <typename T, const unsigned int N> inline size_t property<T, N>::count() const { return N; } template <typename T, const unsigned int N> inline const char* property<T, N>::type() const { return type_name<T>(); } template <typename T, const unsigned int N> const T& property<T, N>::get() const { return get(0); } template <typename T, const unsigned int N> inline T& property<T, N>::get() { return get(0); } template <typename T, const unsigned int N> const T& property<T, N>::get(unsigned int idx) const { VCML_ERROR_ON(idx >= N, "index %d out of bounds", idx); return m_value[idx]; } template <typename T, const unsigned int N> inline T& property<T, N>::get(unsigned int idx) { VCML_ERROR_ON(idx >= N, "index %d out of bounds", idx); return m_value[idx]; } template <typename T, const unsigned int N> inline void property<T, N>::set(const T& val) { for (unsigned int i = 0; i < N; i++) m_value[i] = val; m_inited = true; } template <typename T, const unsigned int N> inline void property<T, N>::set(const T val[N]) { for (unsigned int i = 0; i < N; i++) m_value[i] = val[i]; m_inited = true; } template <typename T, const unsigned int N> inline void property<T, N>::set(const T& val, unsigned int idx) { VCML_ERROR_ON(idx >= N, "index %d out of bounds", idx); m_value[idx] = val; m_inited = true; } template <typename T, const unsigned int N> inline const T& property<T, N>::get_default() const { return m_defval; } template <typename T, const unsigned int N> inline void property<T,N>::set_default(const T& defval) { m_defval = defval; if (!m_inited) set(defval); } template <typename T, const unsigned int N> inline property<T,N>::operator T() const { return get(0); } template <typename T, const unsigned int N> inline T property<T,N>::operator ~ () const { return ~get(0); } template <typename T, const unsigned int N> inline const T& property<T,N>::operator [] (unsigned int idx) const { return get(idx); } template <typename T, const unsigned int N> inline T& property<T,N>::operator [] (unsigned int idx) { return get(idx); } template <typename T, const unsigned int N> inline property<T,N>& property<T, N>::operator = (const property<T,N>& o) { for (unsigned int i = 0; i < N; i++) set(o.m_value[i], i); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator = (const T2& other) { set(other); return *this; } template <typename T, const unsigned int N>template <typename T2> inline property<T, N>& property<T, N>::operator += (const T2& other) { set(get() + other, 0); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator -= (const T2& other) { set(get() - other, 0); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator *= (const T2& other) { set(get() * other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator /= (const T2& other) { set(get() / other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator %= (const T2& other) { set(get() % other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator &= (const T2& other) { set(get() & other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator |= (const T2& other) { set(get() | other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator ^= (const T2& other) { set(get() ^ other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator <<= (const T2& other) { set(get() << other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline property<T, N>& property<T, N>::operator >>= (const T2& other) { set(get() >> other); return *this; } template <typename T, const unsigned int N> template<typename T2> inline bool property<T, N>::operator == (const T2& other) { for (unsigned int i = 0; i < N; i++) if (m_value[i] != other) return false; return true; } template <typename T, const unsigned int N> template <typename T2> inline bool property<T, N>::operator < (const T2& other) { for (unsigned int i = 0; i < N; i++) if (m_value[i] >= other) return false; return true; } template <typename T, const unsigned int N> template <typename T2> inline bool property<T, N>::operator > (const T2& other) { for (unsigned int i = 0; i < N; i++) if (m_value[i] <= other) return false; return true; } template <typename T, const unsigned int N> template <typename T2> inline bool property<T, N>::operator != (const T2& other) { return !operator == (other); } template <typename T, const unsigned int N> template <typename T2> inline bool property<T, N>::operator <= (const T2& other) { return !operator > (other); } template <typename T, const unsigned int N>template <typename T2> inline bool property<T, N>::operator >= (const T2& other) { return !operator < (other); } } #endif
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ /** \file * This file declares the UpdatableResource base class representing resources * that can be kept updated. The two subclasses UpdatableFile and * UpdatableSetting are also defined here. * * @author Marius Blomli mariusab@opera.com */ #ifndef _UPDATEABLESETTING_H_INCLUDED_ #define _UPDATEABLESETTING_H_INCLUDED_ #ifdef AUTO_UPDATE_SUPPORT #include "adjunct/autoupdate/updatableresource.h" /** * This class is a representation of a preference setting that is to be * kept up to date by the auto update system. * @see UpdatableResource::GetHashKey */ class UpdatableSetting: public UpdatableResource { public: UpdatableSetting(); /** * Implementing UpdatableResource API. */ virtual UpdatableResourceType GetType() { return RTSetting; } virtual ResourceClass GetResourceClass() { return Setting; } virtual OpFileLength GetSize() const { return 0; } virtual OP_STATUS UpdateResource(); virtual BOOL CheckResource() { return TRUE; } virtual OP_STATUS Cleanup() { return OpStatus::OK; } virtual const uni_char* GetResourceName() { return UNI_L("Setting"); } virtual BOOL UpdateRequiresUnpacking() { return FALSE; } virtual BOOL UpdateRequiresRestart() { return FALSE; } virtual BOOL VerifyAttributes(); BOOL IsUpdateCheckInterval(); }; #endif // AUTO_UPDATE_SUPPORT #endif // _UPDATEABLESETTING_H_INCLUDED_
#include "spliter.hpp" class SpliterFactory { public: virtual ISpliter* CreateSpliter(std::string path, size_t count) = 0; }; class BinarySpliterFactory : public SpliterFactory { public: ISpliter* CreateSpliter(std::string path, size_t count) { return new BinarySpliter(path, count); } }; class PictureSpliterFactory : public SpliterFactory { public: ISpliter* CreateSpliter(std::string path, size_t count) { return new PictureSpliter(path, count); } }; class VideoSpliterFactory : public SpliterFactory { public: ISpliter* CreateSpliter(std::string path, size_t count) { return new VideoSpliter(path, count); } };
//Inclass Challenge 9.1: Create a custom Point class with a 2 parameter constructor and the methods: distance_to_origin(), printout(), distance(Point point2) //Kartik Nagpal - kn8767 - 10/30/18 #include <iostream> #include <random> #include <cmath> using std::cout; using std::endl; class Point{ private: float x, y; public: Point() { x = 0; y = 0; } Point(float xcoordinate, float ycoordinate) { x = xcoordinate; y = ycoordinate; } double getX() { return x; } double getY() { return y; } float distance_to_origin() { return sqrt(pow(x,2) + pow(y,2)); } void printout() { cout << "(" << x << ", " << y << ")" << endl; } float distance(Point pt2) { return sqrt(pow(x-pt2.x, 2) + pow(y-pt2.y, 2)); } }; int main() { Point p1(3, 4); Point p2(1, 0); cout << "Distance to Origin: " << p1.distance_to_origin() << endl; p1.printout(); cout << "Distance from p1 to p2: " << p1.distance(p2) << endl; }
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <string.h> #include <vector> #include "backprop.h" #define LAMBDA 1.0 #define ETA 0.1 #define SQR( x ) ( ( x ) * ( x ) ) void randomize( double * p, int n ) { for ( int i = 0; i < n; i++ ) { p[i] = ( double )rand() / ( RAND_MAX ); } } NN * createNN( int n, int h_1, int h_2, int o ) { srand(time(NULL)); NN * nn = new NN; nn->n = new int[4]; nn->n[0] = n; nn->n[1] = h_1; nn->n[2] = h_2; nn->n[3] = o; nn->l = 4; nn->w = new double ** [nn->l - 1]; for ( int k = 0; k < nn->l - 1; k++ ) { nn->w[k] = new double * [nn->n[k + 1]]; for ( int j = 0; j < nn->n[k + 1]; j++ ) { nn->w[k][j] = new double[nn->n[k]]; randomize( nn->w[k][j], nn->n[k]); // BIAS //nn->w[k][j] = new double[nn->n[k] + 1]; //randomize( nn->w[k][j], nn->n[k] + 1 ); } } nn->y = new double * [nn->l]; for ( int k = 0; k < nn->l; k++ ) { nn->y[k] = new double[nn->n[k]]; memset( nn->y[k], 0, sizeof( double ) * nn->n[k] ); } nn->in = nn->y[0]; nn->out = nn->y[nn->l - 1]; nn->d = new double * [nn->l]; for ( int k = 0; k < nn->l; k++ ) { nn->d[k] = new double[nn->n[k]]; memset( nn->d[k], 0, sizeof( double ) * nn->n[k] ); } return nn; } void releaseNN( NN *& nn ) { for ( int k = 0; k < nn->l - 1; k++ ) { for ( int j = 0; j < nn->n[k + 1]; j++ ) { delete [] nn->w[k][j]; } delete [] nn->w[k]; } delete [] nn->w; for ( int k = 0; k < nn->l; k++ ) { delete [] nn->y[k]; } delete [] nn->y; for ( int k = 0; k < nn->l; k++ ) { delete [] nn->d[k]; } delete [] nn->d; delete [] nn->n; delete nn; nn = NULL; } void feedforward( NN * nn ) { double potential = 0.0; //potential for (int k = 1; k < nn->l; k++) { //layers for (int i = 0; i < nn->n[k]; i++) { // neurons in current layer potential = 0; for (int j = 0; j < nn->n[k - 1]; j++) { //neurons in previous layer potential += nn->w[k-1][i][j] * nn->y[k-1][j]; } nn->y[k][i] = 1 / (1 + exp(-LAMBDA * potential)); } } } double backpropagation(NN * nn, double * t) { for (int i = 0; i < nn->n[nn->l - 1]; i++) { nn->d[nn->l - 1][i] = (t[i] - nn->y[nn->l - 1][i]) * nn->y[nn->l - 1][i] * (1 - nn->y[nn->l - 1][i]) * LAMBDA; } for (int k = nn->l - 2; k > 0; k--) { for (int i = 0; i < nn->n[k]; i++) { for (int j = 0; j < nn->n[k + 1]; j++) { nn->d[k][i] += nn->d[k + 1][j] * nn->w[k][j][i]; } nn->d[k][i] *= LAMBDA * nn->y[k][i] * (1 - nn->y[k][i]); } } for (int k = 0; k < nn->l - 1; k++) { for (int i = 0; i < nn->n[k + 1]; i++) { for (int j = 0; j < nn->n[k]; j++) { nn->w[k][i][j] += nn->d[k + 1][i] * nn->y[k][j] * ETA; } } } double error = 0.0; for (int i = 0; i < nn->n[nn->l - 1]; i++) { error += 0.5 * ((t[i] - nn->y[2][i]) * (t[i] - 1)); } return error; } void setInput( NN * nn, double * in, bool verbose ) { memcpy( nn->in, in, sizeof( double ) * nn->n[0] ); if ( verbose ) { printf( "input=(" ); for ( int i = 0; i < nn->n[0]; i++ ) { printf( "%0.3f", nn->in[i] ); if ( i < nn->n[0] - 1 ) { printf( ", " ); } } printf( ")\n" ); } } int getOutput( NN * nn, bool verbose ) { double max = 0.0; int max_i = 0; if(verbose) printf( " output=" ); for ( int i = 0; i < nn->n[nn->l - 1]; i++ ) { if(verbose) printf( "%0.3f ", nn->out[i] ); if(nn->out[i] > max) { max = nn->out[i]; max_i = i; } } if(verbose) printf( " -> %d\n" , max_i); //if(nn->out[0] > nn->out[1] && nn->out[0] - nn->out[1] < 0.1) return 2; return max_i; }
//orgCode.cpp #include "menu.h" #include <iostream> #include <iomanip> #include <string> #include <windows.h> #include <time.h> #include <stdlib.h> #include <conio.h> #include <vector> #include <fstream> #include <sstream> #include <math.h> #define ESYS "Employee System" #define MSYS "Master System" #define ETITLE "====================================菜单====================================" #define SIDETITLE "==========选菜栏==========" #define FOOT "============================================================================" #define COUNT "===================================状态栏====================================" #define ETIPS "\tYou can press the \"SPACE\" key to confirm your choice \n\n\tor press the \"TAB\" key to revoke your choice \n\n\tor press the \"ENTER\" key to submit your choices\n\n\tor press the \"ESC\" key to quit this system" #define MTITLE "===============================店铺及员工管理===============================" using namespace std; string LogIn::serchStr = "\0"; //=======================================================logIn void LogIn::isGoOn(){ if(tValue == 0) exit(0); } void LogIn::login(){ int t = 3; string userN,passW; HANDLE tOut; tOut = GetStdHandle(STD_OUTPUT_HANDLE); while(t>0) { SetConsoleTextAttribute(tOut,07); cout<<"\n\nYou have "<<t<<" chances to login."; cout<<"\n\tUsername : "; cin>>userN; cout<<"\n\tPassword : "; cin>>passW; if(verifyingMas(userN,passW)) { SetConsoleTextAttribute(tOut,FOREGROUND_GREEN|0X8); cout<<"\n\n\t\tLogging in..."; symbol = "master"; Sleep(1*1000); system("cls"); break; } else if(verifyingEmp(userN,passW)) { serchStr = userN; SetConsoleTextAttribute(tOut,FOREGROUND_GREEN|0X8); cout<<"\n\n\t\tLogging in..."; symbol = "employee"; Sleep(3*1000); system("cls"); break; } SetConsoleTextAttribute(tOut,FOREGROUND_RED|0X8); cout<<"The Username or the Passeord is WRONG !!!\n\n"; t--; tValue = t; } } bool LogIn::verifyingEmp(string userN,string passW){ ifstream inFile; string serchO,serchT; inFile.open("employeeCountInformation.txt",ios::in); if(!inFile.is_open()){ return false; } else{ while(!inFile.eof()){ inFile>>serchO; if(serchO == userN){ inFile>>serchT;//Key step : read the serchT which is behind the serchO if(serchT == passW){ return true; } else{ return false; } } } } inFile.close(); return false; } bool LogIn::verifyingMas(string userN,string passW){ ifstream inFile; string serchO,serchT; inFile.open("masterCountInformation.txt",ios::in); if(!inFile.is_open()){ return false; } else{ while(!inFile.eof()){ inFile>>serchO; if(serchO == userN){ inFile>>serchT; if(serchT == passW){ return true; } else{ return false; } } } } inFile.close(); return false; } void LogIn::select(){ if(symbol == "master") { //the master's system Master B; B.theMasterSystem(); } else if(symbol == "employee") { //the employees' system Employee A;//TIPS : If you want to use the classB's function in the classA , you could make a object to use it. A.theEmployeeSystem(); } } //=================================================================================================================================== //=======================================================The employees' system======================================================= COORD pos = {0,0};//define the begin pos void Employee::showTheMenu(string *types,int Size,int thisIndex){ // int i; HANDLE hOut; hOut = GetStdHandle(STD_OUTPUT_HANDLE); system("cls"); SetConsoleTextAttribute(hOut,FOREGROUND_GREEN|0x8);//get the 'TITLE' pos.X = 5; pos.Y = 2; SetConsoleCursorPosition(hOut,pos);//set the position of the 'TITLE' cout<<ETITLE; SetConsoleTextAttribute(hOut,FOREGROUND_GREEN|0x8); pos.X = 85; pos.Y = 2; SetConsoleCursorPosition(hOut,pos); cout<<SIDETITLE; SetConsoleTextAttribute(hOut,FOREGROUND_GREEN|0x8); pos.X = 5; pos.Y = 15; SetConsoleCursorPosition(hOut,pos); cout<<COUNT; SetConsoleTextAttribute(hOut,FOREGROUND_GREEN|0x8); pos.X = 5; pos.Y = 19; SetConsoleCursorPosition(hOut,pos); cout<<FOOT; cout<<"\n"<<ETIPS; SetConsoleTextAttribute(hOut,FOREGROUND_RED|0x8); int span = 0; for(int t=0 ; t<(int)sStorage.size() ; t++){ pos.X = 87; pos.Y = 4+span; SetConsoleCursorPosition(hOut,pos); cout<<sStorage[t].sName<<" : "<<sStorage[t].sPrice<<" 元"<<"\n"<<endl; span += 2; } //======================================================================= for(int i=0 ; i<Size ; i+=2){ if(i == thisIndex){ SetConsoleTextAttribute(hOut,FOREGROUND_RED|0x8); if(i>=0&&i<10){ pos.X = 5; pos.Y = 5+i; } if(i >= 10&&i<20){ pos.X = 35; pos.Y = i-5; } if(i>=20&&i<30){ pos.X = 65; pos.Y = i-15; } SetConsoleCursorPosition(hOut,pos); cout<<"=>"<<types[i]; } else{ SetConsoleTextAttribute(hOut,FOREGROUND_BLUE|0x0b); if(i>=0&&i<10){ pos.X = 5; pos.Y = 5+i; } if(i >= 10&&i<20){ pos.X = 35; pos.Y = i-5; } if(i>=20&&i<30){ pos.X = 65; pos.Y = i-15; } SetConsoleCursorPosition(hOut,pos); cout<<types[i]; } } fflush(stdout); } void Employee::readEmployeeD(){ string empN; string empP; string empS; int intempS; EmpD empMidObj; ifstream inEMPfile("employeeCountInformation.txt"); if(!inEMPfile.is_open()){ cout<<"Open is failure!"; Sleep(3000); exit(0); } else{ while(!inEMPfile.eof()){ inEMPfile>>empN; empMidObj.EmpNu = empN; inEMPfile>>empP; empMidObj.EmpPa = empP; inEMPfile>>empS; intempS = str2num(empS); empMidObj.EmpSa = intempS; empd.push_back(empMidObj); } } inEMPfile.close(); } void Employee::readRestaurantD(){ string mSale; string year; int j = 1; time_t timep; struct tm *p; time(&timep); p = gmtime(&timep); ifstream inRfile("restaurantData.txt"); if(!inRfile.is_open()){ exit(0); } else{ while(!inRfile.eof()){ inRfile>>mSale; sa[j].monthS = str2num(mSale); inRfile>>year; sa[j].wY = str2num(year); j++; if(13 == j)break; } if(str2num(year)!=(1900+p->tm_year)){ for(int i=1 ; i<13 ; i++){ sa[i].monthS = 0; sa[i].wY = (1900+p->tm_year); } } } inRfile.close(); } int Employee::selectMenu(int Size ,int *thisIndex){ int ch; ch = getch(); switch(ch){ case UP: if(*thisIndex>0) *thisIndex -= 2;break; case DOWN: if(*thisIndex<Size -2) *thisIndex += 2; break; case LEFT:if(*thisIndex>=10) *thisIndex -= 10;break; case RIGHT:if(*thisIndex<20) *thisIndex += 10;break; case SPACE:return SPACE;break; case ENTER:return ENTER;break; case ESC:return ESC;break; case TAB:return TAB;break; //Idea : to make a effect of rebacking } return 0; } void Employee::inputValue(int cou,int thisIndex){ int wantNum; showStorage tag;//key step cout<<kind[thisIndex].name<<"× "; cin>>wantNum; tag.sName = kind[thisIndex].name; tag.sCopies = wantNum; tag.sPrice = kind[thisIndex].price * wantNum; sStorage.push_back(tag); } CONSOLE_CURSOR_INFO sss; void Employee::showAndPrintTheReceipt(){ double AllPrice = 0; int AllNum = 0; char ch; LogIn Operator; string sTime = getPresentTime(); time_t timep; struct tm *p; time(&timep); p = gmtime(&timep); HANDLE sOut; sOut = GetStdHandle(STD_OUTPUT_HANDLE); for(int i=0 ; i<(int)sStorage.size() ; i++){ AllPrice += sStorage[i].sPrice; AllNum += sStorage[i].sCopies; } sa[p->tm_mon+1].monthS += (int)AllPrice; for(int i=0 ; i<(int)empd.size() ; i++){ if(Operator.getSech() == empd[i].EmpNu){ empd[i].EmpSa += (int)AllPrice; break; } } ofstream outEMPDfile("employeeCountInformation.txt",ios::trunc); if(!outEMPDfile.is_open()){ exit(0); } else{ for(int i=0 ; i<(int)empd.size()-1; i++){ outEMPDfile<<empd[i].EmpNu<<endl; outEMPDfile<<empd[i].EmpPa<<endl; outEMPDfile<<empd[i].EmpSa<<endl; } } outEMPDfile.close(); ofstream outRfile("restaurantData.txt"); if(!outRfile.is_open()){ exit(0); } else{ for(int i=1 ; i<13 ; i++){ outRfile<<sa[i].monthS<<endl; outRfile<<sa[i].wY<<endl; } } outRfile.close(); cout<<"\n\n\tOperator : "<<Operator.getSech()<<endl; cout<<"\n\tCommodity\t\t\t\tNumber\t\tSubtotal"<<endl; cout<<"\t-----------------------------------------------------------------------"<<endl; for(int i=0 ; i<(int)sStorage.size() ; i++){ cout<<"\n\n\t"<<sStorage[i].sName<<"\t\t\t\t\t"<<sStorage[i].sCopies<<"\t\t"<<sStorage[i].sPrice; } cout<<"\n\t-----------------------------------------------------------------------"<<endl; cout<<"\n\t \t\t\t\tAllNumber\tTotal Amount"; cout<<"\n\t-----------------------------------------------------------------------"<<endl; cout<<"\n\tTotal : \t\t\t\t"<<AllNum<<"\t\t"<<fixed<<setprecision(1)<<AllPrice<<endl; cout<<"\n\t-----------------------------------------------------------------------"<<endl; cout<<"\n\tDo you want to print the receipt?( Y / N )"; cin>>ch; if('Y' == ch){ fstream printReceipt("receipt.txt",ios::app); ofstream outReceipt("receipt.txt",ios::trunc); if(!outReceipt.is_open()){ SetConsoleTextAttribute(sOut,FOREGROUND_RED); cout<<"Print Failure!"; } else{ outReceipt<<"\n\n\n\t-----------------------------------------------------------------------------------------------"<<endl; outReceipt<<"\t\t\t\t\tX X 饭 店"<<endl; outReceipt<<"\t-----------------------------------------------------------------------------------------------"<<endl; outReceipt<<"\tDate\t\t\t\t\t\t"<<sTime<<endl; outReceipt<<"\tOperator\t\t\t\t\t\t"<<Operator.getSech()<<endl; outReceipt<<"\t-----------------------------------------------------------------------------------------------"<<endl; outReceipt<<"\tCommodity\t\t\t\tNumber\t\tSubtotal"<<endl; outReceipt<<"\t-----------------------------------------------------------------------------------------------"<<endl; for(int i=0 ; i<(int)sStorage.size() ; i++){ outReceipt<<"\n\n\t"<<sStorage[i].sName<<"\t\t\t\t\t"<<sStorage[i].sCopies<<"\t\t"<<sStorage[i].sPrice; } outReceipt<<"\n\t-----------------------------------------------------------------------------------------------"<<endl; outReceipt<<"\n\t\t\t\t\t\tAllNumber\tTotal Amount"; outReceipt<<"\n\t-----------------------------------------------------------------------------------------------"<<endl; outReceipt<<"\n\tTotal : \t\t\t\t\t"<<AllNum<<"\t\t"<<fixed<<setprecision(1)<<AllPrice<<endl; outReceipt<<"\n\t-----------------------------------------------------------------------------------------------"<<endl; outReceipt<<"\n\t--------------------------------- Thank you for patronage ! --------------------------------"<<endl; } outReceipt.close(); printReceipt.close(); system("cls"); SetConsoleTextAttribute(sOut,FOREGROUND_GREEN|0x0a); cout<<"\n\n\n\n\n\n\t\t\tPrint Success!!\n\n\n\t\tAnd the system will back to the menu after 3s ....."; Sleep(3000); } } string Employee::getPresentTime(){ string strTime; time_t pt; time(&pt); strTime = ctime(&pt); return strTime; } CONSOLE_CURSOR_INFO fff;//flashCursor void Employee::theEmployeeSystem(){ int sele; int thisIndex = 0; int Size = 30; int cou = 1; HANDLE hOut; SetConsoleTitle(ESYS);//change this title hOut = GetStdHandle(STD_OUTPUT_HANDLE);//get the std Handle GetConsoleCursorInfo(hOut,&fff);//get cursor fff.bVisible = 0;//set this cursor disappear SetConsoleCursorInfo(hOut,&fff);//set cursor readRestaurantD(); readEmployeeD(); while(true){ readRestaurantD(); showTheMenu(types,Size,thisIndex); sele = selectMenu(Size, &thisIndex); if(sele == ESC){ system("cls"); cout<<"\n\n\n\t\t\t>>>>>>>>>>>>>> This system is stop! <<<<<<<<<<<<<<\n\n\n\n"; SetConsoleTextAttribute(hOut,07); break; } if(sele == SPACE){ pos.X = 5; pos.Y = 17; SetConsoleCursorPosition(hOut,pos); switch(thisIndex){ case 0: inputValue(cou,thisIndex); break; case 2: inputValue(cou,thisIndex); break; case 4: inputValue(cou,thisIndex); break; case 6: inputValue(cou,thisIndex); break; case 8: inputValue(cou,thisIndex); break; case 10: inputValue(cou,thisIndex); break; case 12: inputValue(cou,thisIndex); break; case 14: inputValue(cou,thisIndex); break; case 16: inputValue(cou,thisIndex); break; case 18: inputValue(cou,thisIndex); break; case 20: inputValue(cou,thisIndex); break; case 22: inputValue(cou,thisIndex); break; case 24: inputValue(cou,thisIndex); break; case 26: inputValue(cou,thisIndex); break; case 28: inputValue(cou,thisIndex); break; } cou++; } if(sele == TAB){ pos.X = 5; pos.Y = 17; SetConsoleCursorPosition(hOut,pos); char chO; cout<<"Do you want to delete your last choice?( Y / N )"; cin>>chO; if(chO == 'Y'){ sStorage.erase(sStorage.end()-1); } }//I want to left "TAB" for the setting of 'revoking' , it's could be intresting :-) if(sele == ENTER){ system("cls"); pos.X = 5; pos.Y = 13; SetConsoleCursorPosition(hOut,pos); char chT; cout<<"Do you want to submit your choice?( Y / N )"; cin>>chT; if(chT == 'Y'){ system("cls"); while(true){ SetConsoleTextAttribute(hOut,FOREGROUND_GREEN); showAndPrintTheReceipt(); //initail the vector array; sStorage.clear(); break; } } } } } //=================================================================================================================================== //=======================================================The master's system========================================================= COORD zos{0,0}; void Master::showTheVersion(string *options,int optionNum,int thatIndex){ system("cls"); HANDLE xOut; xOut = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(xOut,FOREGROUND_GREEN|0x8); zos.X = 15; zos.Y = 2; SetConsoleCursorPosition(xOut,zos); cout<<MTITLE; SetConsoleTextAttribute(xOut,FOREGROUND_GREEN|0x8); zos.X = 15; zos.Y = 17; SetConsoleCursorPosition(xOut,zos); cout<<FOOT; for(int i=0 ; i<optionNum ; i+=2){ if(i == thatIndex){ SetConsoleTextAttribute(xOut,FOREGROUND_RED|0x8); zos.X = 48; zos.Y = 5 + i; SetConsoleCursorPosition(xOut,zos); cout<<"=> "<<options[i]; } else{ SetConsoleTextAttribute(xOut,FOREGROUND_BLUE|0x0b); zos.X = 48; zos.Y = 5 + i; SetConsoleCursorPosition(xOut,zos); cout<<options[i]; } } fflush(stdout); } int Master::select(int optionNum,int *thatIndex){ int cch; cch = getch(); switch(cch){ case UP_:if(*thatIndex>0) *thatIndex-=2;break; case DOWN_:if(*thatIndex<optionNum-2) *thatIndex+=2;break; case ENTER_:return ENTER_;break; case ESC_:return ESC_;break; } return 0; } void Master::readEmployeeDetail(){ string empN; string empP; string empS; int intempS; EmpDetail empMidObj; ifstream inEMPfile("employeeCountInformation.txt"); if(!inEMPfile.is_open()){ cout<<"Open is failure!"; Sleep(3000); exit(0); } else{ while(!inEMPfile.eof()){ inEMPfile>>empN; empMidObj.EmpNum = empN; inEMPfile>>empP; empMidObj.EmpPassword = empP; inEMPfile>>empS; intempS = str2num(empS); empMidObj.EmpSales = intempS; Emp.push_back(empMidObj); } } inEMPfile.close(); } void Master::readRestaurantData(){ string mSale; string year; int j = 1; time_t timep; struct tm *p; time(&timep); p = gmtime(&timep); ifstream inRESfile("restaurantData.txt"); if(!inRESfile.is_open()){ exit(0); } else{ while(!inRESfile.eof()){ inRESfile>>mSale; sav[j].monthSale = str2num(mSale); inRESfile>>year; sav[j].wYear = str2num(year); j++; if(13 == j)break; } if(str2num(year)!=(1900+p->tm_year)){ for(int i=1 ; i<13 ; i++){ sav[i].monthSale = 0; sav[i].wYear = (1900+p->tm_year); } } } inRESfile.close(); } void Master::addMember(){ system("cls"); time_t timep; struct tm *p; time(&timep); p = gmtime(&timep); HANDLE kOut; kOut = GetStdHandle(STD_OUTPUT_HANDLE); string registerPass; string registerName; EmpDetail newMeb; cout<<"\n\t\t-----------------------注册新员工-----------------------"; cout<<"\n\n\n\t\t\t\t(用户名将自动生成)"; cout<<"\n\n\n\t\t\t\t请输入密码 : "; cin>>registerPass; registerName = num2str(1900+p->tm_year)+num2str(1+p->tm_mon)+num2str(p->tm_mday)+num2str(p->tm_hour)+num2str(p->tm_min)+num2str(p->tm_sec); newMeb.EmpNum = registerName; newMeb.EmpPassword = registerPass; newMeb.EmpSales = 0; Emp.push_back(newMeb); ofstream outEMPfile("employeeCountInformation.txt",ios::app); if(!outEMPfile.is_open()){ cout<<"WRONG!"; exit(0); } else{ outEMPfile<<registerName<<endl; outEMPfile<<registerPass<<endl; outEMPfile<<0<<endl; } outEMPfile.close(); cout<<"\n\n\t\t\t\t\tRegisting..."; Sleep(3000); system("cls"); cout<<"\n\n\n\n\t\t\t\t\tSUCCESS!!"; cout<<"\n\n\n\t\t\t Your USERNAME is : "; SetConsoleTextAttribute(kOut,FOREGROUND_RED|0x8); cout<<registerName; SetConsoleTextAttribute(kOut,FOREGROUND_GREEN|0x8); cout<<"\n\n\n\t\t\t Your PASSWORD is : "; SetConsoleTextAttribute(kOut,FOREGROUND_RED|0x8); cout<<registerPass; SetConsoleTextAttribute(kOut,FOREGROUND_GREEN|0x8); cout<<"\n\n\t\t\tYou must remember them in 15s!!"; Sleep(15000); } void Master::deleteMember(){ system("cls"); HANDLE dOut; dOut = GetStdHandle(STD_OUTPUT_HANDLE); string unsubscribe; char en; bool mid = true; cout<<"\n\t\t-----------------------注销员工-----------------------"; cout<<"\n\n\t\t\t请输入需注销的账号 :"; cin>>unsubscribe; cout<<"\n\n\t\t\tDo you want to log out from this account?( Y / N ) : "; cin>>en; if('Y' == en){ for(int i=0 ; i<(int)Emp.size() ; i++){ if(unsubscribe == Emp[i].EmpNum){ Emp.erase(Emp.begin()+i); ofstream outEMPfile("employeeCountInformation.txt",ios::trunc); if(!outEMPfile.is_open()){ cout<<"wrong!"; Sleep(2000); exit(0); } else{ for(int j=0 ; j<(int)Emp.size()-1 ; j++){ outEMPfile<<Emp[j].EmpNum<<endl; outEMPfile<<Emp[j].EmpPassword<<endl; outEMPfile<<Emp[j].EmpSales<<endl; } } outEMPfile.close(); system("cls"); cout<<Emp.size(); cout<<"\n\n\n\n\n\t\t\t\t\t\t注销成功!"; Sleep(3000); mid = false; break; } } if(mid){ system("cls"); SetConsoleTextAttribute(dOut,FOREGROUND_RED|0x8); cout<<"\n\n\t\t\t未找到此员工!"; Sleep(2000); } } } void Master::changeMember(){ system("cls"); HANDLE lOut; lOut = GetStdHandle(STD_OUTPUT_HANDLE); string eAccount; string eAccountPass; bool mid = true; cout<<"\n\t\t-----------------------更改员工密码-----------------------"; cout<<"\n\n\t\t请输入员工账号 :"; cin>>eAccount; for(int i=0 ; i<(int)Emp.size() ; i++){ if(eAccount == Emp[i].EmpNum){ cout<<"\n\n\t\t请输入新密码 :"; cin>>eAccountPass; Emp[i].EmpPassword = eAccountPass; ofstream outEMPfile("employeeCountInformation.txt",ios::trunc); if(!outEMPfile.is_open()){ cout<<"wrong!"; Sleep(2000); exit(0); } else{ for(int j=0 ; j<(int)Emp.size() ; j++){ outEMPfile<<Emp[j].EmpNum<<endl; outEMPfile<<Emp[j].EmpPassword<<endl; outEMPfile<<Emp[j].EmpSales<<endl; } } outEMPfile.close(); system("cls"); cout<<"\n\n\n\n\t\t\t\t\t修改成功!"; Sleep(3000); mid = false; break; } } if(mid){ system("cls"); SetConsoleTextAttribute(lOut,FOREGROUND_RED|0x8); cout<<"\n\n\n\n\t\t\t\t\t未找到此员工!"; Sleep(2000); } } void Master::findMember(){ system("cls"); HANDLE mOut; mOut = GetStdHandle(STD_OUTPUT_HANDLE); string EmpAccount; string one,two; string curentAchive; int j=0; bool mark = true; cout<<"\n\n\t\t\t----------------------查询员工当前总业绩----------------------"; cout<<"\n\n\n\t\t\t\t\t\t请输入员工账号:"; cin>>EmpAccount; ifstream inEMPfile("employeeCountInformation.txt"); if(!inEMPfile.is_open()){ exit(0); } else{ while(!inEMPfile.eof()){ inEMPfile>>curentAchive; if(EmpAccount == curentAchive){ inEMPfile>>one; inEMPfile>>two; mark = false; break; } j++; } if(mark){ system("cls"); SetConsoleTextAttribute(mOut,FOREGROUND_RED|0x8); cout<<"\n\n\t\t\t未找到此员工!"; Sleep(2000); } } inEMPfile.close(); if(!mark){ cout<<"\n\n\t\t\t\t\t\t此员工当前业绩:"<<two; cout<<"\n\n\n\t\t\t\t\t\t3s后返回主菜单"; Sleep(3000); } } COORD gos = {0,30}; void Master::annualSummary(){ system("cls"); time_t timep; struct tm *p; time(&timep); p = gmtime(&timep); HANDLE uOut; uOut = GetStdHandle(STD_OUTPUT_HANDLE); int j; int mid =-1; cout<<"\n\n\t\t\t----------------------查询店铺综合情况----------------------"; cout<<"\n\n\n\t===================================== 全体员工数据一览 ======================================\n\n\n"; SetConsoleTextAttribute(uOut,07); for(int i=0 ; i<(int)Emp.size()-1 ; i++ ){ cout<<"\n\n\t\t"<<string(35,'+')<<" | "<<string(35,'+'); cout<<"\n\t\t\t\t\t\t\t|\n\t\t员工账号:"<<Emp[i].EmpNum<<"\t\t\t|"; i++; if(i>=(int)Emp.size()-1){ cout<<"\n\t\t\t\t\t\t\t|\n\t\t销售量:"<<Emp[i-1].EmpSales; break; } else{ cout<<"\t员工账号:"<<Emp[i].EmpNum; cout<<"\n\t\t\t\t\t\t\t|\n\t\t销售量:"<<Emp[i-1].EmpSales<<"\t\t\t\t|"<<"\t销售量:"<<Emp[i].EmpSales; } } cout<<"\n\n"; SetConsoleTextAttribute(uOut,FOREGROUND_RED|0x8); for(int i=0 ; i<(int)Emp.size()-1 ; i++){ if(Emp[i].EmpSales>mid){ mid = Emp[i].EmpSales; j = i; } } cout<<"\n\n\t\t"<<" "<<string(24,'*')<<string(8,' ')<<"销 售 之 星"<<string(8,' ')<<string(24,'*'); cout<<"\n\n\t\t"<<" "<<string(18,'*')<<string(9,' ')<<Emp[j].EmpNum<<string(10,' ')<<string(18,'*'); cout<<"\n\n\t\t\t"<<" "<<string(12,'*')<<string(8,' ')<<"个 人 销 额"<<string(8,' ')<<string(12,'*'); cout<<"\n\n\t\t\t\t"<<" "<<string(6,'*')<<string(11,' ')<<mid<<string(11,' ')<<string(6,'*'); SetConsoleTextAttribute(uOut,FOREGROUND_GREEN|0x8); cout<<"\n\n\n\t=============================================================================================\n"; //========================================================================================================================================= int star[13] = {0}; int lid = -1; int k = 0; int t = 1; double allSale = 0; for(int i=1 ; i<13 ; i++){ star[i] = ceil(sav[i].monthSale/240); if(lid<sav[i].monthSale){ lid = sav[i].monthSale; k = i; } allSale += sav[i].monthSale; } cout<<"\n\t=================================== 餐馆"<<1900+p->tm_year<<"年度数据一览 ====================================\n"; SetConsoleTextAttribute(uOut,07); cout<<"\n\n\n\n\t\t"<<string(22,' ')<<"5k"<<string(21,' ')<<"10k"<<" 月销售额"; cout<<"\n\t\t"<<string(50,'-')<<">"; for(int i=1 ; i<13 ; i++){ cout<<"\n\t"<<i<<"月 "<<"\t|"<<string(star[i],'*'); cout<<"\n\t\t|"; } cout<<"\n\t\tV"; for(int i=0 ; i<25 ; i++){ gos.X = 68; gos.Y = 48+i; if(t == k&&i%2!=0){ SetConsoleTextAttribute(uOut,FOREGROUND_RED|0x8); cout<<"<-"<<sav[t].monthSale; SetConsoleTextAttribute(uOut,07); t++; } else if(t!=k && i%2!=0){ cout<<"<-"<<sav[t].monthSale; t++; } else{ cout<<" "; } SetConsoleCursorPosition(uOut,gos); } SetConsoleTextAttribute(uOut,FOREGROUND_RED|0x8); cout<<"\n\n\t\t销额最高月份: "<<k<<"月"<<"\t销售额: "<<sav[k].monthSale<<"\n\n\t\t"<<"全年总销额:"<<fixed<<setprecision(2)<<allSale; SetConsoleTextAttribute(uOut,FOREGROUND_GREEN|0x8); gos.X = 0; gos.Y = 75; SetConsoleCursorPosition(uOut,gos); cout<<"\n\n\n\t=============================================================================================\n"; fflush(stdout); getch(); } CONSOLE_CURSOR_INFO vvv; void Master::theMasterSystem(){ int thatIndex = 0; int optionNum = 10; int opo = 1; HANDLE xOut; xOut = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTitle(MSYS); GetConsoleCursorInfo(xOut,&vvv); vvv.bVisible = 0; SetConsoleCursorInfo(xOut,&vvv); readEmployeeDetail(); readRestaurantData(); //At the begining, we should read the "txt" storage,because it will be convenient for us to continue to do the other tasks while(true){ readRestaurantData(); showTheVersion(options,optionNum,thatIndex); opo = select(optionNum,&thatIndex); if(opo == ESC_){ system("cls"); cout<<"\n\n\n\t\t\t>>>>>>>>>>>>>> This system is stop! <<<<<<<<<<<<<<\n\n\n\n"; SetConsoleTextAttribute(xOut,07); break; } if(opo == ENTER_){ switch(thatIndex){ case 0:SetConsoleTextAttribute(xOut,FOREGROUND_GREEN|0x8);addMember();break; case 2:SetConsoleTextAttribute(xOut,FOREGROUND_GREEN|0x8);deleteMember();break; case 4:SetConsoleTextAttribute(xOut,FOREGROUND_GREEN|0x8);changeMember();break; case 6:SetConsoleTextAttribute(xOut,FOREGROUND_GREEN|0x8);findMember();break; case 8:SetConsoleTextAttribute(xOut,FOREGROUND_GREEN|0x8);annualSummary();break; } } } } int str2num(string s){ int num; stringstream ss(s); ss>>num; return num; } string num2str(int i){ stringstream ss; ss<<i; return ss.str(); }
#pragma once #include "SIngletonBase.h" /* ini 파일은 대단락 키 값으로 되어있음 */ //struct tagIniData { // const char* section; // const char* key; // const char* value; //}; struct tagIniData { char section[32]; char key[32]; char value[32]; }; class IniData : public SingletonBase<IniData> { private: vector<tagIniData> _vIniData; public: IniData(); ~IniData(); void AddData(const char* section, const char* key, const char* value); void SaveData(const char* fileName); char* LoadDataString(const char* fileName, const char* section, const char* key); int LoadDataInteger(const char* fileName, const char* section, const char* key); }; #define INIDATA IniData::GetSingleton()
// Created on: 1994-06-01 // Created by: Christian CAILLET // Copyright (c) 1994-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 _IGESSelect_UpdateLastChange_HeaderFile #define _IGESSelect_UpdateLastChange_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IGESSelect_ModelModifier.hxx> class IFSelect_ContextModif; class IGESData_IGESModel; class Interface_CopyTool; class TCollection_AsciiString; class IGESSelect_UpdateLastChange; DEFINE_STANDARD_HANDLE(IGESSelect_UpdateLastChange, IGESSelect_ModelModifier) //! Allows to Change the Last Change Date indication in the Header //! (Global Section) of IGES File. It is taken from the operating //! system (time of application of the Modifier). //! The Selection of the Modifier is not used : it simply acts as //! a criterium to select IGES Files to touch up. //! Remark : IGES Models noted as version before IGES 5.1 are in //! addition changed to 5.1 class IGESSelect_UpdateLastChange : public IGESSelect_ModelModifier { public: //! Creates an UpdateLastChange, which uses the system Date Standard_EXPORT IGESSelect_UpdateLastChange(); //! Specific action : only <target> is used : the system Date //! is set to Global Section Item n0 25. Also sets IGES Version //! (Item n0 23) to IGES5 if it was older. Standard_EXPORT void Performing (IFSelect_ContextModif& ctx, const Handle(IGESData_IGESModel)& target, Interface_CopyTool& TC) const Standard_OVERRIDE; //! Returns a text which is //! "Update IGES Header Last Change Date" Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IGESSelect_UpdateLastChange,IGESSelect_ModelModifier) protected: private: }; #endif // _IGESSelect_UpdateLastChange_HeaderFile
#ifndef __CAMERA_H__ #define __CAMERA_H__ /* Generic camera class by Nghia Ho */ class Camera { private: float m_x, m_y, m_z; // Position float m_lx, m_ly, m_lz; // Direction vector of where we are looking at float m_yaw, m_pitch; // Various rotation angles float m_strafe_lx, m_strafe_lz; // Always 90 degree to direction vector public: Camera() { Init(); } ~Camera() {} void Init(); void Refresh(); void SetPos(float x, float y, float z); void GetPos(float &x, float &y, float &z); inline float pega_x() { return m_x; } inline float pega_y() { return m_y; } inline float pega_z() { return m_z; } inline float pega_pitch() { return m_pitch*100; } inline float pega_yaw() { return m_yaw*100; } void GetDirectionVector(float &x, float &y, float &z); void SetYaw(float angle); void SetPitch(float angle); // Navigation void Move(float incr, bool flyMode = true); void Strafe(float incr); void Fly(float incr); void RotateYaw(float angle); void RotatePitch(float angle); }; #endif
#include "SimplePgMatcher.h" #include "copmem/CopMEMMatcher.h" #include "../pseudogenome/persistence/SeparatedPseudoGenomePersistence.h" #include "../utils/LzmaLib.h" namespace PgTools { SimplePgMatcher::SimplePgMatcher(const string &srcPg, uint32_t targetMatchLength, uint32_t minMatchLength) : srcPg(srcPg), targetMatchLength(targetMatchLength) { cout << "Source pseudogenome length: " << srcPg.length() << endl; if (srcPg.size() >= targetMatchLength) matcher = new CopMEMMatcher(srcPg.data(), srcPg.length(), targetMatchLength, minMatchLength); //matcher = new DefaultTextMatcher(srcPg, targetMatchLength); } SimplePgMatcher::~SimplePgMatcher() { if (matcher) delete (matcher); } void SimplePgMatcher::exactMatchPg(string &destPg, bool destPgIsSrcPg, uint32_t minMatchLength) { time_checkpoint(); if (!destPgIsSrcPg) cout << "Destination pseudogenome length: " << destPgLength << endl; if (revComplMatching) { if (destPgIsSrcPg) { string queryPg = reverseComplement(destPg); matcher->matchTexts(textMatches, queryPg, destPgIsSrcPg, revComplMatching, minMatchLength); } else { reverseComplementInPlace(destPg); matcher->matchTexts(textMatches, destPg, destPgIsSrcPg, revComplMatching, minMatchLength); reverseComplementInPlace(destPg); } } else matcher->matchTexts(textMatches, destPg, destPgIsSrcPg, revComplMatching, minMatchLength); *logout << "... found " << textMatches.size() << " exact matches in " << time_millis() << " msec. " << endl; /* std::sort(textMatches.begin(), textMatches.end(), [](const TextMatch &match1, const TextMatch &match2) -> bool { return match1.length > match2.length; }); cout << "Largest matches:" << endl; for (uint32_t i = 0; i < textMatches.size() && i < 10; i++) textMatches[i].report(cout);/**/ if (revComplMatching) correctDestPositionDueToRevComplMatching(); } using namespace PgTools; void SimplePgMatcher::correctDestPositionDueToRevComplMatching() { for (TextMatch &match: textMatches) match.posDestText = destPgLength - (match.posDestText + match.length); } string SimplePgMatcher::getTotalMatchStat(uint_pg_len_max totalMatchLength) { return toString(totalMatchLength) + " (" + toString((totalMatchLength * 100.0) / destPgLength, 1) + "%)"; } char SimplePgMatcher::MATCH_MARK = '%'; void SimplePgMatcher::markAndRemoveExactMatches( bool destPgIsSrcPg, string &destPg, string &resPgMapOff, string &resPgMapLen, bool revComplMatching, uint32_t minMatchLength) { if (!matcher) { resPgMapOff.clear(); resPgMapLen.clear(); return; } this->revComplMatching = revComplMatching; this->destPgLength = destPg.length(); if (minMatchLength == UINT32_MAX) minMatchLength = targetMatchLength; exactMatchPg(destPg, destPgIsSrcPg, minMatchLength); chrono::steady_clock::time_point post_start = chrono::steady_clock::now(); if (destPgIsSrcPg) resolveMappingCollisionsInTheSameText(); ostringstream pgMapOffDest; ostringstream pgMapLenDest; PgSAHelpers::writeUIntByteFrugal(pgMapLenDest, minMatchLength); sort(textMatches.begin(), textMatches.end()); textMatches.erase(unique(textMatches.begin(), textMatches.end()), textMatches.end()); *logout << "Unique exact matches: " << textMatches.size() << endl; char *destPtr = (char *) destPg.data(); uint_pg_len_max pos = 0; uint_pg_len_max nPos = 0; uint_pg_len_max totalDestOverlap = 0; uint_pg_len_max totalMatched = 0; bool isPgLengthStd = srcPg.length() <= UINT32_MAX; for (TextMatch &match: textMatches) { if (match.posDestText < pos) { uint_pg_len_max overflow = pos - match.posDestText; if (overflow >= match.length) { totalDestOverlap += match.length; match.length = 0; continue; } totalDestOverlap += overflow; match.length -= overflow; match.posDestText += overflow; if (!revComplMatching) match.posSrcText += overflow; } if (match.length < minMatchLength) { totalDestOverlap += match.length; continue; } totalMatched += match.length; uint64_t length = match.posDestText - pos; memmove(destPtr + nPos, destPtr + pos, length); nPos += length; destPg[nPos++] = MATCH_MARK; if (isPgLengthStd) PgSAHelpers::writeValue<uint32_t>(pgMapOffDest, match.posSrcText); else PgSAHelpers::writeValue<uint64_t>(pgMapOffDest, match.posSrcText); PgSAHelpers::writeUIntByteFrugal(pgMapLenDest, match.length - minMatchLength); pos = match.endPosDestText(); } uint64_t length = destPg.length() - pos; memmove(destPtr + nPos, destPtr + pos, length); nPos += length; destPg.resize(nPos); textMatches.clear(); resPgMapOff = pgMapOffDest.str(); pgMapOffDest.clear(); resPgMapLen = pgMapLenDest.str(); pgMapLenDest.clear(); *logout << "Preparing output time: " << time_millis(post_start) << " msec." << endl; cout << "Final size of Pg: " << nPos << " (removed: " << getTotalMatchStat(totalMatched) << "; " << totalDestOverlap << " chars in overlapped dest symbol)" << endl; } void SimplePgMatcher::writeMatchingResult(const string &pgPrefix, const string &pgMapped, const string &pgMapOff, const string &pgMapLen) { PgSAHelpers::writeStringToFile(pgPrefix + SeparatedPseudoGenomeBase::PSEUDOGENOME_FILE_SUFFIX, pgMapped); PgSAHelpers::writeStringToFile(pgPrefix + SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_OFFSETS_FILE_SUFFIX, pgMapOff); PgSAHelpers::writeStringToFile(pgPrefix + SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_LENGTHS_FILE_SUFFIX, pgMapLen); } void SimplePgMatcher::resolveMappingCollisionsInTheSameText() { for (TextMatch &match: textMatches) { if (match.posSrcText > match.posDestText) { uint64_t tmp = match.posSrcText; match.posSrcText = match.posDestText; match.posDestText = tmp; } if (revComplMatching && match.endPosSrcText() > match.posDestText) { uint64_t margin = (match.endPosSrcText() - match.posDestText + 1) / 2; match.length -= margin; match.posDestText += margin; } } } void SimplePgMatcher::matchPgsInPg(string &hqPgSequence, string &lqPgSequence, string &nPgSequence, bool separateNReads, ostream &pgrcOut, uint8_t coder_level, const string &hqPgPrefix, const string &lqPgPrefix, const string &nPgPrefix, uint_pg_len_max targetMatchLength, uint32_t minMatchLength) { chrono::steady_clock::time_point ref_start = chrono::steady_clock::now(); const unsigned long refSequenceLength = hqPgSequence.length(); bool isPgLengthStd = refSequenceLength <= UINT32_MAX; PgTools::SimplePgMatcher* matcher = new PgTools::SimplePgMatcher(hqPgSequence, targetMatchLength, minMatchLength); *logout << "Feeding reference pseudogenome finished in " << time_millis(ref_start) << " msec. " << endl; chrono::steady_clock::time_point lq_start = chrono::steady_clock::now(); string lqPgMapOff, lqPgMapLen; matcher->markAndRemoveExactMatches(false, lqPgSequence, lqPgMapOff, lqPgMapLen, true, minMatchLength); if (!lqPgPrefix.empty()) matcher->writeMatchingResult(lqPgPrefix, lqPgSequence, lqPgMapOff, lqPgMapLen); *logout << "PgMatching lqPg finished in " << time_millis(lq_start) << " msec. " << endl; chrono::steady_clock::time_point n_start = chrono::steady_clock::now(); string nPgMapOff, nPgMapLen; matcher->markAndRemoveExactMatches(false, nPgSequence, nPgMapOff, nPgMapLen, true, minMatchLength); if (!nPgPrefix.empty()) matcher->writeMatchingResult(nPgPrefix, nPgSequence, nPgMapOff, nPgMapLen); if (!nPgSequence.empty()) *logout << "PgMatching nPg finished in " << time_millis(n_start) << " msec. " << endl; chrono::steady_clock::time_point hq_start = chrono::steady_clock::now(); string hqPgMapOff, hqPgMapLen; matcher->markAndRemoveExactMatches(true, hqPgSequence, hqPgMapOff, hqPgMapLen, true, minMatchLength); if (!hqPgPrefix.empty()) matcher->writeMatchingResult(hqPgPrefix, hqPgSequence, hqPgMapOff, hqPgMapLen); *logout << "PgMatching hqPg finished in " << time_millis(hq_start) << " msec. " << endl; delete(matcher); PgSAHelpers::writeValue<uint_pg_len_max>(pgrcOut, hqPgSequence.length(), false); PgSAHelpers::writeValue<uint_pg_len_max>(pgrcOut, lqPgSequence.length(), false); PgSAHelpers::writeValue<uint_pg_len_max>(pgrcOut, nPgSequence.length(), false); string comboPgSeq = std::move(hqPgSequence); comboPgSeq.reserve(comboPgSeq.size() + lqPgSequence.size() + nPgSequence.size()); comboPgSeq.append(lqPgSequence); lqPgSequence.clear(); lqPgSequence.shrink_to_fit(); comboPgSeq.append(nPgSequence); nPgSequence.clear(); nPgSequence.shrink_to_fit(); compressPgSequence(pgrcOut, comboPgSeq, coder_level, nPgSequence.empty()); *logout << "Good sequence mapping - offsets... "; double estimated_pg_offset_ratio = simpleUintCompressionEstimate(refSequenceLength, isPgLengthStd ? UINT32_MAX : UINT64_MAX); const int pgrc_pg_offset_dataperiodcode = isPgLengthStd ? PGRC_DATAPERIODCODE_32_t : PGRC_DATAPERIODCODE_64_t; writeCompressed(pgrcOut, hqPgMapOff.data(), hqPgMapOff.size(), LZMA_CODER, coder_level, pgrc_pg_offset_dataperiodcode, estimated_pg_offset_ratio); *logout << "lengths... "; writeCompressed(pgrcOut, hqPgMapLen.data(), hqPgMapLen.size(), LZMA_CODER, coder_level, PGRC_DATAPERIODCODE_8_t); *logout << "Bad sequence mapping - offsets... "; writeCompressed(pgrcOut, lqPgMapOff.data(), lqPgMapOff.size(), LZMA_CODER, coder_level, pgrc_pg_offset_dataperiodcode, estimated_pg_offset_ratio); *logout << "lengths... "; writeCompressed(pgrcOut, lqPgMapLen.data(), lqPgMapLen.size(), LZMA_CODER, coder_level, PGRC_DATAPERIODCODE_8_t); if (separateNReads) { *logout << "N sequence mapping - offsets... "; writeCompressed(pgrcOut, nPgMapOff.data(), nPgMapOff.size(), LZMA_CODER, coder_level, pgrc_pg_offset_dataperiodcode, estimated_pg_offset_ratio); *logout << "lengths... "; writeCompressed(pgrcOut, nPgMapLen.data(), nPgMapLen.size(), LZMA_CODER, coder_level, PGRC_DATAPERIODCODE_8_t); } } void SimplePgMatcher::compressPgSequence(ostream &pgrcOut, string &pgSequence, uint8_t coder_level, bool noNPgSequence, bool testAndValidation) { *logout << "Var-len encoding joined mapped sequences (good&bad" << (noNPgSequence ? "" : "&N") << ")... "; size_t compLen = 0; char *compSeq = componentCompress(pgrcOut, compLen, pgSequence.data(), pgSequence.size(), VARLEN_DNA_CODER, coder_level, VarLenDNACoder::getCoderParam(VarLenDNACoder::STATIC_CODES_CODER_PARAM, VarLenDNACoder::AG_EXTENDED_CODES_ID), 1); if (testAndValidation) { cout << "\n*** Var-len coding validation and additional tests..." << endl; string valPgSeq; valPgSeq.resize(pgSequence.size()); size_t valSeq = pgSequence.size(); Uncompress((char *) valPgSeq.data(), valSeq, compSeq, compLen, VARLEN_DNA_CODER); cout << (valPgSeq == pgSequence ? "Coding validated :)" : "Coding error :(") << endl; writeCompressed(null_stream, pgSequence.data(), pgSequence.length(), LZMA_CODER, coder_level, PGRC_DATAPERIODCODE_8_t, COMPRESSION_ESTIMATION_BASIC_DNA); cout << "OTHER CODEBOOKS..." << endl; for(int i = 1; i < VarLenDNACoder::CODEBOOK_ID::VARLEN_CODEBOOKS_COUNT; i++) { cout << "codebook id: " << i << endl; size_t compLen = 0; char *compSeq = componentCompress(pgrcOut, compLen, pgSequence.data(), pgSequence.size(), VARLEN_DNA_CODER, coder_level, VarLenDNACoder::getCoderParam( VarLenDNACoder::STATIC_CODES_CODER_PARAM, i), 1); Uncompress((char *) valPgSeq.data(), valSeq, compSeq, compLen, VARLEN_DNA_CODER); cout << (valPgSeq == pgSequence ? "Coding validated :)" : "Coding error :(") << endl; writeCompressed(null_stream, compSeq, compLen, LZMA_CODER, coder_level, PGRC_DATAPERIODCODE_8_t, COMPRESSION_ESTIMATION_VAR_LEN_DNA); delete[] compSeq; } cout << "***\n" << endl; } pgSequence.clear(); pgSequence.shrink_to_fit(); *logout << "Joined var-len encoded mapped sequences (good&bad" << (noNPgSequence ? "" : "&N") << ")... "; writeCompressed(pgrcOut, compSeq, compLen, LZMA_CODER, coder_level, PGRC_DATAPERIODCODE_8_t, COMPRESSION_ESTIMATION_VAR_LEN_DNA); delete[] compSeq; } void SimplePgMatcher::restoreMatchedPgs(istream &pgrcIn, uint_pg_len_max orgHqPgLen, string &hqPgSequence, string &lqPgSequence, string &nPgSequence) { uint_pg_len_max hqPgMappedLen, lqPgMappedLen, nPgMappedLen; string pgMapOff, pgMapLen; istringstream pgMapOffSrc, pgMapLenSrc; PgSAHelpers::readValue<uint_pg_len_max>(pgrcIn, hqPgMappedLen, false); PgSAHelpers::readValue<uint_pg_len_max>(pgrcIn, lqPgMappedLen, false); PgSAHelpers::readValue<uint_pg_len_max>(pgrcIn, nPgMappedLen, false); string comboPgMapped; readCompressed(pgrcIn, comboPgMapped); string nPgMapped(comboPgMapped, hqPgMappedLen + lqPgMappedLen); comboPgMapped.resize(hqPgMappedLen + lqPgMappedLen); { string lqPgMapped(comboPgMapped, hqPgMappedLen); comboPgMapped.resize(hqPgMappedLen); comboPgMapped.shrink_to_fit(); { string hqPgMapped = std::move(comboPgMapped); readCompressed(pgrcIn, pgMapOff); readCompressed(pgrcIn, pgMapLen); pgMapOffSrc.str(pgMapOff); pgMapLenSrc.str(pgMapLen); hqPgSequence.clear(); hqPgSequence = SimplePgMatcher::restoreMatchedPg(hqPgSequence, orgHqPgLen, hqPgMapped, pgMapOffSrc, pgMapLenSrc, true, false, true); } readCompressed(pgrcIn, pgMapOff); readCompressed(pgrcIn, pgMapLen); pgMapOffSrc.str(pgMapOff); pgMapLenSrc.str(pgMapLen); lqPgSequence = SimplePgMatcher::restoreMatchedPg(hqPgSequence, orgHqPgLen, lqPgMapped, pgMapOffSrc, pgMapLenSrc, true, false); } if (nPgMappedLen) { readCompressed(pgrcIn, pgMapOff); readCompressed(pgrcIn, pgMapLen); pgMapOffSrc.str(pgMapOff); pgMapLenSrc.str(pgMapLen); nPgSequence = SimplePgMatcher::restoreMatchedPg(hqPgSequence, orgHqPgLen, nPgMapped, pgMapOffSrc, pgMapLenSrc, true, false); } } string SimplePgMatcher::restoreMatchedPg(string &srcPg, size_t orgSrcLen, const string &destPg, istream &pgMapOffSrc, istream &pgMapLenSrc, bool revComplMatching, bool plainTextReadMode, bool srcIsDest) { bool isPgLengthStd = orgSrcLen <= UINT32_MAX; if (srcIsDest) srcPg.resize(0); string tmp; string &resPg = srcIsDest ? srcPg : tmp; uint64_t posDest = 0; uint32_t minMatchLength = 0; PgSAHelpers::readUIntByteFrugal(pgMapLenSrc, minMatchLength); uint64_t markPos = 0; while ((markPos = destPg.find(MATCH_MARK, posDest)) != std::string::npos) { resPg.append(destPg, posDest, markPos - posDest); posDest = markPos + 1; uint64_t matchSrcPos = 0; if (isPgLengthStd) { uint32_t tmp; PgSAHelpers::readValue<uint32_t>(pgMapOffSrc, tmp, plainTextReadMode); matchSrcPos = tmp; } else PgSAHelpers::readValue<uint64_t>(pgMapOffSrc, matchSrcPos, plainTextReadMode); uint64_t matchLength = 0; PgSAHelpers::readUIntByteFrugal(pgMapLenSrc, matchLength); matchLength += minMatchLength; if (revComplMatching) resPg.append(reverseComplement(srcPg.substr(matchSrcPos, matchLength))); else resPg.append(srcPg.substr(matchSrcPos, matchLength)); } resPg.append(destPg, posDest, destPg.length() - posDest); cout << "Restored Pg sequence of length: " << resPg.length() << endl; return resPg; } string SimplePgMatcher::restoreMatchedPg(string &srcPg, const string &destPgPrefix, bool revComplMatching, bool plainTextReadMode) { string destPg = SeparatedPseudoGenomePersistence::loadPseudoGenomeSequence(destPgPrefix); ifstream pgMapOffSrc = SeparatedPseudoGenomePersistence::getPseudoGenomeElementSrc(destPgPrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_OFFSETS_FILE_SUFFIX); ifstream pgMapLenSrc = SeparatedPseudoGenomePersistence::getPseudoGenomeElementSrc(destPgPrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_LENGTHS_FILE_SUFFIX); return SimplePgMatcher::restoreMatchedPg(srcPg, srcPg.length(), destPg, pgMapOffSrc, pgMapLenSrc, revComplMatching, plainTextReadMode, false); } string SimplePgMatcher::restoreAutoMatchedPg(const string &pgPrefix, bool revComplMatching) { PseudoGenomeHeader *pgh = 0; ReadsSetProperties *prop = 0; bool plainTextReadMode = false; SeparatedPseudoGenomeBase::getPseudoGenomeProperties(pgPrefix, pgh, prop, plainTextReadMode); string destPg = SeparatedPseudoGenomePersistence::loadPseudoGenomeSequence(pgPrefix); ifstream pgMapOffSrc = SeparatedPseudoGenomePersistence::getPseudoGenomeElementSrc(pgPrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_OFFSETS_FILE_SUFFIX); ifstream pgMapLenSrc = SeparatedPseudoGenomePersistence::getPseudoGenomeElementSrc(pgPrefix, SeparatedPseudoGenomeBase::PSEUDOGENOME_MAPPING_LENGTHS_FILE_SUFFIX); string resPg; resPg = SimplePgMatcher::restoreMatchedPg(resPg, pgh->getPseudoGenomeLength(), destPg, pgMapOffSrc, pgMapLenSrc, revComplMatching, plainTextReadMode, true); delete (pgh); delete (prop); return resPg; } }
#ifndef ZOO_H #define ZOO_H using namespace std; class Zoo{ private: int bank_balance; Tiger * tigers; SeaLion * sealions; Bear * bears; int tiger_count; int sea_lion_count; int bear_count; bool attendance_boom = false; int base_cost = 80; public: //! Function header template DO NOT TOUCH /****************************************************** ** Function: ** Description: ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ //! FUNCTIONS OF THE CLASS /****************************************************** ** Function: Zoo ** Description: Simple constructor for the zoo class ** object. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ Zoo(); //TODO// Code this constructor /****************************************************** ** Function: ~Zoo ** Description: Simple destructor for the zoo class ** object. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ ~Zoo(); //TODO Code this destructor //! FUNCTIONS OF THE GAME /****************************************************** ** Function: sick_*animal* ** Description: Three identical functions to apply ** sickness to the respective animal, deduct for care, ** or kill the animal if it cannot be afforded. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void sick_tiger(); void sick_bear(); void sick_sealion(); /****************************************************** ** Function: kill_*animl* ** Description: Kills an animal and removes it from the ** zoo. ** Parameters: int ** Pre-conditions: Take in an integer to represent which ** of the *animal* to kill. ** Post-conditions: Unchanged. ******************************************************/ void kill_tiger(int); void kill_bear(int); void kill_sealion(int); /****************************************************** ** Function: count_animals ** Description: Counts the adult and baby animals of ** each species. ** Parameters: int &, int &, int &, int &, int &, int & ** Pre-conditions: Take in pointers to integer values ** representing the counts of the adult and baby members ** of each species. ** Post-conditions: Set those integer values to the ** correct values. ******************************************************/ void count_animals(int &, int &, int &, int &, int &, int &); /****************************************************** ** Function: is_loss ** Description: Tests the user to see if they have lost ** the game. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ bool is_loss(); /****************************************************** ** Function: birth ** Description: Function for an animal giving birth to ** offspring. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void birth(); /****************************************************** ** Function: apply_sick ** Description: Simple function that applies sickness ** to the animal if possible. ** Parameters: bool, bool, bool ** Pre-conditions: Take in three boolean values to show ** which species have a member to even get sick. ** Post-conditions: Unchanged. ******************************************************/ bool apply_sick(bool, bool, bool); /****************************************************** ** Function: sick ** Description: Gets one random animal sick and the ** zookeeper must care for them. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void sick(); /****************************************************** ** Function: special_event ** Description: Simple hub for the speciale event to be ** selected and then call the associated function. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void special_event(); /****************************************************** ** Function: compute_food_cost ** Description: Compute the food cost for the turn and ** deduct it from the bank balance. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void compute_food_cost(); /****************************************************** ** Function: compute_revenue ** Description: Compute the revenue for the turn and ** add the net revenue to your balance. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void compute_revenue(); //TODO// Code this function /****************************************************** ** Function: turn_hub_function ** Description: This function acts as a hub to execute ** a single turn in the game. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void turn_hub_function(); /****************************************************** ** Function: purchase_tiger ** Description: Simple function that shallow copies the ** current tigers and adds dynamic memory to the end of ** the new array to add tigers. ** Parameters: int ** Pre-conditions: Takes in an int to represent the num ** of tigers to purchase. ** Post-conditions: Unchanged. ******************************************************/ void purchase_tiger(int, int); /****************************************************** ** Function: purchase_sea_lion ** Description: Simple function that shallow copies the ** current sea lions and adds dynamic memory to the end of ** the new array to add sea lions. ** Parameters: int ** Pre-conditions: Takes in an int to represent the num ** of sea lions to purchase. ** Post-conditions: Unchanged. ******************************************************/ void purchase_sea_lion(int, int); /****************************************************** ** Function: purchase_bear ** Description: Simple function that shallow copies the ** current bears and adds dynamic memory to the end of ** the new array to add bears. ** Parameters: int ** Pre-conditions: Takes in an int to represent the num ** of bears to purchase. ** Post-conditions: Unchanged. ******************************************************/ void purchase_bear(int, int); /****************************************************** ** Function: animal_purchase_choice ** Description: Simple driver with user input to direct ** the choice to purchase or not, and how many to buy. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void animal_purchase_choice(); /****************************************************** ** Function: purchase_animal ** Description: Function to purchase animals. ** Parameters: int ** Pre-conditions: Take in the number of animals the ** user wants to buy. ** Post-conditions: Unchanged. ******************************************************/ //? Place functions in each animal class or keep everything here using accessors and mutators. ////void purchase_animal(int); //TODO Code this function /****************************************************** ** Function: increment_ages ** Description: Ages all of the animals forward by one ** month. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ void increment_ages(); //TODO// Code this function //! ACCESSOR FUNCTIONS /****************************************************** ** Function: get_tiger_count ** Description: Simple accessor for the tiger count ** member variable. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ int get_tiger_count(); //TODO// Code this accessor /****************************************************** ** Function: get_sea_lion_count ** Description: Simple accessor for the sea lion count ** member variable. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ int get_sea_lion_count(); //TODO// Code this accessor /****************************************************** ** Function: get_bear_count ** Description: Simple accessor for the bear count ** member variable. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ int get_bear_count(); //TODO// Code this accessor /****************************************************** ** Function: get_bank_balance ** Description: Simple accessor for the bank_balance ** member variable. ** Parameters: NA ** Pre-conditions: NA ** Post-conditions: NA ******************************************************/ int get_bank_balance(); //TODO// Code this accessor //! MUTATOR FUNCTIONS /****************************************************** ** Function: set_bank_balance ** Description: Simple mutator for the bank_balance ** member variable. ** Parameters: int ** Pre-conditions: Take in an integer value of the new ** bank balance. ** Post-conditions: Unchanged. ******************************************************/ void set_bank_balance(int); //TODO// Code this mutator }; #endif
//知识点:二分答案,前缀和 /* By:Luckyblock 题目要求: 给定 一数列a, 给定m个区间[li,ri], 给定一参数S 可任意选择 参数W的值 区间i的贡献 Yi = ∑(区间内>=W的数的数量) * ∑(区间内>=W的数的权值和) 总贡献 = abs(∑Yi - S); 求 令总贡献最小的 参数W的值 分析题意: - 对于所求的 W, 发现如下性质: 当 W 单增时, wj大于等于W的 元素数量 单减, 总贡献Y单减 当 W 单减时, wj大于等于W的 元素数量 单增, 总贡献Y单增 发现 W 的取值 与Y呈 负相关, 则可以通过二分答案 枚举W; - 当 W 确定时, 考虑如何求得Y, 以检查答案的优劣性 1.暴力枚举! 对于 每一个所求区间, 暴力枚举其中合法元素, 并暴力计算 复杂度 O(nm) , 必然会被卡掉 2.要求 区间内合法元素数 及 区间内合法元素的和 显然, 所求的 两量满足可减性 , 可以使用前缀和 O(n)维护 , 并可O(1) 求得每个区间内 两量 就可 O(1)计算出 单个区间的贡献 复杂度 O(n) */ #include<cstdio> #include<ctype.h> #include<cstdlib> #define max(a,b) (a>b?a:b) #define int long long const int MARX = 2e5+10; //============================================================= int n, m, S, ans, maxw , w[MARX], v[MARX]; int l[MARX], r[MARX];//查询的m个区间 int sum1[MARX], sum2[MARX]; //sum1,2为 两前缀和数组, 1为满足条件的 矿石个数, 2为满足条件的 矿石 价值和 //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch); ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch); ch=getchar()) w = w*10+ch-'0'; return s*w; } int abs(int x) {return (x<0?-x:x);}//绝对值 函数 bool check(int W,int &sum) { sum = 0; for(int i = 1; i <= n; i ++) //维护两前缀和 sum1[i] = sum1[i-1] + (w[i] >= W), sum2[i] = sum2[i-1] + v[i] * (w[i] >= W); for(int i = 1; i <= m; i ++)//枚举查询区间 { int l1 = l[i], r1 = r[i];//计算 区间的贡献 sum += (sum1[r1]-sum1[l1-1]) * (sum2[r1]-sum2[l1-1]); } return sum > S;//检查答案优劣性 } //============================================================= signed main() { n = read(),m = read(), S = read(); for(int i = 1; i <= n; i ++) { w[i] = read(), v[i] = read(); maxw = max(maxw,w[i]); } for(int i =1 ; i <= m; i ++) l[i] = read(), r[i] = read(); for(int l = 1,r = maxw; l <= r;)//二分枚举 参数W { int mid = (l + r) >> 1, sum; if(check(mid,sum)) l = mid + 1; else r = mid - 1; if(abs(sum - S) < abs(ans - S)) ans = sum;//更新答案 } printf("%lld",abs(ans - S)); }
#ifndef TINKER_INTERFACE_HPP #define TINKER_INTERFACE_HPP #include <cstdint> /* Here is the minimal c++ side Fortran interface to tinker (see tinker_interface.f95 for fortran side) * * Any Fortran subroutine should be called using only pointers, and the return type is always void * * In C++ they should be declared within a extern "C" block * */ #define TINKER_ARGSLEN 240 /** * @brief This makes variables declared in the Fortran module tinker_cpp acessible from C++ */ extern const int32_t natoms; extern double* x; extern double* y; extern double* z; extern double* vx; extern double* vy; extern double* vz; extern "C" { /** * @brief Provides the pseudo command line parameters to the tinker fortran code * * @param n_args number of strings stored in arguments_concatenated : the total size of the arguments_concatenated string will be 240*n_args characters * @param arguments_concatenated a long string containing arguments : they are concatenated, each argument was a string of exactly 240 characters * */ void tinker_initialization(int32_t* n_args, char arguments_concatenated[]); /** * @brief Routine setting up integrator * * @param numSteps Number of steps to perform * @param delta_t The time step in picoseconds */ void tinker_setup_integration(int32_t* numSteps, double* delta_t); /** * @brief Routine setting up simulation for NVT ensemble * * @param temperature Temperature in Kelvin * @param tau_temp Temperature coupling in ps */ void tinker_setup_NVT(double* temperature, double* tau_temp); /** * @brief Routine setting up simulation for NPT ensemble * * @param temperature Temperature in Kelvin * @param press Pressure in atmospheres * @param tau_temp Temperature coupling in ps * @param tau_press Pressure coupling in ps */ void tinker_setup_NPT(double* temperature, double* press, double* tau_temp, double* tau_press); /** * @brief Routine for seeting frequency of writing to stdout or to traj files * * NOTE This should be called after tinker_setup_NVT or tinker_setup_NPT * * NOTE To disable I/O set those to a really large value * * @param write_freq Freq for writing trajectory to archive file * @param print_freq Freq for writing info to stdout */ void tinker_setup_IO(int32_t* write_freq, int32_t* print_freq); /** * @brief Perform one integration step * * @param istep The current step number */ void tinker_stochastic_one_step(int32_t* istep); /** * @brief Perform nsteps integration steps * * @param istep The current step number * @param nsteps The number of steps to perform */ void tinker_stochastic_n_steps(int32_t* istep, int32_t* nsteps); /** * @brief Retrieve coordinates and velocities from Tinker * * They will be stored in pointers x y z vx vy vz : they are of size natoms and have been allocated/freed by the fortran module. */ void tinker_get_crdvels(); /** * @brief Provide to Tinker x y z coordinates and vx vy vz velocities * * They areretrieved from pointers x y z vx vy vz : they are of size natoms and have been allocated/freed by the fortran module. */ void tinker_set_crdvels(); /** * @brief Finalize the Tinker code * */ void tinker_finalize(); } #endif /* TINKER_INTERFACE_HPP */
/* SettingsWnd.cpp Source file for class SettingsWnd. @author: Martin Terneborg. */ #include "SettingsWnd.h" #include <CommCtrl.h> #include "InitCtrls.h" #define CONTROLTEXT_MAXREFRESHRATE L"Max refresh rate:" #define CONTROLTEXT_SAMPLESIZE L"Sample size:" #define CONTROLTEXT_SAVEANDEXIT L"Save && exit" #define CONTROLTEXT_CANCEL L"Cancel" #define CONTROLTEXT_ONLYPRIMARYMONITOR L"Use only primary monitor" #define CONTROLTEXT_MULTITHREADING L"Multithreading" #define CONTROLTEXT_BAUDRATE L"Baud rate:" #define CONTROLTEXT_CLOCKWISE L"Clockwise" #define TEXTLIMIT_REFRESHRATE 3 #define TEXTLIMIT_SAMPLESIZE 3 #define TEXTLIMIT_BAUDRATE 6 CONST LPCWSTR SettingsWnd::m_TITLE = L"Settings"; /* The window's message procedure. */ LRESULT CALLBACK SettingsWnd::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: //Store the pointer to the settings object SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG)((LPCREATESTRUCT)lParam)->lpCreateParams); break; case WM_COMMAND: switch (LOWORD(wParam)) { case m_CONTROL_ID::CANCEL_BUTTON: SendMessage(hWnd, WM_CLOSE, NULL, NULL); break; case m_CONTROL_ID::SAVE_BUTTON: { //Retrieve the pointer to the settings object Settings * settings = (Settings*)GetWindowLongPtr(hWnd, GWLP_USERDATA); Settings oldSettings = *settings; if (!GetSettings(hWnd, settings)) { MessageBox(hWnd, L"Failed to retrieve settings.", L"Error!", MB_ICONERROR); *settings = oldSettings; } else { DestroyWindow(hWnd); } break; } } break; case WM_CLOSE: //Check if any of the controls have been modified Settings * settings; settings = (Settings*)GetWindowLongPtr(hWnd, GWLP_USERDATA); BOOL bModified; bModified = SendMessage(GetDlgItem(hWnd, m_CONTROL_ID::REFRESHRATE_EDIT), EM_GETMODIFY, NULL, NULL) || SendMessage(GetDlgItem(hWnd, m_CONTROL_ID::SAMPLESIZE_EDIT), EM_GETMODIFY, NULL, NULL); //If any of the controls have been modified prompt the user with a button asking if he/she wants to //discard the changes. if(bModified) { if (MessageBox(hWnd, L"Settings has been changed, discard changes?", L"Warning", MB_ICONASTERISK | MB_OKCANCEL) == IDOK) { DestroyWindow(hWnd); } } else { DestroyWindow(hWnd); } break; case WM_DESTROY: SendMessage(GetWindow(hWnd, GW_OWNER), WM_PARENTNOTIFY, WM_DESTROY, (LPARAM)hWnd); //TODO: This shouldn't be called manually break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } /* Registers the window's class. @return The unique class atom of the window class. */ ATOM SettingsWnd::Register() { WNDCLASSEX wc; wc.cbClsExtra = 0; wc.cbSize = sizeof(WNDCLASSEX); wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = NULL; wc.hIconSm = NULL; wc.hInstance = GetModuleHandle(NULL); wc.lpfnWndProc = WndProc; wc.lpszClassName = m_TITLE; wc.lpszMenuName = NULL; wc.style = CS_HREDRAW | CS_VREDRAW; return RegisterClassEx(&wc); } /* Gets all the settings from the controls. @param hWnd: A handle to the (settings) window. @param settings: A pointer to the settings object to be filled with the settings. @return TRUE if all settings are successfully retrieved, otherwise FALSE. */ BOOL SettingsWnd::GetSettings(CONST HWND hWnd, Settings * CONST settings) { //Get the max refresh rate BOOL refreshRateSuccess; UINT8 refreshRate = GetDlgItemInt(hWnd, m_CONTROL_ID::REFRESHRATE_EDIT, &refreshRateSuccess, FALSE); //Get the sample size BOOL sampleSizeSuccess; UINT sampleSize = GetDlgItemInt(hWnd, m_CONTROL_ID::SAMPLESIZE_EDIT, &sampleSizeSuccess, FALSE); //Get the baud rate BOOL baudRateSuccess; UINT baudRate = GetDlgItemInt(hWnd, m_CONTROL_ID::BAUDRATE_EDIT, &baudRateSuccess, FALSE); //Get the status of the checkboxes BOOL bPrimaryMonitor = SendMessage(GetDlgItem(hWnd, m_CONTROL_ID::PRIMARYMONITOR_CHECKBOX), BM_GETCHECK, NULL, NULL) == BST_CHECKED ? BST_CHECKED : BST_UNCHECKED; BOOL bMultiThreading = SendMessage(GetDlgItem(hWnd, m_CONTROL_ID::MULTITHREADING_CHECKBOX), BM_GETCHECK, NULL, NULL) == BST_CHECKED ? BST_CHECKED : BST_UNCHECKED; //Get the selected monitors std::vector<Monitor> allMonitors = Monitor::GetMonitors(); std::vector<Monitor> selectedMonitors; for (INT i = 0; i < ListView_GetItemCount(GetDlgItem(hWnd, m_CONTROL_ID::MONITOR_LIST)); i++) { //If item is checked if (ListView_GetCheckState(GetDlgItem(hWnd, m_CONTROL_ID::MONITOR_LIST), i)) { //Get the item LVITEM lvItem; lvItem.mask = LVIF_PARAM; lvItem.iItem = i; ListView_GetItem(GetDlgItem(hWnd, m_CONTROL_ID::MONITOR_LIST), &lvItem); HMONITOR hMonitor = (HMONITOR)lvItem.lParam; //Find the matching monitor by comparing handles for (UINT j = 0; j < allMonitors.size(); j++) { if (allMonitors.at(j).GetMonitorHandle() == hMonitor) { selectedMonitors.push_back(allMonitors.at(j)); } } } } //Copy over all old settings for the monitor if it was previously selected for (UINT i = 0; i < selectedMonitors.size(); i++) { for (UINT j = 0; j < settings->m_usedMonitors.size(); j++) { if (selectedMonitors.at(i).GetMonitorHandle() == settings->m_usedMonitors.at(j).GetMonitorHandle()) { Monitor oldMonitor = settings->m_usedMonitors.at(j); selectedMonitors.at(i).SetLeftLeds(oldMonitor.GetLeftLeds()); selectedMonitors.at(i).SetRightLeds(oldMonitor.GetRightLeds()); selectedMonitors.at(i).SetTopLeds(oldMonitor.GetTopLeds()); selectedMonitors.at(i).SetBottomLeds(oldMonitor.GetBottomLeds()); selectedMonitors.at(i).SetPosX(oldMonitor.GetPosX()); selectedMonitors.at(i).SetPosY(oldMonitor.GetPosY()); break; } } } //If every setting was retrieved successfully if (sampleSizeSuccess && refreshRateSuccess && baudRateSuccess) { settings->m_maxRefreshRate = refreshRate; settings->m_sampleSize = sampleSize; settings->m_bMultiThreading = bMultiThreading; settings->m_bUsePrimaryMonitor = bPrimaryMonitor; settings->m_nBaudRate = baudRate; settings->m_usedMonitors.clear(); settings->m_usedMonitors = selectedMonitors; return TRUE; } else { return FALSE; } } /* Creates the window. @param hWndParent, A reference to a handle to the parent (main) window @param settings, A reference to the settings object that the window will save the settings to. @return TRUE if the window was created successfully, otherwise FALSE. */ BOOL SettingsWnd::Create(CONST HWND hWndParent, CONST Settings &settings) { if (hWndParent == NULL) { return FALSE; } Register(); HWND hWnd = CreateWindow( m_TITLE, m_TITLE, WS_POPUPWINDOW | WS_VISIBLE | WS_CAPTION, CW_USEDEFAULT, CW_USEDEFAULT, 500, 300, hWndParent, NULL, GetModuleHandle(NULL), (LPVOID)&settings); if (hWnd == NULL) { return FALSE; } InitControls(hWnd, settings); UpdateWindow(hWnd); ShowWindow(hWnd, SW_SHOW); return TRUE; } /* Initializes all the controls of the window. @param hWndParent: A handle to the parent (settings) window. @param settings: A reference to the settings object containing the settings of the program. @return TRUE if successful, otherwise FALSE. */ BOOL SettingsWnd::InitControls(CONST HWND hWndParent, CONST Settings &settings) { //TODO: Check for and handle null handles HWND hTxt; RECT txtRect; //Refresh rate hTxt = InitTextCtrl(hWndParent, CONTROLTEXT_MAXREFRESHRATE, 0, 0, NULL); GetClientRect(hTxt, &txtRect); //Get the text dimensions HWND hRefRate = InitEditCtrl(hWndParent, txtRect.right, 0, 20, 20, (HMENU)m_CONTROL_ID::REFRESHRATE_EDIT); SendMessage(hRefRate, EM_SETLIMITTEXT, (WPARAM)TEXTLIMIT_REFRESHRATE, NULL); SetDlgItemInt(hWndParent, m_CONTROL_ID::REFRESHRATE_EDIT, settings.m_maxRefreshRate, FALSE); //Sample size hTxt = InitTextCtrl(hWndParent, CONTROLTEXT_SAMPLESIZE, 0, 25, NULL); GetClientRect(hTxt, &txtRect); //Get the text dimensions HWND hSs = InitEditCtrl(hWndParent, txtRect.right, 25, 20, 20, (HMENU)m_CONTROL_ID::SAMPLESIZE_EDIT); SendMessage(hSs, EM_SETLIMITTEXT, (WPARAM)TEXTLIMIT_SAMPLESIZE, NULL); SetDlgItemInt(hWndParent, m_CONTROL_ID::SAMPLESIZE_EDIT, settings.m_sampleSize, FALSE); //Baud rate hTxt = InitTextCtrl(hWndParent, CONTROLTEXT_BAUDRATE, 0, 50, NULL); GetClientRect(hTxt, &txtRect); //Get the text dimensions HWND hBaud = InitEditCtrl(hWndParent, txtRect.right, 50, 20, 20, (HMENU)m_CONTROL_ID::BAUDRATE_EDIT); SendMessage(hBaud, EM_SETLIMITTEXT, (WPARAM)TEXTLIMIT_BAUDRATE, NULL); SetDlgItemInt(hWndParent, m_CONTROL_ID::BAUDRATE_EDIT, settings.m_nBaudRate, FALSE); InitMonitorList(hWndParent, 0, 80, settings.m_usedMonitors); RECT clientRect; GetClientRect(hWndParent, &clientRect); CONST auto BUTTONWIDTH = 100, BUTTONHEIGHT = 20; //Save and exit HWND hSaveExit = InitBtnCtrl(hWndParent, clientRect.right / 2 - BUTTONWIDTH, clientRect.bottom - BUTTONHEIGHT, BUTTONWIDTH, BUTTONHEIGHT, CONTROLTEXT_SAVEANDEXIT, (HMENU)m_CONTROL_ID::SAVE_BUTTON); //Cancel HWND hCancel = InitBtnCtrl(hWndParent, clientRect.right / 2, clientRect.bottom - BUTTONHEIGHT, BUTTONWIDTH, BUTTONHEIGHT, CONTROLTEXT_CANCEL, (HMENU)m_CONTROL_ID::CANCEL_BUTTON); //Only primary monitor HWND hPrimaryMonitor = InitCheckboxCtrl(hWndParent, 0, 180, CONTROLTEXT_ONLYPRIMARYMONITOR, (HMENU)m_CONTROL_ID::PRIMARYMONITOR_CHECKBOX); SendMessage(hPrimaryMonitor, BM_SETCHECK, (WPARAM)settings.m_bUsePrimaryMonitor ? TRUE : FALSE, NULL); //Multithreading HWND hMultithreading = InitCheckboxCtrl(hWndParent, 0, 200, CONTROLTEXT_MULTITHREADING, (HMENU)m_CONTROL_ID::MULTITHREADING_CHECKBOX); SendMessage(hMultithreading, BM_SETCHECK, (WPARAM)settings.m_bMultiThreading ? TRUE : FALSE, NULL); return TRUE; } /* Initializes the monitor list and text control. @param hWndParent: A handle to the parent (settings) window. @param x: The horizontal position of the monitor list. @param y: The vertical position of the monitor list. @param selectedMonitors: A vector containing all currently selected monitors. */ VOID SettingsWnd::InitMonitorList(CONST HWND hWndParent, CONST INT x, CONST INT y, CONST std::vector<Monitor> &selectedMonitors) { HWND hList = CreateWindow( WC_LISTVIEW, L"", WS_CHILD | WS_VISIBLE | WS_BORDER | LVS_REPORT | LVS_EDITLABELS, x, y, 200, 100, hWndParent, (HMENU)m_CONTROL_ID::MONITOR_LIST, GetModuleHandle(NULL), NULL); if (hList == NULL) { throw L"Error initialzing ListView-Control: Monitor List!"; } ListView_SetExtendedListViewStyle(hList, LVS_EX_CHECKBOXES | LVS_EX_GRIDLINES); //Insert the column LVCOLUMN lvColumn; lvColumn.cx = 200; lvColumn.fmt = LVCFMT_LEFT; lvColumn.pszText = L"Monitor"; lvColumn.iSubItem = 0; lvColumn.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; ListView_InsertColumn(hList, 0, &lvColumn); LVITEM lvItem; lvItem.mask = LVIF_TEXT | LVIF_PARAM; lvItem.iSubItem = 0; lvItem.stateMask = 0; //TODO: This line might not be necessary std::vector<Monitor> allMonitors = Monitor::GetMonitors(); for (UINT i = 0; i < allMonitors.size(); i++) { //Add the monitor to the list std::wstring monitorName(allMonitors.at(i).GetMonitorName()); lvItem.pszText = (LPTSTR)monitorName.c_str(); lvItem.iItem = i; lvItem.lParam = (LPARAM)allMonitors.at(i).GetMonitorHandle(); ListView_InsertItem(hList, &lvItem); //Check if monitor is selected for (UINT j = 0; j < selectedMonitors.size(); j++) { if (selectedMonitors.at(j).GetMonitorHandle() == allMonitors.at(i).GetMonitorHandle()) { ListView_SetCheckState(hList, i, TRUE); //Set it as checked break; } } } }
extern int qInitResources_skipRccGood(); int main(int, char**) { // Fails to link if the symbol is not present. qInitResources_skipRccGood(); return 0; }
// This file is part of HemeLB and is Copyright (C) // the HemeLB team and/or their institutions, as detailed in the // file AUTHORS. This software is provided under the terms of the // license in the file LICENSE. #include "extraction/PropertyActor.h" namespace hemelb { namespace extraction { PropertyActor::PropertyActor(const lb::SimulationState& simulationState, const std::vector<PropertyOutputFile*>& propertyOutputs, IterableDataSource& dataSource, reporting::Timers& timers, const net::IOCommunicator& ioComms) : simulationState(simulationState), timers(timers) { propertyWriter = new PropertyWriter(dataSource, propertyOutputs, ioComms); } PropertyActor::~PropertyActor() { delete propertyWriter; } void PropertyActor::SetRequiredProperties(lb::MacroscopicPropertyCache& propertyCache) { const std::vector<LocalPropertyOutput*>& propertyOutputs = propertyWriter->GetPropertyOutputs(); // Iterate over each property output spec. for (unsigned output = 0; output < propertyOutputs.size(); ++output) { const LocalPropertyOutput* propertyOutput = propertyOutputs[output]; // Only consider the ones that are being written this iteration. if (propertyOutput->ShouldWrite(simulationState.GetTimeStep())) { const PropertyOutputFile* outputFile = propertyOutput->GetOutputSpec(); // Iterate over each field. for (unsigned outputField = 0; outputField < outputFile->fields.size(); ++outputField) { // Set the cache to calculate each required field. switch (outputFile->fields[outputField].type) { case (OutputField::Pressure): propertyCache.densityCache.SetRefreshFlag(); break; case OutputField::Velocity: propertyCache.velocityCache.SetRefreshFlag(); break; case OutputField::ShearStress: propertyCache.wallShearStressMagnitudeCache.SetRefreshFlag(); break; case OutputField::VonMisesStress: propertyCache.vonMisesStressCache.SetRefreshFlag(); break; case OutputField::ShearRate: propertyCache.shearRateCache.SetRefreshFlag(); break; case OutputField::StressTensor: propertyCache.stressTensorCache.SetRefreshFlag(); break; case OutputField::Traction: propertyCache.tractionCache.SetRefreshFlag(); break; case OutputField::TangentialProjectionTraction: propertyCache.tangentialProjectionTractionCache.SetRefreshFlag(); break; case OutputField::Distributions: // We don't actually have to cache anything to get the distribution break; case OutputField::MpiRank: // We don't actually have to cache anything to get the rank. break; default: // This assert should never trip. It only occurs when someone adds a new field to OutputField // and forgets adding a new case to the switch assert(false); } } } } } void PropertyActor::EndIteration() { timers[reporting::Timers::extractionWriting].Start(); propertyWriter->Write(simulationState.GetTimeStep()); timers[reporting::Timers::extractionWriting].Stop(); } } }
#include <string> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <list> #include <algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <numeric> #include <bitset> #include <deque> //#include <random> #include <string.h> #include <stdlib.h> #include <vector> #include <unordered_map> #include <thread> const long long LINF = (5e18); const int INF = (1<<30); const int sINF = (1<<23); const int MOD = 1000000009; const double EPS = 1e-6; using namespace std; struct edge { int to, cap, cost, rev; edge(int t, int cap, int cost, int r) : to(t), cap(cap), cost(cost), rev(r) {} }; class MinCostFlow { vector<vector<edge>> G; vector<int> prevv, preve; int dist[1000]; int V; public: MinCostFlow(int n) { init(n); } void init(int n) { V = n; preve.clear(); preve.resize(V); prevv.clear(); prevv.resize(V); G.clear(); G.resize(V); } void add_edge(int from, int to, int cap, int cost) { G[from].push_back(edge(to, cap, cost, (int)G[to].size())); G[to].push_back(edge(from, 0, -cost, (int)G[from].size()-1)); } int min_cost_flow(int s, int t, int f) { int res = 0; while (f > 0) { fill(dist, dist+V, INF); dist[s] = 0; bool update = true; while (update) { update = false; for (int v=0; v<V; ++v) { if (dist[v] == INF) continue; for (int i=0; i<G[v].size(); ++i) { edge &e = G[v][i]; if (e.cap > 0 && dist[e.to] > dist[v] + e.cost) { dist[e.to] = dist[v] + e.cost; prevv[e.to] = v; preve[e.to] = i; update = true; } } } } if (dist[t] == INF) { return -1; } int d = f; for (int v=t; v!=s; v=prevv[v]) d = min(d, G[prevv[v]][preve[v]].cap); f -= d; res += d * dist[t]; for (int v=t; v!=s; v=prevv[v]) { edge &e = G[prevv[v]][preve[v]]; e.cap -= d; G[v][e.rev].cap += d; } } return res; } }; class GoodCompanyDivOne { public: vector<int> superior, training; int dp[35][35]; int N, K; int f(int x, int p) { if (dp[x][p] != -1) return dp[x][p]; vector<int> y(1, x); for (int i=0; i<N; ++i) { if (superior[i] == x) { y.push_back(i); } } int m = (int)y.size(); vector<vector<int>> table(m, vector<int>(K, INF)); for (int i=0; i<K; ++i) { if (i == p) continue; table[0][p] = min(table[0][p], training[i]); table[0][i] = training[i]; } for (int j=1; j<m; ++j) { for (int i=0; i<K; ++i) { table[j][i] = f(y[j], i); } } unique_ptr<MinCostFlow> G(new MinCostFlow(m+K+2)); int source = m+K, sink = m+K+1; for(int i=0; i<m; ++i) G->add_edge(source, i, 1, 0); for(int i=0; i<K; ++i) G->add_edge(m+i, sink, 1, 0); for (int j=0; j<m; ++j) { for (int i=0; i<K; ++i) { G->add_edge(j, m+i, 1, table[j][i]); } } int t = G->min_cost_flow(source, sink, m); int res; if (t == -1) res = sINF; else res = t + training[p]; return dp[x][p] = res; } int minimumCost(vector <int> superior, vector <int> training) { this->superior = superior; this->training = training; memset(dp, -1, sizeof(dp)); this->N = (int)superior.size(); int root = -1; for (int i=0; i<N; ++i) if (superior[i] == -1) root = i; this->K = (int)training.size(); int ans = sINF; for (int i=0; i<K; ++i) ans = min(ans, f(root, i)); return ans == sINF ? -1 : 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(); } 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 int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {-1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(0, Arg2, minimumCost(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {-1, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 10; verify_case(1, Arg2, minimumCost(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {-1, 0, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = -1; verify_case(2, Arg2, minimumCost(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {-1, 0, 0, 2, 2, 2, 1, 1, 6, 0, 5, 4, 11, 10, 3, 6, 11, 7, 0, 2, 13, 14, 2, 10, 9, 11, 22, 10, 3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {4, 2, 6, 6, 8, 3, 3, 1, 1, 5, 8, 6, 8, 2, 4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 71; verify_case(3, Arg2, minimumCost(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { GoodCompanyDivOne ___test; ___test.run_test(-1); } // END CUT HERE
#include <iostream> using namespace std; class Circle { public: float radius, area; public: void read(); void compute(); void display(); }; void Circle::read() { cout << "Enter the radius : "; cin >> radius; } void Circle::compute() { area = 3.14 * radius * radius; } void Circle::display() { cout << "Area : " << area << endl; } int main() { Circle c; c.read(); c.compute(); c.display(); }
//---------------------------------------------------------------- // Icon.cpp // // Copyright 2002-2004 Raven Software //---------------------------------------------------------------- #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" #include "Icon.h" /* =============== rvIcon::rvIcon =============== */ rvIcon::rvIcon() { iconHandle = -1; } /* =============== rvIcon::~rvIcon =============== */ rvIcon::~rvIcon() { FreeIcon(); } /* =============== rvIcon::FreeIcon =============== */ void rvIcon::FreeIcon( void ) { if ( iconHandle != - 1 ) { gameRenderWorld->FreeEntityDef( iconHandle ); iconHandle = -1; } } /* =============== rvIcon::CreateIcon =============== */ qhandle_t rvIcon::CreateIcon( const char *mtr, int suppressViewID ) { FreeIcon(); memset( &renderEnt, 0, sizeof( renderEnt ) ); renderEnt.origin = vec3_origin; renderEnt.axis = mat3_identity; renderEnt.shaderParms[ SHADERPARM_RED ] = 1.0f; renderEnt.shaderParms[ SHADERPARM_GREEN ] = 1.0f; renderEnt.shaderParms[ SHADERPARM_BLUE ] = 1.0f; renderEnt.shaderParms[ SHADERPARM_ALPHA ] = 1.0f; renderEnt.shaderParms[ SHADERPARM_SPRITE_WIDTH ] = 16.0f; renderEnt.shaderParms[ SHADERPARM_SPRITE_HEIGHT ] = 16.0f; renderEnt.hModel = renderModelManager->FindModel( "_sprite" ); renderEnt.callback = NULL; renderEnt.numJoints = 0; renderEnt.joints = NULL; renderEnt.customSkin = 0; renderEnt.noShadow = true; renderEnt.noSelfShadow = true; renderEnt.customShader = declManager->FindMaterial( mtr ); renderEnt.referenceShader = 0; renderEnt.bounds = renderEnt.hModel->Bounds( &renderEnt ); renderEnt.suppressSurfaceInViewID = suppressViewID; iconHandle = gameRenderWorld->AddEntityDef( &renderEnt ); return iconHandle; } /* =============== rvIcon::UpdateIcon =============== */ void rvIcon::UpdateIcon( const idVec3 &origin, const idMat3 &axis ) { assert( iconHandle >= 0 ); renderEnt.origin = origin; renderEnt.axis = axis; gameRenderWorld->UpdateEntityDef( iconHandle, &renderEnt ); } int rvIcon::GetWidth( void ) const { return renderEnt.shaderParms[ SHADERPARM_SPRITE_WIDTH ]; } int rvIcon::GetHeight( void ) const { return renderEnt.shaderParms[ SHADERPARM_SPRITE_HEIGHT ]; }
#pragma once #include <istream> #include <Poco/SAX/SAXParser.h> #include <Poco/XML/NamePool.h> #include <Poco/DOM/Document.h> namespace Poco { namespace XML { class XMLReader; } } namespace BeeeOn { class DenyDTDHandler; /** * The parser prevents parsing documents containing DTD definitions. * The purpose is to protect the system against XML attacks like: * * * Generic Entity Expansion * * Recursive Entity Expansion * * XML Remote Entity Expansion * * The parser throws InvalidArgumentException when a DTD section * is encountered. * * Parsing is thread-safe as for each parsing step a new parser * is allocated. */ class SecureXmlParser { public: SecureXmlParser(); ~SecureXmlParser(); Poco::XML::Document *parse(const char *input, std::size_t length); Poco::XML::Document *parse(const std::string &input); Poco::XML::Document *parse(std::istream &in); private: void secure(Poco::XML::XMLReader &reader, DenyDTDHandler &handler); }; }
/* * Ещё одна реализация шаблона посетителя, который проверяет типы данных переменных и методов */ #pragma once #include "Visitor.h" #include "Table.h" #include <assert.h> class CTypeChecker : public IVisitor { public: CTypeChecker( CSymbolsTable::CTable *_table ) : table( _table ), currentClass( NULL ), currentMethod( NULL ), isCorrect( true ) { assert( _table != NULL ); }; bool IsAllCorrect() const { return isCorrect; }; // Является ли последний полученный тип обозначением встроенного типа данных static bool IsLastTypeBuiltIn( Symbol::CSymbol* type ) { return ( type == Symbol::CSymbol::GetSymbol( "int" ) || type == Symbol::CSymbol::GetSymbol( "int[]" ) || type == Symbol::CSymbol::GetSymbol( "boolean" ) ); } void Visit( const CProgram* node ); void Visit( const CMainClassDeclaration* node ); void Visit( const CClassDeclaration* node ); void Visit( const CClassExtendsDeclaration* node ); void Visit( const CClassDeclarationList* node ); void Visit( const CVariableDeclaration* node ); void Visit( const CVariableDeclarationList* node ); void Visit( const CMethodDeclaration* node ); void Visit( const CMethodDeclarationList* node ); void Visit( const CFormalList* node ); void Visit( const CFormalRestList* node ); void Visit( const CBuiltInType* node ); void Visit( const CUserType* node ); void Visit( const CStatementList* node ); void Visit( const CStatementBlock* node ); void Visit( const CIfStatement* node ); void Visit( const CWhileStatement* node ); void Visit( const CPrintStatement* node ); void Visit( const CAssignmentStatement* node ); void Visit( const CArrayElementAssignmentStatement* node ); void Visit( const CBinaryOperatorExpression* node ); void Visit( const CIndexAccessExpression* node ); void Visit( const CLengthExpression* node ); void Visit( const CMethodCallExpression* node ); void Visit( const CIntegerOrBooleanExpression* node ); void Visit( const CIdentifierExpression* node ); void Visit( const CThisExpression* node ); void Visit( const CNewIntegerArrayExpression* node ); void Visit( const CNewObjectExpression* node ); void Visit( const CNegationExpression* node ); void Visit( const CParenthesesExpression* node ); void Visit( const CExpressionList* node ); private: bool isCorrect; // флаг, гласящий о том, что всё ли верно в программе с типами данных CSymbolsTable::CClassInformation* currentClass; // Текущий класс, в котором находится посетитель CSymbolsTable::CMethodInformation* currentMethod; // Текущий метод std::string lastTypeValue; // Переменная состояния CSymbolsTable::CTable* table; // таблица, к которой мы обращаемся };
# include <iostream> namespace std; int main() { //================================ for (int n=10; n>0; n--) { cout << n << ", "; if (n==5) { cout << "aborted!"; break; } } //================================ for (int n=5; n>0; n--) { if (n==3) continue; //Only when the number is 3, stip working but loop will not be broken cout << n << ", "; } //================================ system("pause") return 0; }
#pragma once #ifdef _WINDOWS #include <GL/glew.h> #endif #include <SDL.h> #include <SDL_opengl.h> #include <SDL_image.h> #include "ShaderProgram.h" #include "Entity.h" class Bullet{ public: Bullet(Entity* shooter); float getPositionX(); float getPositionY(); void Draw(GLuint textureID, ShaderProgram* program); void UpdateBullet(float elapsed); private: Entity* shooter; const float bullet_x; float timeLeftOver; float bullet_y; float speed; };
/////////////////////////////////// // Filename: InputClass.cpp ////////////////////////////////// #include "InputClass.h" InputClass::InputClass() { m_directInput = 0; m_keyboard = 0; m_mouse = 0; } InputClass::InputClass(const InputClass& other) { } InputClass::~InputClass() { } bool InputClass::Initialize(HINSTANCE hInstance, HWND hWnd, int screenWidth, int screenHeight) { HRESULT result; //store the screen size which will be used for positioning the mouse cursor m_screenWidth = screenWidth; m_screenHeight = screenHeight; //initialize the mouse location on screen m_mouseX = 0; m_mouseY = 0; //initialize the direct input object result = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_directInput, NULL); if (FAILED(result)) { return false; } //initialize the direct input object for the keyboard result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, NULL); if (FAILED(result)) { return false; } //set the data format result = m_keyboard->SetDataFormat(&c_dfDIKeyboard); if (FAILED(result)) { return false; } //set the cooperative level of the keyboard, DISCL_EXCLUSIVE makes it so the keyboard is used only by this program, DISCL_NONEXCLUSIVE is the opposite and the keyboard input is not exclusive to the program result = m_keyboard->SetCooperativeLevel(hWnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE); if (FAILED(result)) { return false; } //now acquire the keyboard result = m_keyboard->Acquire(); if (FAILED(result)) { return false; } //initialize the mouse object result = m_directInput->CreateDevice(GUID_SysMouse, &m_mouse, NULL); if (FAILED(result)) { return false; } //set the data format result = m_mouse->SetDataFormat(&c_dfDIMouse); if (FAILED(result)) { return false; } //the cooperative level result = m_mouse->SetCooperativeLevel(hWnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE); if (FAILED(result)) { return false; } //acquire the mouse result = m_mouse->Acquire(); if (FAILED(result)) { return false; } return true; } void InputClass::Shutdown() { //release the mouse if (m_mouse) { m_mouse->Unacquire(); m_mouse->Release(); m_mouse = 0; } //release the keyboard if (m_keyboard) { m_keyboard->Unacquire(); m_keyboard->Release(); m_keyboard = 0; } //release the main direct input object if (m_directInput) { m_directInput->Release(); m_directInput = 0; } return; } bool InputClass::Frame() { bool result; //read keyboard state result = ReadKeyboard(); if (!result) { return false; } //read mouse state result = ReadMouse(); if (!result) { return false; } //process the changes in the states ProcessInput(); return true; } bool InputClass::ReadKeyboard() { HRESULT result; //read the keyboard device result = m_keyboard->GetDeviceState(sizeof(m_keyboardButtons), (LPVOID)&m_keyboardButtons); if (FAILED(result)) { //if the keyboard was not acquired or something else is getting in the way if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { m_keyboard->Acquire(); } else { return false; } } return true; } bool InputClass::ReadMouse() { HRESULT result; //read the mouse device result = m_mouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&m_mouseState); if (FAILED(result)) { //if the mouse was not acquired or something else is getting in the way if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) { m_mouse->Acquire(); } else { return false; } } return true; } void InputClass::ProcessInput() { //update the location of the mouse cursor based on the change of the mouse location during the frame m_mouseX += m_mouseState.lX; m_mouseY += m_mouseState.lY; //ensure the mouse location doesn't exceed the screen width of height if (m_mouseX < 0) m_mouseX = 0; if (m_mouseY < 0) m_mouseY = 0; if (m_mouseX > m_screenWidth) m_mouseX = m_screenWidth; if (m_mouseY > m_screenHeight) m_mouseY = m_screenHeight; return; } bool InputClass::IsEscapePressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_ESCAPE] && 0x80) { return true; } return false; } bool InputClass::IsUpArrowPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_UP] && 0xC8) { return true; } return false; } bool InputClass::IsDownArrowPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_DOWN] && 0xD0) { return true; } return false; } bool InputClass::IsRightArrowPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_RIGHT] && 0xCD) { return true; } return false; } bool InputClass::IsLeftArrowPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_LEFT] && 0xCB) { return true; } return false; } bool InputClass::IsWPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_W] && 0x11) { return true; } return false; } bool InputClass::IsSPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_S] && 0x1F) { return true; } return false; } bool InputClass::IsAPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_A] && 0x1E) { return true; } return false; } bool InputClass::IsDPressed() { //is escape key being pressed?, bitwise & keyboard check if (m_keyboardButtons[DIK_D] && 0x20) { return true; } return false; } void InputClass::GetMouseLocation(int& mouseX, int& mouseY) { mouseX = m_mouseX; mouseY = m_mouseY; return; }
#include <Arduino.h> #include <FastLED.h> #include "Gamma.h" void Gamma::initPower(const float p) { for (int i=0; i<256; i++) { // Regular gamma function, gamma = 2.8 _lut[i] = powf((float)i/255, p) * 255 + 0.5; } } void Gamma::initAntiLog(const float p) { const float scaleBack = powf(2, p) - 1; for (int i=0; i<256; i++) { // rrrus's cool-mo-dee anti-log function, turns on sooner, // wider range of mid-tones. _lut[i] = ((powf(2, p * (float)i/255) - 1) / scaleBack) * 255 + 0.5; } }
#include "Chickens.h" Chickens::Chickens() { } Chickens::Chickens(string textureName) : Rect(textureName) { this->init(); pos = false; this->health = 1; nextChange = 0; } void Chickens::Update(GLfloat deltaTime) { } Chickens::~Chickens() { }
#pragma once #include <iosfwd> #include <cmath> #include "vector.h" #include "vector2.h" namespace sbg { template<typename T> struct Vector<3, T> { static_assert(std::is_arithmetic<T>::value, "Vector must be aritmetic"); using MathType = typename std::conditional<std::is_floating_point<T>::value, T, double>::type; constexpr Vector() : x{0}, y{0}, z{0} {} constexpr explicit Vector(T value) : x{value}, y{value}, z{value} {} constexpr Vector(T _x, T _y, T _z) : x{_x}, y{_y}, z{_z} {} template<typename O, typename std::enable_if<std::is_convertible<T, O>::value, int>::type = 0> constexpr inline operator Vector<3, O> () const { return Vector<3, O>{ static_cast<O>(x), static_cast<O>(y), static_cast<O>(z) }; } template<typename O, typename std::enable_if<is_strictly_explicitly_convertible<T, O>::value, int>::type = 0> constexpr explicit inline operator Vector<3, O> () const { return Vector<3, O>{ static_cast<O>(x), static_cast<O>(y), static_cast<O>(z) }; } Vector<2, MathType> angle() const { return Vector<2, double>(std::atan(y / x), std::acos(z / length())); } MathType length() const { return std::sqrt(power<2>(x) + power<2>(y) + power<2>(z)); } void applyAngle(const Vector<2, MathType> angles) { if (!null()) { auto lenght = length(); x = static_cast<T>(std::sin(angles.y) * std::cos(angles.x) * lenght); y = static_cast<T>(std::sin(angles.x) * std::sin(angles.y) * lenght); z = static_cast<T>(std::cos(angles.y) * lenght); } } Vector<3, T> angle(const Vector<2, MathType> angles) const { Vector<3, T> temp; if (!null()) { auto lenght = length(); temp.x = static_cast<T>(std::sin(angles.y) * std::cos(angles.x) * lenght); temp.y = static_cast<T>(std::sin(angles.x) * std::sin(angles.y) * lenght); temp.z = static_cast<T>(std::cos(angles.y) * lenght); } return temp; } void applyLenght(MathType lenght) { if (!null()) { auto product = lenght / length(); x *= static_cast<T>(product); y *= static_cast<T>(product); z *= static_cast<T>(product); } else { x = static_cast<T>(lenght); } } Vector<3, decltype(std::declval<T>() * std::declval<MathType>())> lenght(MathType lenght) { auto product = lenght / length(); return { x * product, y * product, z * product }; } Vector<3, T> project(const Vector<3, T>& other) const { return dot(other.unit()) * other; } bool null() const { return x == 0 && y == 0 && z == 0; } Vector<3, decltype((std::declval<T>() / std::declval<MathType>()))> unit() const { if (!null()) { auto lenght = length(); return {x / lenght, y / lenght, z / lenght}; } else { return {0, 0, 0}; } } template<typename U> constexpr Vector<3, decltype((std::declval<T>() * std::declval<U>()))> cross(const Vector<3, U>& other) const { return {y * other.z - z * other.y, -1 * x * other.z + z * other.x, x * other.y - y * other.x}; } template<typename U> constexpr auto dot(const Vector<3, U>& vec) const -> decltype((std::declval<T>() * std::declval<U>())) { return (x * vec.x) + (y * vec.y) + (z * vec.z); } Vector<3, T>& operator=(const Vector<3, T>& other) { x = other.x; y = other.y; z = other.z; return *this; } template<typename U> constexpr bool operator==(const Vector<3, U>& other) const { return x == other.x && y == other.y && z == other.z; } template<typename U> constexpr bool operator!=(const Vector<3, U>& other) const { return !(*this == other); } template<typename U> constexpr bool operator<(const Vector<3, U>& other) const { return ((x * x) + (y * y) + (z * z)) < ((other.x * other.x) + (other.y * other.y) + (other.z * other.z)); } template<typename U> constexpr bool operator>(const Vector<3, U>& other) const { return ((x * x) + (y * y) + (z * z)) > ((other.x * other.x) + (other.y * other.y) + (other.z * other.z)); } constexpr bool operator>(MathType length) const { return ((x * x) + (y * y) + (z * z)) > (length * length); } constexpr bool operator<(MathType length) const { return ((x * x) + (y * y) + (z * z)) < (length * length); } T x, y, z; constexpr static int size = 3; using type = T; }; template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator<(const Vector<3, T>& vec, U length) { return power<2>(vec.x) + power<2>(vec.y) + power<2>(vec.z) < static_cast<typename Vector<3, T>::MathType>(length * length); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator>(const Vector<3, T>& vec, U length) { return power<2>(vec.x) + power<2>(vec.y) + power<2>(vec.z) > static_cast<typename Vector<3, T>::MathType>(length * length); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator<(U length, const Vector<3, T>& vec) { return static_cast<typename Vector<3, T>::MathType>(length * length) < power<2>(vec.x) + power<2>(vec.y) + power<2>(vec.z); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator>(U length, const Vector<3, T>& vec) { return static_cast<typename Vector<3, T>::MathType>(length * length) > power<2>(vec.x) + power<2>(vec.y) + power<2>(vec.z); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<3, decltype(std::declval<T>() / std::declval<U>())> operator/(const Vector<3, T>& vec, U divider) { return {vec.x / divider, vec.y / divider, vec.z / divider}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<3, decltype(std::declval<T>() / std::declval<U>())> operator/(U divider, const Vector<3, T>& vec) { return {divider / vec.x, divider / vec.y, divider / vec.z}; } template<typename T, typename U> constexpr Vector<3, decltype(std::declval<T>() / std::declval<U>())> operator/(const Vector<3, T>& vec1, const Vector<3, U>& vec2) { return {vec1.x / vec2.x, vec1.y / vec2.y, vec1.z / vec2.z}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<3, decltype(std::declval<T>() * std::declval<U>())> operator*(const Vector<3, T>& vec, U multiplier) { return {vec.x * multiplier, vec.y * multiplier, vec.z * multiplier}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<3, decltype(std::declval<T>() * std::declval<U>())> operator*(U multiplier, const Vector<3, T>& vec) { return {vec.x * multiplier, vec.y * multiplier, vec.z * multiplier}; } template<typename T, typename U> constexpr Vector<3, decltype(std::declval<T>() * std::declval<U>())> operator*(const Vector<3, T>& vec1, const Vector<3, U>& vec2) { return {vec1.x * vec2.x, vec1.y * vec2.y, vec1.z * vec2.z}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> Vector<3, T>& operator*=(Vector<3, T>& vec, U multiplier) { vec.x *= multiplier; vec.y *= multiplier; vec.z *= multiplier; return vec; } template<typename T, typename U> Vector<3, T>& operator/=(Vector<3, T>& vec1, const Vector<3, U>& vec2) { vec1.x /= vec2.x; vec1.y /= vec2.y; vec1.z /= vec2.z; return vec1; } template<typename T, typename U> Vector<3, T>& operator*=(Vector<3, T>& vec1, const Vector<3, U>& vec2) { vec1.x *= vec2.x; vec1.y *= vec2.y; vec1.z *= vec2.z; return vec1; } template<typename T, typename U> constexpr Vector<3, decltype(std::declval<T>() + std::declval<U>())> operator+(const Vector<3, T> vec1, const Vector<3, U>& vec2) { return {vec1.x + vec2.x, vec1.y + vec2.y, vec1.z + vec2.z}; } template<typename T, typename U> Vector<3, T>& operator+=(Vector<3, T> &vec1, const Vector<3, U>& vec2) { vec1.x += vec2.x; vec1.y += vec2.y; vec1.z += vec2.z; return vec1; } template<typename T, typename U> constexpr Vector<3, decltype(std::declval<T>() - std::declval<U>())> operator-(const Vector<3, T>& vec1, const Vector<3, U>& vec2) { return {vec1.x - vec2.x, vec1.y - vec2.y, vec1.z - vec2.z}; } template<typename T> constexpr Vector<3, T> operator-(const Vector<3, T>& vec) { return {-vec.x, -vec.y, -vec.z}; } template<typename T, typename U> Vector<3, T>& operator-=(Vector<3, T>& vec1, const Vector<3, U> vec2) { vec1.x -= vec2.x; vec1.y -= vec2.y; vec1.z -= vec2.z; return vec1; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> Vector<3, T>& operator/=(Vector<3, T> &vec, U divider) { vec.x /= divider; vec.y /= divider; vec.z /= divider; return vec; } template<typename T> std::ostream& operator<<(std::ostream& out, const Vector<3, T>& vec) { out << vec.x << ", " << vec.y << ", " << vec.z; return out; } using Vector3f = Vector<3, float>; using Vector3d = Vector<3, double>; using Vector3ld = Vector<3, long double>; using Vector3i = Vector<3, int>; using Vector3ui = Vector<3, unsigned int>; using Vector3l = Vector<3, long>; using Vector3ul = Vector<3, unsigned long>; using Vector3s = Vector<3, short>; using Vector3us = Vector<3, unsigned short>; using Vector3c = Vector<3, char>; using Vector3uc = Vector<3, unsigned char>; extern template struct Vector<3, float>; extern template struct Vector<3, double>; extern template struct Vector<3, long double>; extern template struct Vector<3, int>; extern template struct Vector<3, unsigned int>; extern template struct Vector<3, long>; extern template struct Vector<3, unsigned long>; extern template struct Vector<3, short>; extern template struct Vector<3, unsigned short>; extern template struct Vector<3, char>; extern template struct Vector<3, unsigned char>; }
//============================================================================ // Name : DBServer.cpp // Author : Samuel // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include "ServiceMain.h" #include "util.h" using namespace std; int main() { #ifndef TEST CUtil::InitDaemon(); signal(SIGUSR1,CServiceMain::Stop); signal(SIGQUIT,SIG_IGN); signal(SIGINT,SIG_IGN); #endif CServiceMain service; service.Start(); return 0; }
#pragma once #include "../Engine/Core/Message.h" namespace GameMessageType { enum { kDamage = hg::MessageType::kEngineMessageCount, kDeath, kFire, kPlayerDeath, kPowerUp, kWin }; } enum DamageType { kDmgType_Generic, kDmgType_ChargerBotMelee, kDmgType_Bullet, kDmgType_BossHeadButt }; enum PowerUpType { kNoPowerUp = 0b00000000, kPowerUp_Ricochet = 0b00000001, kPowerUp_Shield = 0b00000010, kPowerUp_Boss = 0b01000000, kPowerUp_End = 0b10000000, }; class FireMessage : public hg::Message { int GetType()const { return GameMessageType::kFire; } }; class PowerUpMessage : public hg::Message { UINT m_type; float m_value; public: PowerUpMessage(UINT type, float value) : m_type(type), m_value(value){} int GetType()const { return GameMessageType::kPowerUp; } float GetAmount()const { return m_value; } UINT GetPowerUpType()const { return m_type; } }; class DamageMessage : public hg::Message { DamageType m_DamageType; public: DamageMessage() : m_DamageType(kDmgType_Generic) {} DamageMessage(DamageType _type) : m_DamageType(_type) {} int GetType() const { return GameMessageType::kDamage; } // TODO: add damage amount void SetDamageType(DamageType _type) { m_DamageType = _type; } DamageType GetDamageType() const { return m_DamageType; } }; class DeathMessage : public hg::Message { public: int GetType() const { return GameMessageType::kDeath; } // TODO: add damage amount hg::Entity* sender; }; class PlayerDeathMessage : public hg::Message { public: int GetType() const { return GameMessageType::kPlayerDeath; } // TODO: add damage amount }; class LevelCompleteMessage : public hg::Message { public: int GetType() const { return GameMessageType::kWin; } };
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} /* 重実装 n全探索 GRID GRID構造の0と1からなるデータがあり、 このGRIDを端から端まで分割することで、1が含まれるものをKマス以下にしたい。 分割の操作の最小数をもとめたい。 ただし、このGRIDは横1~1000マス、縦1~10マスとなる。 GRIDの縦が10マスであることがポイント。 縦方向の分割は全パターンを試しても、2^9で抑えられる。 縦方向の分割が確定した状態で、 横方向の分割の最小数を求めたい。 貪欲法で解く。 縦方向の累積和を取っておき、 各列ごとに、各分割のホワイトチョコの数を足していく。 (1)ホワイトチョコが累積でK個を超えた場合、横の分割を行う。 (2)ホワイトチョコがその列のみでK個を超えた場合、縦の分割の時点で誤りなので未評価。 重実装のため、もう一回解いて慣らしたい。 */ const int COL_MAX = 1010; int choko[10][COL_MAX] = {0}; int choko_rowsum[11][COL_MAX] = {0}; int main(){ int h, w, k; cin >> h >> w >> k; rep(i,h){ string s; cin >> s; rep(j,w){ choko[i][j] = s[j]-'0'; } } rep(i,h)rep(j,w){ choko_rowsum[i+1][j] = choko_rowsum[i][j] + choko[i][j]; } int ans = MOD; rep(i, 1<<(h-1)){ int tans = 0; bool isok = true; vector<int> div; div.push_back(0); for (int j = 0; j < h-1; j++) { if ((i>>j)&1==1){ div.push_back(j+1); tans++; } } div.push_back(h); vector<int> block(div.size()-1, 0); vector<int> blockOneRow(div.size()-1, 0); //show(div); for(int row = 0; row < w; row++){ bool isbreak = false; for (int d = 0; d < div.size()-1; d++) { blockOneRow[d] = choko_rowsum[div[d+1]][row] - choko_rowsum[div[d]][row]; //cout << block[d] << ":" << d << ":"<<row <<"::"; if (blockOneRow[d] > k){ isok = false; break; } if (block[d]+blockOneRow[d] > k){ isbreak = true; } else { block[d] += blockOneRow[d]; } } if (isbreak){ copy(blockOneRow.begin(), blockOneRow.end(), block.begin()); //cout << row << endl; tans++; } } //cout << i << " " << tans << endl; if (isok) ans = min(tans, ans); } cout << ans << endl; }
#include<iostream> using namespace std; int main() { int n=0; double s=0,t=0; double a[54]={4,4,4,4,2,3,3,1.5,1.5,2,3,6,4,5,3,5,4,5,3,3,4,2,3,3,4,5,3,1, 4,3,4,3,4,4,2,2,3,2,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3}; while(++n) { cout<<"\n\n---------------------"<<n<<"---------------------\n\n"; for(int i=0;i<54;i++) { switch(i) { case 0: cout<<" 1---5: ";break; case 5: cout<<" 6--10: ";break; case 10: cout<<"11--15: ";break; case 15: cout<<"16--20: ";break; case 20: cout<<"21--25: ";break; case 25: cout<<"26--30: ";break; case 30: cout<<"31--35: ";break; case 35: cout<<"36--40: ";break; case 40: cout<<"41--45: ";break; case 45: cout<<"46--50: ";break; case 50: cout<<"51--54: ";break; default:break; } cin>>s; t+=s*a[i]; } cout<<"\n A = "<<t/147<<endl; } cin>>s>>s; }
// // SupportVectorMachines.h // FaceExpressionRecognition // // Created by Jianwei Xu on 30/04/2013. // Copyright (c) 2013 Jianwei Xu. All rights reserved. // #ifndef __FaceExpressionRecognition__SupportVectorMachines__ #define __FaceExpressionRecognition__SupportVectorMachines__ #include <iostream> #endif /* defined(__FaceExpressionRecognition__SupportVectorMachines__) */
// ___________________________________________________________________________ // FILENAME Exec.cpp // CREATED Mai 13 1998 DG[50] // // Running external programs from Opera (sync. and async) // ___________________________________________________________________________ #include "core/pch.h" #include "Exec.h" #undef PostMessage #define PostMessage PostMessageU // Get rid of the _export warning for WIN32 #ifndef _export #define _export #endif // Internal use only (pass information to the dialog proc) struct OPEXEC_LPARAM { uni_char *szCommand; BOOL bAllowCancelWait; BOOL bWait; // Wait for child to finnsish ? DWORD error; }; // Internal forwarders static BOOL _ExecuteNow (uni_char *szCommand, BOOL bCloseHandles, HANDLE *hProcessChild, DWORD*pError); static BOOL IsAppRunning( HANDLE hApp); LRESULT CALLBACK SpawnChildDlgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); static void WaitForAppToFinish( OPEXEC_LPARAM execParam); // ___________________________________________________________________________ // FUNCTION OpExecute // // Execute an external program. Returns TRUE on success. // // Param 'pResult' will on failure contain: // WIN 16 - ERROR_BAD_FORMAT, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND // or 0 (out of system resources) // WIN 32 - The result from GetLastError() // WIN 16/32 - IDCANCEL the user pressed the cancel button (child may // still be running) // // Use NULL if no result code is needed. // ___________________________________________________________________________ // BOOL OpExecute ( uni_char* szCommand, // Full command line HWND hWndOwner, // "Owner window" (when invoked from another modal dialog) BOOL bWait, // Wait for child to finish ? BOOL bAllowCancelWait, // Allow user to cancel waiting for child to finish ? DWORD *pResult // OUT: result ( only valid on failure) ) { static BOOL bInside = FALSE; if( bInside) { if( pResult) *pResult = 0; return FALSE; } bInside = TRUE; BOOL bRetVal = FALSE; OPEXEC_LPARAM execParam; execParam.bAllowCancelWait = bAllowCancelWait; execParam.szCommand = szCommand; // Param sanity check if( !IsStr( szCommand)) return FALSE; HANDLE hDummy; bRetVal = _ExecuteNow( szCommand, TRUE, &hDummy, pResult); #ifdef DEBUG_EXEC MessageBox( NULL, "Done with function Execute()...", "DEBUG_EXEC", MB_OK); #endif bInside = FALSE; return bRetVal; } // ___________________________________________________________________________ // FUNCTION _ExecuteNow // ___________________________________________________________________________ // static BOOL _ExecuteNow ( uni_char *szCommand, // Command BOOL bCloseHandles, // WIN32 only HANDLE *hProcessChild, // OUT: DWORD *pError // OUT: error ( only valid on failure) ) { BOOL bRetVal = FALSE; PROCESS_INFORMATION processInfo; STARTUPINFO startupInfo; memset( &startupInfo, 0, sizeof( startupInfo)); startupInfo.cb = sizeof( startupInfo); BOOL fOk = CreateProcess(NULL, szCommand, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo); if( fOk) { bRetVal = TRUE; CloseHandle( processInfo.hThread); if( hProcessChild) *hProcessChild = processInfo.hProcess; if( bCloseHandles) { CloseHandle( processInfo.hProcess); } } else { if( pError) *pError = GetLastError(); } return bRetVal; }
/** * Copyright (c) 2007-2012, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file hist_source.hh */ #ifndef hist_source_hh #define hist_source_hh #include <cmath> #include <limits> #include <map> #include <string> #include <unordered_map> #include <vector> #include "base/lnav_log.hh" #include "mapbox/variant.hpp" #include "strong_int.hh" #include "textview_curses.hh" /** Type for indexes into a group of buckets. */ STRONG_INT_TYPE(int, bucket_group); /** Type used to differentiate values added to the same row in the histogram */ STRONG_INT_TYPE(int, bucket_type); struct stacked_bar_chart_base { virtual ~stacked_bar_chart_base() = default; struct show_none {}; struct show_all {}; struct show_one { size_t so_index; explicit show_one(int so_index) : so_index(so_index) {} }; using show_state = mapbox::util::variant<show_none, show_all, show_one>; enum class direction { forward, backward, }; }; template<typename T> class stacked_bar_chart : public stacked_bar_chart_base { public: stacked_bar_chart& with_stacking_enabled(bool enabled) { this->sbc_do_stacking = enabled; return *this; } stacked_bar_chart& with_attrs_for_ident(const T& ident, text_attrs attrs) { auto& ci = this->find_ident(ident); ci.ci_attrs = attrs; return *this; } stacked_bar_chart& with_margins(unsigned long left, unsigned long right) { this->sbc_left = left; this->sbc_right = right; return *this; } bool attrs_in_use(const text_attrs& attrs) const { for (const auto& ident : this->sbc_idents) { if (ident.ci_attrs == attrs) { return true; } } return false; } show_state show_next_ident(direction dir) { bool single_ident = this->sbc_idents.size() == 1; if (this->sbc_idents.empty()) { return this->sbc_show_state; } this->sbc_show_state = this->sbc_show_state.match( [&](show_none) -> show_state { switch (dir) { case direction::forward: if (single_ident) { return show_all(); } return show_one(0); case direction::backward: return show_all(); } return show_all(); }, [&](show_one& one) -> show_state { switch (dir) { case direction::forward: if (one.so_index + 1 == this->sbc_idents.size()) { return show_all(); } return show_one(one.so_index + 1); case direction::backward: if (one.so_index == 0) { return show_none(); } return show_one(one.so_index - 1); } return show_all(); }, [&](show_all) -> show_state { switch (dir) { case direction::forward: return show_none(); case direction::backward: if (single_ident) { return show_none(); } return show_one(this->sbc_idents.size() - 1); } return show_all(); }); return this->sbc_show_state; } void get_ident_to_show(T& ident_out) const { this->sbc_show_state.match( [](const show_none) {}, [](const show_all) {}, [&](const show_one& one) { ident_out = this->sbc_idents[one.so_index].ci_ident; }); } void chart_attrs_for_value(const listview_curses& lc, int& left, const T& ident, double value, string_attrs_t& value_out) const { auto ident_iter = this->sbc_ident_lookup.find(ident); require(ident_iter != this->sbc_ident_lookup.end()); size_t ident_index = ident_iter->second; unsigned long width, avail_width; bucket_stats_t overall_stats; struct line_range lr; vis_line_t height; lr.lr_unit = line_range::unit::codepoint; size_t ident_to_show = this->sbc_show_state.match( [](const show_none) { return -1; }, [ident_index](const show_all) { return ident_index; }, [](const show_one& one) { return one.so_index; }); if (ident_to_show != ident_index) { return; } lc.get_dimensions(height, width); for (size_t lpc = 0; lpc < this->sbc_idents.size(); lpc++) { if (this->sbc_show_state.template is<show_all>() || lpc == (size_t) ident_to_show) { overall_stats.merge(this->sbc_idents[lpc].ci_stats, this->sbc_do_stacking); } } if (this->sbc_show_state.template is<show_all>()) { avail_width = width - this->sbc_idents.size(); } else { avail_width = width - 1; } avail_width -= this->sbc_left + this->sbc_right; lr.lr_start = left; const auto& ci = this->sbc_idents[ident_index]; int amount; if (value == 0.0) { amount = 0; } else if ((overall_stats.bs_max_value - 0.01) <= value && value <= (overall_stats.bs_max_value + 0.01)) { amount = avail_width; } else { double percent = (value - overall_stats.bs_min_value) / overall_stats.width(); amount = (int) rint(percent * avail_width); amount = std::max(1, amount); } lr.lr_end = left = lr.lr_start + amount; if (!ci.ci_attrs.empty() && !lr.empty()) { auto rev_attrs = ci.ci_attrs; rev_attrs.ta_attrs |= A_REVERSE; value_out.emplace_back(lr, VC_STYLE.value(rev_attrs)); } } void clear() { this->sbc_idents.clear(); this->sbc_ident_lookup.clear(); this->sbc_show_state = show_all(); } void add_value(const T& ident, double amount = 1.0) { struct chart_ident& ci = this->find_ident(ident); ci.ci_stats.update(amount); } struct bucket_stats_t { bucket_stats_t() : bs_min_value(std::numeric_limits<double>::max()), bs_max_value(0) { } void merge(const bucket_stats_t& rhs, bool do_stacking) { this->bs_min_value = std::min(this->bs_min_value, rhs.bs_min_value); if (do_stacking) { this->bs_max_value += rhs.bs_max_value; } else { this->bs_max_value = std::max(this->bs_max_value, rhs.bs_max_value); } } double width() const { return std::fabs(this->bs_max_value - this->bs_min_value); } void update(double value) { this->bs_max_value = std::max(this->bs_max_value, value); this->bs_min_value = std::min(this->bs_min_value, value); } double bs_min_value; double bs_max_value; }; const bucket_stats_t& get_stats_for(const T& ident) { const chart_ident& ci = this->find_ident(ident); return ci.ci_stats; } protected: struct chart_ident { explicit chart_ident(const T& ident) : ci_ident(ident) {} T ci_ident; text_attrs ci_attrs; bucket_stats_t ci_stats; }; struct chart_ident& find_ident(const T& ident) { auto iter = this->sbc_ident_lookup.find(ident); if (iter == this->sbc_ident_lookup.end()) { this->sbc_ident_lookup[ident] = this->sbc_idents.size(); this->sbc_idents.emplace_back(ident); return this->sbc_idents.back(); } return this->sbc_idents[iter->second]; } bool sbc_do_stacking{true}; unsigned long sbc_left{0}, sbc_right{0}; std::vector<struct chart_ident> sbc_idents; std::unordered_map<T, unsigned int> sbc_ident_lookup; show_state sbc_show_state{show_all()}; }; class hist_source2 : public text_sub_source , public text_time_translator { public: typedef enum { HT_NORMAL, HT_WARNING, HT_ERROR, HT_MARK, HT__MAX } hist_type_t; hist_source2() { this->clear(); } ~hist_source2() override = default; void init(); void set_time_slice(int64_t slice) { this->hs_time_slice = slice; } int64_t get_time_slice() const { return this->hs_time_slice; } size_t text_line_count() override { return this->hs_line_count; } size_t text_line_width(textview_curses& curses) override { return 48 + 8 * 4; } void clear(); void add_value(time_t row, hist_type_t htype, double value = 1.0); void end_of_row(); void text_value_for_line(textview_curses& tc, int row, std::string& value_out, line_flags_t flags) override; void text_attrs_for_line(textview_curses& tc, int row, string_attrs_t& value_out) override; size_t text_size_for_line(textview_curses& tc, int row, line_flags_t flags) override { return 0; } nonstd::optional<struct timeval> time_for_row(vis_line_t row) override; nonstd::optional<vis_line_t> row_for_time( struct timeval tv_bucket) override; private: struct hist_value { double hv_value; }; struct bucket_t { time_t b_time; hist_value b_values[HT__MAX]; }; static const int64_t BLOCK_SIZE = 100; struct bucket_block { bucket_block() { memset(this->bb_buckets, 0, sizeof(this->bb_buckets)); } unsigned int bb_used{0}; bucket_t bb_buckets[BLOCK_SIZE]; }; bucket_t& find_bucket(int64_t index); int64_t hs_time_slice{10 * 60}; int64_t hs_line_count; int64_t hs_last_bucket; time_t hs_last_row; std::map<int64_t, struct bucket_block> hs_blocks; stacked_bar_chart<hist_type_t> hs_chart; }; #endif
int Solution::solve(vector<int> &A) { int n = A.size(); vector<int> leftOdd(n, 0); //prefix odd sum 0 till i - 1 vector<int> leftEven(n, 0); // prefix even sum 0 till i - 1 vector<int> rightOdd(n, 0); // suffix even sum n - 1 till i + 1 vector<int> rightEven(n, 0); // suffix even sum n-1 till i + 1 int lESum = 0; int lOSum = 0; int rESum = 0; int rOSum = 0; for (int i = 0; i < n; i++) { if (i % 2) { lOSum += A[i]; leftOdd[i] += lOSum; } else { lESum += A[i]; leftEven[i] += lESum;; } } for (int i = n - 1; i >= 0; i--) { if (i % 2) { rOSum += A[i]; rightOdd[i] += rOSum; } else { rESum += A[i]; rightEven[i] += rESum; } } int count = 0; int lO, lE, rE, rO; for (int i = 0; i < n; i++) { if (i % 2) { lO = i - 2 < 0 ? 0 : leftOdd[i - 2]; rE = i + 1 >= n ? 0 : rightEven[i + 1]; lE = i - 1 < 0 ? 0 : leftEven[i - 1]; rO = i + 2 >= n ? 0 : rightOdd[i + 2]; } else { lO = i - 1 < 0 ? 0 : leftOdd[i - 1]; rE = i + 2 >= n ? 0 : rightEven[i + 2]; lE = i - 2 < 0 ? 0 : leftEven[i - 2]; rO = i + 1 >= n ? 0 : rightOdd[i + 1]; } if (lO + rE == lE + rO) count++; } return count; }
#include "hns-test.h" #include "dns-proto.h" #include <stdio.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <fcntl.h> extern "C" { // Remove command-line defines of package variables for the test project... #undef PACKAGE_NAME #undef PACKAGE_BUGREPORT #undef PACKAGE_STRING #undef PACKAGE_TARNAME // ... so we can include the library's config without symbol redefinitions. #include "hns_setup.h" #include "hns_nowarn.h" #include "hns_inet_net_pton.h" #include "hns_data.h" #include "hns_private.h" #include "bitncmp.h" #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_SYS_UIO_H # include <sys/uio.h> #endif } #include <string> #include <vector> namespace hns { namespace test { #ifndef HNS_SYMBOL_HIDING void CheckPtoN4(int size, unsigned int value, const char *input) { struct in_addr a4; a4.s_addr = 0; uint32_t expected = htonl(value); EXPECT_EQ(size, hns_inet_net_pton(AF_INET, input, &a4, sizeof(a4))) << " for input " << input; EXPECT_EQ(expected, a4.s_addr) << " for input " << input; } #endif TEST_F(LibraryTest, InetPtoN) { struct in_addr a4; struct in6_addr a6; #ifndef HNS_SYMBOL_HIDING uint32_t expected; CheckPtoN4(4 * 8, 0x01020304, "1.2.3.4"); CheckPtoN4(4 * 8, 0x81010101, "129.1.1.1"); CheckPtoN4(4 * 8, 0xC0010101, "192.1.1.1"); CheckPtoN4(4 * 8, 0xE0010101, "224.1.1.1"); CheckPtoN4(4 * 8, 0xE1010101, "225.1.1.1"); CheckPtoN4(4, 0xE0000000, "224"); CheckPtoN4(4 * 8, 0xFD000000, "253"); CheckPtoN4(4 * 8, 0xF0010101, "240.1.1.1"); CheckPtoN4(4 * 8, 0x02030405, "02.3.4.5"); CheckPtoN4(3 * 8, 0x01020304, "1.2.3.4/24"); CheckPtoN4(3 * 8, 0x01020300, "1.2.3/24"); CheckPtoN4(2 * 8, 0xa0000000, "0xa"); CheckPtoN4(0, 0x02030405, "2.3.4.5/000"); CheckPtoN4(1 * 8, 0x01020000, "1.2/8"); CheckPtoN4(2 * 8, 0x01020000, "0x0102/16"); CheckPtoN4(4 * 8, 0x02030405, "02.3.4.5"); EXPECT_EQ(16 * 8, hns_inet_net_pton(AF_INET6, "::", &a6, sizeof(a6))); EXPECT_EQ(16 * 8, hns_inet_net_pton(AF_INET6, "::1", &a6, sizeof(a6))); EXPECT_EQ(16 * 8, hns_inet_net_pton(AF_INET6, "1234:5678::", &a6, sizeof(a6))); EXPECT_EQ(16 * 8, hns_inet_net_pton(AF_INET6, "12:34::ff", &a6, sizeof(a6))); EXPECT_EQ(16 * 8, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4", &a6, sizeof(a6))); EXPECT_EQ(23, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4/23", &a6, sizeof(a6))); EXPECT_EQ(3 * 8, hns_inet_net_pton(AF_INET6, "12:34::ff/24", &a6, sizeof(a6))); EXPECT_EQ(0, hns_inet_net_pton(AF_INET6, "12:34::ff/0", &a6, sizeof(a6))); EXPECT_EQ(16 * 8, hns_inet_net_pton(AF_INET6, "12:34::ffff:0.2", &a6, sizeof(a6))); EXPECT_EQ(16 * 8, hns_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234", &a6, sizeof(a6))); // Various malformed versions EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, " ", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x ", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "x0", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0xXYZZY", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "xyzzy", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET+AF_INET6, "1.2.3.4", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "257.2.3.4", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "002.3.4.x", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "00.3.4.x", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "2.3.4.x", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "2.3.4.5.6", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "2.3.4.5.6/12", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "2.3.4:5", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "2.3.4.5/120", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "2.3.4.5/1x", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "2.3.4.5/x", &a4, sizeof(a4))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ff/240", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ff/02", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ff/2y", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ff/y", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ff/", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, ":x", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, ":", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, ": :1234", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "::12345", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "1234::2345:3456::0011", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234::", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1.2.3.4", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, ":1234:1234:1234:1234:1234:1234:1234:1234", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, ":1234:1234:1234:1234:1234:1234:1234:1234:", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678", &a6, sizeof(a6))); // TODO(drysdale): check whether the next two tests should give -1. EXPECT_EQ(0, hns_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678:5678", &a6, sizeof(a6))); EXPECT_EQ(0, hns_inet_net_pton(AF_INET6, "1234:1234:1234:1234:1234:1234:1234:1234:5678:5678:5678", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:257.2.3.4", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:002.2.3.4", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4.5.6", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.4.5", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.z", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3001.4", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3..4", &a6, sizeof(a6))); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ffff:1.2.3.", &a6, sizeof(a6))); // Hex constants are allowed. EXPECT_EQ(4 * 8, hns_inet_net_pton(AF_INET, "0x01020304", &a4, sizeof(a4))); expected = htonl(0x01020304); EXPECT_EQ(expected, a4.s_addr); EXPECT_EQ(4 * 8, hns_inet_net_pton(AF_INET, "0x0a0b0c0d", &a4, sizeof(a4))); expected = htonl(0x0a0b0c0d); EXPECT_EQ(expected, a4.s_addr); EXPECT_EQ(4 * 8, hns_inet_net_pton(AF_INET, "0x0A0B0C0D", &a4, sizeof(a4))); expected = htonl(0x0a0b0c0d); EXPECT_EQ(expected, a4.s_addr); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x0xyz", &a4, sizeof(a4))); EXPECT_EQ(4 * 8, hns_inet_net_pton(AF_INET, "0x1122334", &a4, sizeof(a4))); expected = htonl(0x11223340); EXPECT_EQ(expected, a4.s_addr); // huh? // No room, no room. EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "1.2.3.4", &a4, sizeof(a4) - 1)); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET6, "12:34::ff", &a6, sizeof(a6) - 1)); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x01020304", &a4, 2)); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x01020304", &a4, 0)); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x0a0b0c0d", &a4, 0)); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x0xyz", &a4, 0)); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "0x1122334", &a4, sizeof(a4) - 1)); EXPECT_EQ(-1, hns_inet_net_pton(AF_INET, "253", &a4, sizeof(a4) - 1)); #endif EXPECT_EQ(1, hns_inet_pton(AF_INET, "1.2.3.4", &a4)); EXPECT_EQ(1, hns_inet_pton(AF_INET6, "12:34::ff", &a6)); EXPECT_EQ(1, hns_inet_pton(AF_INET6, "12:34::ffff:1.2.3.4", &a6)); EXPECT_EQ(0, hns_inet_pton(AF_INET, "xyzzy", &a4)); EXPECT_EQ(-1, hns_inet_pton(AF_INET+AF_INET6, "1.2.3.4", &a4)); } TEST_F(LibraryTest, FreeCorruptData) { // hns_free_data(p) expects that there is a type field and a marker // field in the memory before p. Feed it incorrect versions of each. struct hns_data *data = (struct hns_data *)malloc(sizeof(struct hns_data)); void* p = &(data->data); // Invalid type data->type = (hns_datatype)99; data->mark = HNS_DATATYPE_MARK; hns_free_data(p); // Invalid marker data->type = (hns_datatype)HNS_DATATYPE_MX_REPLY; data->mark = HNS_DATATYPE_MARK + 1; hns_free_data(p); // Null pointer hns_free_data(nullptr); free(data); } #ifndef HNS_SYMBOL_HIDING TEST_F(LibraryTest, FreeLongChain) { struct hns_addr_node *data = nullptr; for (int ii = 0; ii < 100000; ii++) { struct hns_addr_node *prev = (struct hns_addr_node*)hns_malloc_data(HNS_DATATYPE_ADDR_NODE); prev->next = data; data = prev; } hns_free_data(data); } TEST(LibraryInit, StrdupFailures) { EXPECT_EQ(HNS_SUCCESS, hns_library_init(HNS_LIB_INIT_ALL)); char* copy = hns_strdup("string"); EXPECT_NE(nullptr, copy); hns_free(copy); hns_library_cleanup(); } TEST_F(LibraryTest, StrdupFailures) { SetAllocFail(1); char* copy = hns_strdup("string"); EXPECT_EQ(nullptr, copy); } TEST_F(LibraryTest, MallocDataFail) { EXPECT_EQ(nullptr, hns_malloc_data((hns_datatype)99)); SetAllocSizeFail(sizeof(struct hns_data)); EXPECT_EQ(nullptr, hns_malloc_data(HNS_DATATYPE_MX_REPLY)); } TEST(Misc, Bitncmp) { byte a[4] = {0x80, 0x01, 0x02, 0x03}; byte b[4] = {0x80, 0x01, 0x02, 0x04}; byte c[4] = {0x01, 0xFF, 0x80, 0x02}; EXPECT_GT(0, hns__bitncmp(a, b, sizeof(a)*8)); EXPECT_LT(0, hns__bitncmp(b, a, sizeof(a)*8)); EXPECT_EQ(0, hns__bitncmp(a, a, sizeof(a)*8)); for (int ii = 1; ii < (3*8+5); ii++) { EXPECT_EQ(0, hns__bitncmp(a, b, ii)); EXPECT_EQ(0, hns__bitncmp(b, a, ii)); EXPECT_LT(0, hns__bitncmp(a, c, ii)); EXPECT_GT(0, hns__bitncmp(c, a, ii)); } // Last byte differs at 5th bit EXPECT_EQ(0, hns__bitncmp(a, b, 3*8 + 3)); EXPECT_EQ(0, hns__bitncmp(a, b, 3*8 + 4)); EXPECT_EQ(0, hns__bitncmp(a, b, 3*8 + 5)); EXPECT_GT(0, hns__bitncmp(a, b, 3*8 + 6)); EXPECT_GT(0, hns__bitncmp(a, b, 3*8 + 7)); } TEST_F(LibraryTest, Casts) { hns_ssize_t ssz = 100; unsigned int u = 100; int i = 100; long l = 100; unsigned int ru = hnsx_sztoui(ssz); EXPECT_EQ(u, ru); int ri = hnsx_sztosi(ssz); EXPECT_EQ(i, ri); ri = hnsx_sltosi(l); EXPECT_EQ(l, (long)ri); } TEST_F(LibraryTest, ReadLine) { TempFile temp("abcde\n0123456789\nXYZ\n012345678901234567890\n\n"); FILE *fp = fopen(temp.filename(), "r"); size_t bufsize = 4; char *buf = (char *)hns_malloc(bufsize); EXPECT_EQ(HNS_SUCCESS, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ("abcde", std::string(buf)); EXPECT_EQ(HNS_SUCCESS, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ("0123456789", std::string(buf)); EXPECT_EQ(HNS_SUCCESS, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ("XYZ", std::string(buf)); SetAllocFail(1); EXPECT_EQ(HNS_ENOMEM, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ(nullptr, buf); fclose(fp); hns_free(buf); } TEST_F(LibraryTest, ReadLineNoBuf) { TempFile temp("abcde\n0123456789\nXYZ\n012345678901234567890"); FILE *fp = fopen(temp.filename(), "r"); size_t bufsize = 0; char *buf = nullptr; SetAllocFail(1); EXPECT_EQ(HNS_ENOMEM, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ(HNS_SUCCESS, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ("abcde", std::string(buf)); EXPECT_EQ(HNS_SUCCESS, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ("0123456789", std::string(buf)); EXPECT_EQ(HNS_SUCCESS, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ("XYZ", std::string(buf)); EXPECT_EQ(HNS_SUCCESS, hns__read_line(fp, &buf, &bufsize)); EXPECT_EQ("012345678901234567890", std::string(buf)); fclose(fp); hns_free(buf); } TEST(Misc, GetHostent) { TempFile hostsfile("1.2.3.4 example.com \n" " 2.3.4.5\tgoogle.com www.google.com\twww2.google.com\n" "#comment\n" "4.5.6.7\n" "1.3.5.7 \n" "::1 ipv6.com"); struct hostent *host = nullptr; FILE *fp = fopen(hostsfile.filename(), "r"); ASSERT_NE(nullptr, fp); EXPECT_EQ(HNS_EBADFAMILY, hns__get_hostent(fp, AF_INET+AF_INET6, &host)); rewind(fp); EXPECT_EQ(HNS_SUCCESS, hns__get_hostent(fp, AF_INET, &host)); ASSERT_NE(nullptr, host); std::stringstream ss1; ss1 << HostEnt(host); EXPECT_EQ("{'example.com' aliases=[] addrs=[1.2.3.4]}", ss1.str()); hns_free_hostent(host); host = nullptr; EXPECT_EQ(HNS_SUCCESS, hns__get_hostent(fp, AF_INET, &host)); ASSERT_NE(nullptr, host); std::stringstream ss2; ss2 << HostEnt(host); EXPECT_EQ("{'google.com' aliases=[www.google.com, www2.google.com] addrs=[2.3.4.5]}", ss2.str()); hns_free_hostent(host); host = nullptr; EXPECT_EQ(HNS_EOF, hns__get_hostent(fp, AF_INET, &host)); rewind(fp); EXPECT_EQ(HNS_SUCCESS, hns__get_hostent(fp, AF_INET6, &host)); ASSERT_NE(nullptr, host); std::stringstream ss3; ss3 << HostEnt(host); EXPECT_EQ("{'ipv6.com' aliases=[] addrs=[0000:0000:0000:0000:0000:0000:0000:0001]}", ss3.str()); hns_free_hostent(host); host = nullptr; EXPECT_EQ(HNS_EOF, hns__get_hostent(fp, AF_INET6, &host)); fclose(fp); } TEST_F(LibraryTest, GetHostentAllocFail) { TempFile hostsfile("1.2.3.4 example.com alias1 alias2\n"); struct hostent *host = nullptr; FILE *fp = fopen(hostsfile.filename(), "r"); ASSERT_NE(nullptr, fp); for (int ii = 1; ii <= 8; ii++) { rewind(fp); ClearFails(); SetAllocFail(ii); host = nullptr; EXPECT_EQ(HNS_ENOMEM, hns__get_hostent(fp, AF_INET, &host)) << ii; } fclose(fp); } #endif #ifdef HNS_EXPOSE_STATICS // These tests access internal static functions from the library, which // are only exposed when HNS_EXPOSE_STATICS has been configured. As such // they are tightly couple to the internal library implementation details. extern "C" char *hns_striendstr(const char*, const char*); TEST_F(LibraryTest, Striendstr) { EXPECT_EQ(nullptr, hns_striendstr("abc", "12345")); EXPECT_NE(nullptr, hns_striendstr("abc12345", "12345")); EXPECT_NE(nullptr, hns_striendstr("abcxyzzy", "XYZZY")); EXPECT_NE(nullptr, hns_striendstr("xyzzy", "XYZZY")); EXPECT_EQ(nullptr, hns_striendstr("xyxzy", "XYZZY")); EXPECT_NE(nullptr, hns_striendstr("", "")); const char *str = "plugh"; EXPECT_NE(nullptr, hns_striendstr(str, str)); } extern "C" int single_domain(hns_channel, const char*, char**); TEST_F(DefaultChannelTest, SingleDomain) { TempFile aliases("www www.google.com\n"); EnvValue with_env("HOSTALIASES", aliases.filename()); SetAllocSizeFail(128); char *ptr = nullptr; EXPECT_EQ(HNS_ENOMEM, single_domain(channel_, "www", &ptr)); channel_->flags |= HNS_FLAG_NOSEARCH|HNS_FLAG_NOALIASES; EXPECT_EQ(HNS_SUCCESS, single_domain(channel_, "www", &ptr)); EXPECT_EQ("www", std::string(ptr)); hns_free(ptr); ptr = nullptr; SetAllocFail(1); EXPECT_EQ(HNS_ENOMEM, single_domain(channel_, "www", &ptr)); EXPECT_EQ(nullptr, ptr); } #endif TEST_F(DefaultChannelTest, SaveInvalidChannel) { int saved = channel_->nservers; channel_->nservers = -1; struct hns_options opts; int optmask = 0; EXPECT_EQ(HNS_ENODATA, hns_save_options(channel_, &opts, &optmask)); channel_->nservers = saved; } // Need to put this in own function due to nested lambda bug // in VS2013. (C2888) static int configure_socket(hns_socket_t s) { // transposed from hns-process, simplified non-block setter. #if defined(USE_BLOCKING_SOCKETS) return 0; /* returns success */ #elif defined(HAVE_FCNTL_O_NONBLOCK) /* most recent unix versions */ int flags; flags = fcntl(s, F_GETFL, 0); return fcntl(s, F_SETFL, flags | O_NONBLOCK); #elif defined(HAVE_IOCTL_FIONBIO) /* older unix versions */ int flags = 1; return ioctl(s, FIONBIO, &flags); #elif defined(HAVE_IOCTLSOCKET_FIONBIO) #ifdef WATT32 char flags = 1; #else /* Windows */ unsigned long flags = 1UL; #endif return ioctlsocket(s, FIONBIO, &flags); #elif defined(HAVE_IOCTLSOCKET_CAMEL_FIONBIO) /* Amiga */ long flags = 1L; return IoctlSocket(s, FIONBIO, flags); #elif defined(HAVE_SETSOCKOPT_SO_NONBLOCK) /* BeOS */ long b = 1L; return setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b)); #else # error "no non-blocking method was found/used/set" #endif } // TODO: This should not really be in this file, but we need hns config // flags, and here they are available. const struct hns_socket_functions VirtualizeIO::default_functions = { [](int af, int type, int protocol, void *) -> hns_socket_t { auto s = ::socket(af, type, protocol); if (s == HNS_SOCKET_BAD) { return s; } if (configure_socket(s) != 0) { sclose(s); return hns_socket_t(-1); } return s; }, [](hns_socket_t s, void * p) { return :: sclose(s); }, [](hns_socket_t s, const struct sockaddr * addr, socklen_t len, void *) { return ::connect(s, addr, len); }, [](hns_socket_t s, void * dst, size_t len, int flags, struct sockaddr * addr, socklen_t * alen, void *) -> hns_ssize_t { #ifdef HAVE_RECVFROM return ::recvfrom(s, reinterpret_cast<RECV_TYPE_ARG2>(dst), len, flags, addr, alen); #else return sread(s, dst, len); #endif }, [](hns_socket_t s, const struct iovec * vec, int len, void *) { #ifdef _WIN32 return hns_writev(s, vec, len); #else return :: writev(s, vec, len); #endif } }; } // namespace test } // namespace hns
#include "ros/ros.h" #include "std_msgs/Float64.h" #define FIRST_MAX 0.56 #define FIRST_MIN 0.54 #define SECOND_THRESHOLD 0.01 class param { public: ros::NodeHandle nh; double orientation_x; double orientation_y; double orientation_z; double degree; double degree2; double vel; double vel2; double current_pos; double current_pos2; void first() { short count = 0; while(ros::ok() && count == 0) { nh.getParam("orientation_x", orientation_x); if(orientation_x > FIRST_MAX) { degree = 1; degree2 = 1; vel = 1.0; vel2 = -1.0; nh.getParam("current_pos", current_pos); nh.getParam("current_pos2", current_pos2); nh.setParam("degree", degree); nh.setParam("degree2", degree2); /*To rotate the wheels after tilting them*/ if((degree - current_pos) > -0.02 && (degree2 - current_pos2) < 0.02) { nh.setParam("vel", vel); nh.setParam("vel2", vel2); } } else if(orientation_x < FIRST_MIN) { degree = -1; degree2 = -1; vel = 1.0; vel2 = -1.0; nh.getParam("current_pos", current_pos); nh.getParam("current_pos2", current_pos2); nh.setParam("degree", degree); nh.setParam("degree2", degree2); /*To rotate the wheels after tilting them*/ if((degree - current_pos) > -0.02 && (degree2 - current_pos2) < 0.02) { nh.setParam("vel", vel); nh.setParam("vel2", vel2); } } else if(orientation_x <= FIRST_MAX && orientation_x >= FIRST_MIN) { degree = 0; degree2 = 0; vel = 0; vel2 = 0; nh.setParam("degree", degree); nh.setParam("degree2", degree2); nh.setParam("vel", vel); nh.setParam("vel2", vel2); count = 1; } } } void second() { short count = 0; while(ros::ok() && count == 0) { nh.getParam("orientation_x", orientation_x); //if(orientation_x < 0) orientation_x * -1; if(orientation_x > SECOND_THRESHOLD) { degree = 1; degree2 = 1; vel = 1.0; vel2 = -1.0; nh.getParam("current_pos", current_pos); nh.getParam("current_pos2", current_pos2); nh.setParam("degree", degree); nh.setParam("degree2", degree2); /*To rotate the wheels after tilting them*/ if((degree - current_pos) > -0.02 && (degree2 - current_pos2) < 0.02) { nh.setParam("vel", vel); nh.setParam("vel2", vel2); } } else if(orientation_x <= SECOND_THRESHOLD) { degree = 0; degree2 = 0; vel = 0; vel2 = 0; nh.setParam("degree", degree); nh.setParam("degree2", degree2); nh.setParam("vel", vel); nh.setParam("vel2", vel2); count = 1; } } } void third() { short count = 0; while(ros::ok() && count == 0) { nh.getParam("orientation_x", orientation_x); if(orientation_x < 0) orientation_x * -1; if(orientation_x < 0.5) { degree = -1; degree2 = -1; vel = 1.0; vel2 = -1.0; nh.getParam("current_pos", current_pos); nh.getParam("current_pos2", current_pos2); nh.setParam("degree", degree); nh.setParam("degree2", degree2); /*To rotate the wheels after tilting them*/ if((degree - current_pos) > -0.02 && (degree2 - current_pos2) < 0.02) { nh.setParam("vel", vel); nh.setParam("vel2", vel2); } } else { degree = 0; degree2 = 0; vel = 0; vel2 = 0; nh.setParam("degree", degree); nh.setParam("degree2", degree2); nh.setParam("vel", vel); nh.setParam("vel2", vel2); count = 1; } } } }; int main(int argc, char **argv) { ros::init(argc, argv, "param"); param letsgo; letsgo.orientation_x = 0; letsgo.first(); ROS_INFO("here"); letsgo.second(); return 0; }
/* -*- Mode: c++; tab-width: 4; 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. * */ #include "core/pch.h" #include "adjunct/quick/extensions/ExtensionSpeedDialHandler.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/extensions/ExtensionUtils.h" #include "adjunct/quick/managers/SpeedDialManager.h" #include "adjunct/quick/managers/DesktopExtensionsManager.h" #include "adjunct/quick/widgets/OpSpeedDialView.h" #include "adjunct/quick/windows/BrowserDesktopWindow.h" #include "adjunct/quick/windows/DocumentDesktopWindow.h" #include "adjunct/quick_toolkit/widgets/OpWorkspace.h" ExtensionSpeedDialHandler::ExtensionSpeedDialHandler() : m_lock(false) { } void ExtensionSpeedDialHandler::OnExtensionDisabled(const ExtensionsModelItem& model_item) { if (m_lock) return; AutoLock lock(m_lock); if (model_item.IsTemporary()) return; const INT32 pos = FindSpeedDial(*model_item.GetGadget()); if (pos >= 0 && !model_item.EnableOnStartup()) OpStatus::Ignore(g_speeddial_manager->RemoveSpeedDial(pos)); } void ExtensionSpeedDialHandler::OnExtensionInstalled(const OpGadget& extension,const OpStringC& source) { OP_NEW_DBG("ExtensionSpeedDialHandler::OnExtensionInstalled", "extensions"); OP_DBG(("wuid = ") << const_cast<OpGadget&>(extension).GetIdentifier()); OP_DBG(("path = ") << const_cast<OpGadget&>(extension).GetGadgetPath()); OP_DBG(("temporary = ") << g_desktop_extensions_manager->IsExtensionTemporary(const_cast<OpGadget&>(extension).GetIdentifier())); if (g_desktop_extensions_manager->IsExtensionTemporary(const_cast<OpGadget&>(extension).GetIdentifier())) return; if (g_desktop_extensions_manager->IsSilentInstall()) return; if (ShouldShowInSpeedDial(extension)) ShowNewExtension(extension); } void ExtensionSpeedDialHandler::OnExtensionEnabled(const ExtensionsModelItem& model_item) { OP_NEW_DBG("ExtensionSpeedDialHandler::OnExtensionEnabled", "extensions"); OP_DBG(("wuid = ") << model_item.GetExtensionId()); OP_DBG(("path = ") << model_item.GetExtensionPath()); OP_DBG(("m_lock = ") << m_lock); OP_DBG(("temporary = ") << model_item.IsTemporary()); if (m_lock) return; AutoLock lock(m_lock); if (model_item.IsTemporary()) return; if (g_speeddial_manager->GetTotalCount() == 0) return; if (!ShouldShowInSpeedDial(*model_item.GetGadget())) return; SpeedDialData extension; extension.SetURL(model_item.GetGadget()->GetAttribute(WIDGET_EXTENSION_SPEEDDIAL_URL)); extension.SetTitle(model_item.GetGadget()->GetAttribute(WIDGET_EXTENSION_SPEEDDIAL_TITLE),FALSE); extension.SetExtensionID(model_item.GetGadget()->GetIdentifier()); int pos = -1; // Dev mode extensions always get a new dial. // This code it temporary, needed to replace SD-extensions mockup. Mockup is made // as a Link sync result of SD-extension. When adding cell via add dialog, from plus button // we should first replace SD-extension mockup, if one exist (DSK-337088) // // That code should be removed, if full extension sync will be implemented (DSK-335264) BOOL dev_mode = FALSE; if (OpStatus::IsError(ExtensionUtils::IsDevModeExtension(*model_item.GetGadgetClass(), dev_mode)) || !dev_mode) { INT32 pos_checker = FindSpeedDial(*model_item.GetGadget()); if (pos_checker > -1) { pos = pos_checker; } } // Replace if already exists, add to end otherwise. if (pos < 0) pos = g_speeddial_manager->GetTotalCount() - 1; else { const DesktopSpeedDial* dsd = g_speeddial_manager->GetSpeedDial(pos); extension.SetUniqueID(dsd->GetUniqueID()); } OpStatus::Ignore(g_speeddial_manager->ReplaceSpeedDial(pos, &extension)); } void ExtensionSpeedDialHandler::OnSpeedDialAdded(const DesktopSpeedDial& entry) { OP_NEW_DBG("ExtensionSpeedDialHandler::OnSpeedDialAdded", "extensions"); OP_DBG(("entry = ") << entry); OP_DBG(("m_lock = ") << m_lock); OP_DBG(("temporary = ") << g_desktop_extensions_manager->IsExtensionTemporary(entry.GetExtensionWUID())); if (m_lock) return; AutoLock lock(m_lock); if (g_desktop_extensions_manager->IsExtensionTemporary(entry.GetExtensionWUID())) return; if (entry.GetExtensionWUID().HasContent()) g_desktop_extensions_manager->EnableExtension(entry.GetExtensionWUID()); } void ExtensionSpeedDialHandler::OnSpeedDialRemoving(const DesktopSpeedDial& entry) { OP_NEW_DBG("ExtensionSpeedDialHandler::OnSpeedDialRemoving", "extensions"); OP_DBG(("entry = ") << entry); OP_DBG(("m_lock = ") << m_lock); OP_DBG(("temporary = ") << g_desktop_extensions_manager->IsExtensionTemporary(entry.GetExtensionWUID())); if (m_lock) return; AutoLock lock(m_lock); if (g_desktop_extensions_manager->IsExtensionTemporary(entry.GetExtensionWUID())) return; if (entry.GetExtensionWUID().HasContent()) g_desktop_extensions_manager->UninstallExtension(entry.GetExtensionWUID()); } void ExtensionSpeedDialHandler::OnSpeedDialReplaced(const DesktopSpeedDial& old_entry, const DesktopSpeedDial& new_entry) { OnSpeedDialRemoving(old_entry); OnSpeedDialAdded(new_entry); } BOOL ExtensionSpeedDialHandler::HandleAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_GET_ACTION_STATE: { OpInputAction* child_action = action->GetChildAction(); switch (child_action->GetAction()) { case OpInputAction::ACTION_SHOW_SPEEDDIAL_EXTENSION_OPTIONS: { const DesktopSpeedDial* entry = g_speeddial_manager->GetSpeedDial(*child_action); if (entry != NULL) { OP_ASSERT(entry->GetExtensionWUID().HasContent()); child_action->SetEnabled(g_desktop_extensions_manager->CanShowOptionsPage( entry->GetExtensionWUID())); } return TRUE; } } break; } case OpInputAction::ACTION_DISABLE_SPEEDDIAL_EXTENSION: const DesktopSpeedDial* entry = g_speeddial_manager->GetSpeedDial(*action); if (entry != NULL) { OP_ASSERT(entry->GetExtensionWUID().HasContent()); OpStatus::Ignore(g_desktop_extensions_manager->DisableExtension( entry->GetExtensionWUID())); } return TRUE; } return FALSE; } OP_STATUS ExtensionSpeedDialHandler::AddSpeedDial(OpGadget& gadget) { if (!g_speeddial_manager->GetTotalCount()) { return OpStatus::ERR; } SpeedDialData extension; RETURN_IF_ERROR(extension.SetURL(gadget.GetAttribute(WIDGET_EXTENSION_SPEEDDIAL_URL))); RETURN_IF_ERROR(extension.SetTitle(gadget.GetAttribute(WIDGET_EXTENSION_SPEEDDIAL_TITLE), FALSE)); RETURN_IF_ERROR(extension.SetExtensionID(gadget.GetIdentifier())); RETURN_IF_ERROR(g_speeddial_manager->InsertSpeedDial(g_speeddial_manager->GetTotalCount() - 1, &extension)); return OpStatus::OK; } INT32 ExtensionSpeedDialHandler::FindSpeedDial(const OpGadget& extension) { // Match by WUID first. for (unsigned i = 0; i < g_speeddial_manager->GetTotalCount(); ++i) { const DesktopSpeedDial* sd = g_speeddial_manager->GetSpeedDial(i); if (sd->GetExtensionWUID() == const_cast<OpGadget&>(extension).GetIdentifier()) return i; } // Match by the global ID next. for (unsigned i = 0; i < g_speeddial_manager->GetTotalCount(); ++i) { const DesktopSpeedDial* sd = g_speeddial_manager->GetSpeedDial(i); if (sd->GetExtensionWUID().HasContent()) continue; OpStringC gid = sd->GetExtensionID(); // Only successful if config.xml actually specifies an ID. if (gid.HasContent() && gid == const_cast<OpGadget&>(extension).GetGadgetId()) return i; } return -1; } void ExtensionSpeedDialHandler::AnimateInSpeedDial(const OpGadget& gadget) { if (ShouldShowInSpeedDial(gadget)) { ShowNewExtension(gadget); } } bool ExtensionSpeedDialHandler::ShouldShowInSpeedDial(const OpGadget& extension) { return ExtensionUtils::RequestsSpeedDialWindow(*const_cast<OpGadget&>(extension).GetClass()) && OpStringC(const_cast<OpGadget&>(extension).GetGadgetId()).HasContent(); } void ExtensionSpeedDialHandler::ShowNewExtension(const OpGadget& extension) { if (!g_application || !g_application->GetActiveBrowserDesktopWindow()) { return; } switch (g_speeddial_manager->GetState()) { case SpeedDialManager::Shown: case SpeedDialManager::ReadOnly: break; default: return; } DocumentDesktopWindow* sd_window = NULL; DocumentView* doc_view = NULL; // Find the Speed Dial window that was focused last. OpWorkspace* workspace = g_application->GetActiveBrowserDesktopWindow()->GetWorkspace(); for (INT32 i = 0; i < workspace->GetDesktopWindowCount(); ++i) { DesktopWindow* window = workspace->GetDesktopWindowFromStack(i); if (window->GetType() == OpTypedObject::WINDOW_TYPE_DOCUMENT) { DocumentDesktopWindow* document_window = static_cast<DocumentDesktopWindow*>(window); doc_view = document_window->GetDocumentViewFromType(DocumentView::DOCUMENT_TYPE_SPEED_DIAL); if (doc_view) { sd_window = document_window; break; } } } if (sd_window == NULL) { // Need a new Speed Dial window. g_application->GetBrowserDesktopWindow(g_application->IsSDI(), FALSE, TRUE, &sd_window); OP_ASSERT(sd_window != NULL); } const INT32 pos = FindSpeedDial(extension); OP_ASSERT(pos >= 0); sd_window->Activate(); if (doc_view) static_cast<OpSpeedDialView*>(doc_view->GetOpWidget())->ShowThumbnail(pos); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef DEVICE_API_ORIENTATION_MANAGER_H #define DEVICE_API_ORIENTATION_MANAGER_H #ifdef DAPI_ORIENTATION_MANAGER_SUPPORT #include "modules/device_api/OpListenable.h" #include "modules/pi/device_api/OpSensor.h" #include "modules/hardcore/timer/optimer.h" #include "modules/prefs/prefsmanager/opprefslistener.h" class ST_device_j7uhsb_ionmanager; /** Listener interface for orientation events */ class OpOrientationListener { public: /** @see OpOrientationData. */ struct Data{ double alpha; double beta; double gamma; bool absolute; }; /** Called when there is a significant change in devices physical orientation. */ virtual void OnOrientationChange(const Data& data) = 0; /** Called whenever the sensor notifies about need of calibration. * The Listener MUST respond by calling OrientationManager::CompassCalibrationReply(). * was_handled parameter must be set to TRUE if the listener handles calibration * and doesn't want platform to provide the default calibration method. Else * if the listeners doesn't want to prevent this default behaviour it should * call OrientationManager::CompassCalibrationReply() with was_handled == FALSE. */ virtual void OnCompassNeedsCalibration() = 0; virtual ~OpOrientationListener() {} }; /** Listener interface for motion events */ class OpMotionListener { public: struct Data{ double x; double y; double z; double x_with_gravity; double y_with_gravity; double z_with_gravity; double rotation_alpha; double rotation_beta; double rotation_gamma; double interval; }; virtual void OnAccelerationChange(const Data& data) = 0; virtual ~OpMotionListener() {} }; /** * Utility class responsible for Handling the lifetime of platrorm * sensors and forwarding the orientation/motion data to listeners. */ class OrientationManager : public OpListenable<OpOrientationListener> , public OpListenable<OpMotionListener> , public OpSensorListener , public OpTimerListener , public OpPrefsListener { public: static OP_STATUS Make(OrientationManager*& new_manager); virtual ~OrientationManager(); /** Attaches the listener for Orientation events. * Attaching the first listener will try to enable * platform sensor implementation. */ OP_STATUS AttachOrientationListener(OpOrientationListener* listener); /** Attaches the listener for Motion events. * Attaching the first listener will try to enable * platform sensor implementation. */ OP_STATUS AttachMotionListener(OpMotionListener* listener); /** Detaches the listener for Orientation events. * Detaching the last listener will schedule disabling * the platform sensors asynchronously. */ OP_STATUS DetachOrientationListener(OpOrientationListener* listener); /** Detaches the listener for Motion events. * Detaching the last listener will schedule disabling * the platform sensors asynchronously. */ OP_STATUS DetachMotionListener(OpMotionListener* listener); /** Called by OpOrientationListener as a reply to OnCompassNeedsCalibration. * * @note If this function is called with listener parameter which is not * a listener expected to call this then it will be ignored. For * example it is always safe to call: * g_DAPI_orientationManager->CompassCalibrationReply(listener, FALSE); * when unataching/destroying listener to make sure there is no * outstanding request. * @param listener listener which responds to OnCompassNeedsCalibration. * @param was_handled - if TRUE then the listener has successfully handled * calibration and OpSensorCalibrationListener::OnSensorCalibrationRequest() * should not be called to perform calibration. */ void CompassCalibrationReply(OpOrientationListener* listener, BOOL was_handled); #ifdef SELFTEST /** Simulates compass needs calibration. * For debugging purposes only. */ void TriggerCompassNeedsCalibration(); #endif // SELFTEST private: // from OpSensorListener virtual void OnNewData(OpSensor* sensor, const OpSensorData* value); virtual void OnSensorNeedsCalibration(OpSensor* sensor); virtual void OnSensorDestroyed(const OpSensor* sensor); // from OpTimerListener virtual void OnTimeOut(OpTimer* timer); // from OpPrefsListener virtual void PrefChanged(OpPrefsCollection::Collections /* id */, int /* pref */, int /* newvalue */); OrientationManager(); DECLARE_LISTENABLE_EVENT1(OpOrientationListener, OrientationChange, const OpOrientationListener::Data&); DECLARE_LISTENABLE_EVENT0(OpOrientationListener, CompassNeedsCalibration); DECLARE_LISTENABLE_EVENT1(OpMotionListener, AccelerationChange, const OpMotionListener::Data); BOOL IsOrientationSensorInitialized() { return m_orientation_sensor ? TRUE : FALSE; } BOOL IsMotionSensorInitialized() { return m_acceleration_sensor || m_acceleration_with_gravity_sensor || m_rotation_speed_sensor; } BOOL IsOrientationEnabled(); /** Checks whether platform sensor event should trigger * OrientationManager event. The algorithm for this is: * 1) if this is orientation sensor event then return TRUE. * 2) else if it is most important of available motion sensors return TRUE. * (the precedence of sensors is : LINEAR_ACCELERATION > ACCELERATION(with gravity) > ROTATION) * 3) else return FALSE. * @param type - type of a sensor event. * @param[out] orientation - set to TRUE if this is orientation event. */ BOOL ShouldDataTriggerEvent(OpSensorType type, BOOL &orientation); /** Calculates the difference between two angles(or any ther periodic value). * This includes periodicity so for example the diff between * 350 and 10 deg is correctly 20 deg. * @param last last angle * @param first first angle * @param period - the period above which the values overflow. */ static double AngleDiff(double last, double first, double period); double AngleDiffFull(const OpSensorData& cur_data); OP_STATUS StartSensor(OpSensorType type); void StopSensor(OpSensorType type); /// Gets the reference to a sensor for a given type OpSensor*& GetSensorForType(OpSensorType type); /// Gets the reference to the last cached sensor data for a given type OpSensorData& GetLastSensorDataForType(OpSensorType type); OpSensor* m_orientation_sensor; OpSensor* m_acceleration_sensor; OpSensor* m_acceleration_with_gravity_sensor; OpSensor* m_rotation_speed_sensor; OpSensorData m_last_acceleration_data; OpSensorData m_last_acceleration_with_gravity_data; OpSensorData m_last_orientation_data; OpSensorData m_last_rotation_speed_data; void InitSensorData(OpSensorData& data, OpSensorType type); void ScheduleEmptyEvent(BOOL orientation); void ScheduleCleanup(); void Cleanup(); OpTimer m_cleanup_timer; OpTimer m_empty_orientation_event_timer; OpTimer m_empty_motion_event_timer; #ifdef SELFTEST friend class ST_device_j7uhsb_ionmanager; /// If this flag is set the orientation manager will always use Mock PI instead of normal ones BOOL m_force_use_mock_sensors; #endif //SELFTEST OpVector<void> m_compass_calibration_replies_pending; BOOL m_compass_calibration_handled; }; #endif // DAPI_ORIENTATION_MANAGER_SUPPORT #endif //DEVICE_API_ORIENTATION_MANAGER_H
// Created on: 1999-06-25 // Created by: Sergey RUIN // Copyright (c) 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 _TDataStd_Directory_HeaderFile #define _TDataStd_Directory_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TDataStd_GenericEmpty.hxx> #include <Standard_Boolean.hxx> #include <Standard_OStream.hxx> class TDF_Label; class Standard_GUID; class TDataStd_Directory; DEFINE_STANDARD_HANDLE(TDataStd_Directory, TDataStd_GenericEmpty) //! Associates a directory in the data framework with //! a TDataStd_TagSource attribute. //! You can create a new directory label and add //! sub-directory or object labels to it, class TDataStd_Directory : public TDataStd_GenericEmpty { public: //! class methods //! ============= //! Searches for a directory attribute on the label //! current, or on one of the father labels of current. //! If a directory attribute is found, true is returned, //! and the attribute found is set as D. Standard_EXPORT static Standard_Boolean Find (const TDF_Label& current, Handle(TDataStd_Directory)& D); //! Creates an empty Directory attribute, located at //! <label>. Raises if <label> has attribute Standard_EXPORT static Handle(TDataStd_Directory) New (const TDF_Label& label); //! Creates a new sub-label and sets the //! sub-directory dir on that label. Standard_EXPORT static Handle(TDataStd_Directory) AddDirectory (const Handle(TDataStd_Directory)& dir); //! Makes new label and returns it to insert //! other object attributes (sketch,part...etc...) Standard_EXPORT static TDF_Label MakeObjectLabel (const Handle(TDataStd_Directory)& dir); //! Directory methods //! =============== Standard_EXPORT static const Standard_GUID& GetID(); Standard_EXPORT TDataStd_Directory(); Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE; Standard_EXPORT virtual Standard_OStream& Dump (Standard_OStream& anOS) const Standard_OVERRIDE; DEFINE_DERIVED_ATTRIBUTE(TDataStd_Directory,TDataStd_GenericEmpty) protected: private: }; #endif // _TDataStd_Directory_HeaderFile
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "FirstPersonProject.h" #include "FirstPersonProjectGameMode.h" #include "FirstPersonProjectHUD.h" #include "FirstPersonProjectCharacter.h" AFirstPersonProjectGameMode::AFirstPersonProjectGameMode() : Super() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnClassFinder(TEXT("/Game/FirstPersonCPP/Blueprints/FirstPersonCharacter")); DefaultPawnClass = PlayerPawnClassFinder.Class; // use our custom HUD class HUDClass = AFirstPersonProjectHUD::StaticClass(); }
#include"conio.h" #include"stdio.h" void main(void) { int a,b,c,pow=1; clrscr(); printf("Enter number = "); scanf("%d",&a); printf("Enter power = "); scanf("%d",&b); for(c=1; c<=b; c++) pow=pow*a; printf("%d",pow); getch(); }
#ifndef REACTOR_REDIS_SERVER_H #define REACTOR_REDIS_SERVER_H #include "reactor/net/TcpServer.h" namespace reactor { class RedisServer { public: RedisServer(EventLoop *loop, InetAddress addr): server_(loop, addr) { } void start() { server_.start(); } private: net::TcpServer server_; }; } #endif
#include "miniTimer.h" miniTimer::miniTimer(void) { } miniTimer::~miniTimer(void) { }